View.java revision b49f446c98096c4790a11d9b5bc83a4e585278c9
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.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.ClipData;
23import android.content.Context;
24import android.content.res.Configuration;
25import android.content.res.Resources;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.Camera;
29import android.graphics.Canvas;
30import android.graphics.Insets;
31import android.graphics.Interpolator;
32import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Outline;
35import android.graphics.Paint;
36import android.graphics.Path;
37import android.graphics.PixelFormat;
38import android.graphics.Point;
39import android.graphics.PorterDuff;
40import android.graphics.PorterDuffXfermode;
41import android.graphics.Rect;
42import android.graphics.RectF;
43import android.graphics.Region;
44import android.graphics.Shader;
45import android.graphics.drawable.ColorDrawable;
46import android.graphics.drawable.Drawable;
47import android.hardware.display.DisplayManagerGlobal;
48import android.os.Bundle;
49import android.os.Handler;
50import android.os.IBinder;
51import android.os.Parcel;
52import android.os.Parcelable;
53import android.os.RemoteException;
54import android.os.SystemClock;
55import android.os.SystemProperties;
56import android.text.TextUtils;
57import android.util.AttributeSet;
58import android.util.FloatProperty;
59import android.util.LayoutDirection;
60import android.util.Log;
61import android.util.LongSparseLongArray;
62import android.util.Pools.SynchronizedPool;
63import android.util.Property;
64import android.util.SparseArray;
65import android.util.SuperNotCalledException;
66import android.util.TypedValue;
67import android.view.ContextMenu.ContextMenuInfo;
68import android.view.AccessibilityIterators.TextSegmentIterator;
69import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
70import android.view.AccessibilityIterators.WordTextSegmentIterator;
71import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
72import android.view.accessibility.AccessibilityEvent;
73import android.view.accessibility.AccessibilityEventSource;
74import android.view.accessibility.AccessibilityManager;
75import android.view.accessibility.AccessibilityNodeInfo;
76import android.view.accessibility.AccessibilityNodeProvider;
77import android.view.animation.Animation;
78import android.view.animation.AnimationUtils;
79import android.view.animation.Transformation;
80import android.view.inputmethod.EditorInfo;
81import android.view.inputmethod.InputConnection;
82import android.view.inputmethod.InputMethodManager;
83import android.widget.ScrollBarDrawable;
84
85import static android.os.Build.VERSION_CODES.*;
86import static java.lang.Math.max;
87
88import com.android.internal.R;
89import com.android.internal.util.Predicate;
90import com.android.internal.view.menu.MenuBuilder;
91import com.google.android.collect.Lists;
92import com.google.android.collect.Maps;
93
94import java.lang.annotation.Retention;
95import java.lang.annotation.RetentionPolicy;
96import java.lang.ref.WeakReference;
97import java.lang.reflect.Field;
98import java.lang.reflect.InvocationTargetException;
99import java.lang.reflect.Method;
100import java.lang.reflect.Modifier;
101import java.util.ArrayList;
102import java.util.Arrays;
103import java.util.Collections;
104import java.util.HashMap;
105import java.util.List;
106import java.util.Locale;
107import java.util.Map;
108import java.util.concurrent.CopyOnWriteArrayList;
109import java.util.concurrent.atomic.AtomicInteger;
110
111/**
112 * <p>
113 * This class represents the basic building block for user interface components. A View
114 * occupies a rectangular area on the screen and is responsible for drawing and
115 * event handling. View is the base class for <em>widgets</em>, which are
116 * used to create interactive UI components (buttons, text fields, etc.). The
117 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
118 * are invisible containers that hold other Views (or other ViewGroups) and define
119 * their layout properties.
120 * </p>
121 *
122 * <div class="special reference">
123 * <h3>Developer Guides</h3>
124 * <p>For information about using this class to develop your application's user interface,
125 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
126 * </div>
127 *
128 * <a name="Using"></a>
129 * <h3>Using Views</h3>
130 * <p>
131 * All of the views in a window are arranged in a single tree. You can add views
132 * either from code or by specifying a tree of views in one or more XML layout
133 * files. There are many specialized subclasses of views that act as controls or
134 * are capable of displaying text, images, or other content.
135 * </p>
136 * <p>
137 * Once you have created a tree of views, there are typically a few types of
138 * common operations you may wish to perform:
139 * <ul>
140 * <li><strong>Set properties:</strong> for example setting the text of a
141 * {@link android.widget.TextView}. The available properties and the methods
142 * that set them will vary among the different subclasses of views. Note that
143 * properties that are known at build time can be set in the XML layout
144 * files.</li>
145 * <li><strong>Set focus:</strong> The framework will handled moving focus in
146 * response to user input. To force focus to a specific view, call
147 * {@link #requestFocus}.</li>
148 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
149 * that will be notified when something interesting happens to the view. For
150 * example, all views will let you set a listener to be notified when the view
151 * gains or loses focus. You can register such a listener using
152 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
153 * Other view subclasses offer more specialized listeners. For example, a Button
154 * exposes a listener to notify clients when the button is clicked.</li>
155 * <li><strong>Set visibility:</strong> You can hide or show views using
156 * {@link #setVisibility(int)}.</li>
157 * </ul>
158 * </p>
159 * <p><em>
160 * Note: The Android framework is responsible for measuring, laying out and
161 * drawing views. You should not call methods that perform these actions on
162 * views yourself unless you are actually implementing a
163 * {@link android.view.ViewGroup}.
164 * </em></p>
165 *
166 * <a name="Lifecycle"></a>
167 * <h3>Implementing a Custom View</h3>
168 *
169 * <p>
170 * To implement a custom view, you will usually begin by providing overrides for
171 * some of the standard methods that the framework calls on all views. You do
172 * not need to override all of these methods. In fact, you can start by just
173 * overriding {@link #onDraw(android.graphics.Canvas)}.
174 * <table border="2" width="85%" align="center" cellpadding="5">
175 *     <thead>
176 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
177 *     </thead>
178 *
179 *     <tbody>
180 *     <tr>
181 *         <td rowspan="2">Creation</td>
182 *         <td>Constructors</td>
183 *         <td>There is a form of the constructor that are called when the view
184 *         is created from code and a form that is called when the view is
185 *         inflated from a layout file. The second form should parse and apply
186 *         any attributes defined in the layout file.
187 *         </td>
188 *     </tr>
189 *     <tr>
190 *         <td><code>{@link #onFinishInflate()}</code></td>
191 *         <td>Called after a view and all of its children has been inflated
192 *         from XML.</td>
193 *     </tr>
194 *
195 *     <tr>
196 *         <td rowspan="3">Layout</td>
197 *         <td><code>{@link #onMeasure(int, int)}</code></td>
198 *         <td>Called to determine the size requirements for this view and all
199 *         of its children.
200 *         </td>
201 *     </tr>
202 *     <tr>
203 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
204 *         <td>Called when this view should assign a size and position to all
205 *         of its children.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
210 *         <td>Called when the size of this view has changed.
211 *         </td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td>Drawing</td>
216 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
217 *         <td>Called when the view should render its content.
218 *         </td>
219 *     </tr>
220 *
221 *     <tr>
222 *         <td rowspan="4">Event processing</td>
223 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
224 *         <td>Called when a new hardware key event occurs.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
229 *         <td>Called when a hardware key up event occurs.
230 *         </td>
231 *     </tr>
232 *     <tr>
233 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
234 *         <td>Called when a trackball motion event occurs.
235 *         </td>
236 *     </tr>
237 *     <tr>
238 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
239 *         <td>Called when a touch screen motion event occurs.
240 *         </td>
241 *     </tr>
242 *
243 *     <tr>
244 *         <td rowspan="2">Focus</td>
245 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
246 *         <td>Called when the view gains or loses focus.
247 *         </td>
248 *     </tr>
249 *
250 *     <tr>
251 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
252 *         <td>Called when the window containing the view gains or loses focus.
253 *         </td>
254 *     </tr>
255 *
256 *     <tr>
257 *         <td rowspan="3">Attaching</td>
258 *         <td><code>{@link #onAttachedToWindow()}</code></td>
259 *         <td>Called when the view is attached to a window.
260 *         </td>
261 *     </tr>
262 *
263 *     <tr>
264 *         <td><code>{@link #onDetachedFromWindow}</code></td>
265 *         <td>Called when the view is detached from its window.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
271 *         <td>Called when the visibility of the window containing the view
272 *         has changed.
273 *         </td>
274 *     </tr>
275 *     </tbody>
276 *
277 * </table>
278 * </p>
279 *
280 * <a name="IDs"></a>
281 * <h3>IDs</h3>
282 * Views may have an integer id associated with them. These ids are typically
283 * assigned in the layout XML files, and are used to find specific views within
284 * the view tree. A common pattern is to:
285 * <ul>
286 * <li>Define a Button in the layout file and assign it a unique ID.
287 * <pre>
288 * &lt;Button
289 *     android:id="@+id/my_button"
290 *     android:layout_width="wrap_content"
291 *     android:layout_height="wrap_content"
292 *     android:text="@string/my_button_text"/&gt;
293 * </pre></li>
294 * <li>From the onCreate method of an Activity, find the Button
295 * <pre class="prettyprint">
296 *      Button myButton = (Button) findViewById(R.id.my_button);
297 * </pre></li>
298 * </ul>
299 * <p>
300 * View IDs need not be unique throughout the tree, but it is good practice to
301 * ensure that they are at least unique within the part of the tree you are
302 * searching.
303 * </p>
304 *
305 * <a name="Position"></a>
306 * <h3>Position</h3>
307 * <p>
308 * The geometry of a view is that of a rectangle. A view has a location,
309 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
310 * two dimensions, expressed as a width and a height. The unit for location
311 * and dimensions is the pixel.
312 * </p>
313 *
314 * <p>
315 * It is possible to retrieve the location of a view by invoking the methods
316 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
317 * coordinate of the rectangle representing the view. The latter returns the
318 * top, or Y, coordinate of the rectangle representing the view. These methods
319 * both return the location of the view relative to its parent. For instance,
320 * when getLeft() returns 20, that means the view is located 20 pixels to the
321 * right of the left edge of its direct parent.
322 * </p>
323 *
324 * <p>
325 * In addition, several convenience methods are offered to avoid unnecessary
326 * computations, namely {@link #getRight()} and {@link #getBottom()}.
327 * These methods return the coordinates of the right and bottom edges of the
328 * rectangle representing the view. For instance, calling {@link #getRight()}
329 * is similar to the following computation: <code>getLeft() + getWidth()</code>
330 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
331 * </p>
332 *
333 * <a name="SizePaddingMargins"></a>
334 * <h3>Size, padding and margins</h3>
335 * <p>
336 * The size of a view is expressed with a width and a height. A view actually
337 * possess two pairs of width and height values.
338 * </p>
339 *
340 * <p>
341 * The first pair is known as <em>measured width</em> and
342 * <em>measured height</em>. These dimensions define how big a view wants to be
343 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
344 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
345 * and {@link #getMeasuredHeight()}.
346 * </p>
347 *
348 * <p>
349 * The second pair is simply known as <em>width</em> and <em>height</em>, or
350 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
351 * dimensions define the actual size of the view on screen, at drawing time and
352 * after layout. These values may, but do not have to, be different from the
353 * measured width and height. The width and height can be obtained by calling
354 * {@link #getWidth()} and {@link #getHeight()}.
355 * </p>
356 *
357 * <p>
358 * To measure its dimensions, a view takes into account its padding. The padding
359 * is expressed in pixels for the left, top, right and bottom parts of the view.
360 * Padding can be used to offset the content of the view by a specific amount of
361 * pixels. For instance, a left padding of 2 will push the view's content by
362 * 2 pixels to the right of the left edge. Padding can be set using the
363 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
364 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
365 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
366 * {@link #getPaddingEnd()}.
367 * </p>
368 *
369 * <p>
370 * Even though a view can define a padding, it does not provide any support for
371 * margins. However, view groups provide such a support. Refer to
372 * {@link android.view.ViewGroup} and
373 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
374 * </p>
375 *
376 * <a name="Layout"></a>
377 * <h3>Layout</h3>
378 * <p>
379 * Layout is a two pass process: a measure pass and a layout pass. The measuring
380 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
381 * of the view tree. Each view pushes dimension specifications down the tree
382 * during the recursion. At the end of the measure pass, every view has stored
383 * its measurements. The second pass happens in
384 * {@link #layout(int,int,int,int)} and is also top-down. During
385 * this pass each parent is responsible for positioning all of its children
386 * using the sizes computed in the measure pass.
387 * </p>
388 *
389 * <p>
390 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
391 * {@link #getMeasuredHeight()} values must be set, along with those for all of
392 * that view's descendants. A view's measured width and measured height values
393 * must respect the constraints imposed by the view's parents. This guarantees
394 * that at the end of the measure pass, all parents accept all of their
395 * children's measurements. A parent view may call measure() more than once on
396 * its children. For example, the parent may measure each child once with
397 * unspecified dimensions to find out how big they want to be, then call
398 * measure() on them again with actual numbers if the sum of all the children's
399 * unconstrained sizes is too big or too small.
400 * </p>
401 *
402 * <p>
403 * The measure pass uses two classes to communicate dimensions. The
404 * {@link MeasureSpec} class is used by views to tell their parents how they
405 * want to be measured and positioned. The base LayoutParams class just
406 * describes how big the view wants to be for both width and height. For each
407 * dimension, it can specify one of:
408 * <ul>
409 * <li> an exact number
410 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
411 * (minus padding)
412 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
413 * enclose its content (plus padding).
414 * </ul>
415 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
416 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
417 * an X and Y value.
418 * </p>
419 *
420 * <p>
421 * MeasureSpecs are used to push requirements down the tree from parent to
422 * child. A MeasureSpec can be in one of three modes:
423 * <ul>
424 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
425 * of a child view. For example, a LinearLayout may call measure() on its child
426 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
427 * tall the child view wants to be given a width of 240 pixels.
428 * <li>EXACTLY: This is used by the parent to impose an exact size on the
429 * child. The child must use this size, and guarantee that all of its
430 * descendants will fit within this size.
431 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
432 * child. The child must gurantee that it and all of its descendants will fit
433 * within this size.
434 * </ul>
435 * </p>
436 *
437 * <p>
438 * To intiate a layout, call {@link #requestLayout}. This method is typically
439 * called by a view on itself when it believes that is can no longer fit within
440 * its current bounds.
441 * </p>
442 *
443 * <a name="Drawing"></a>
444 * <h3>Drawing</h3>
445 * <p>
446 * Drawing is handled by walking the tree and rendering each view that
447 * intersects the invalid region. Because the tree is traversed in-order,
448 * this means that parents will draw before (i.e., behind) their children, with
449 * siblings drawn in the order they appear in the tree.
450 * If you set a background drawable for a View, then the View will draw it for you
451 * before calling back to its <code>onDraw()</code> method.
452 * </p>
453 *
454 * <p>
455 * Note that the framework will not draw views that are not in the invalid region.
456 * </p>
457 *
458 * <p>
459 * To force a view to draw, call {@link #invalidate()}.
460 * </p>
461 *
462 * <a name="EventHandlingThreading"></a>
463 * <h3>Event Handling and Threading</h3>
464 * <p>
465 * The basic cycle of a view is as follows:
466 * <ol>
467 * <li>An event comes in and is dispatched to the appropriate view. The view
468 * handles the event and notifies any listeners.</li>
469 * <li>If in the course of processing the event, the view's bounds may need
470 * to be changed, the view will call {@link #requestLayout()}.</li>
471 * <li>Similarly, if in the course of processing the event the view's appearance
472 * may need to be changed, the view will call {@link #invalidate()}.</li>
473 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
474 * the framework will take care of measuring, laying out, and drawing the tree
475 * as appropriate.</li>
476 * </ol>
477 * </p>
478 *
479 * <p><em>Note: The entire view tree is single threaded. You must always be on
480 * the UI thread when calling any method on any view.</em>
481 * If you are doing work on other threads and want to update the state of a view
482 * from that thread, you should use a {@link Handler}.
483 * </p>
484 *
485 * <a name="FocusHandling"></a>
486 * <h3>Focus Handling</h3>
487 * <p>
488 * The framework will handle routine focus movement in response to user input.
489 * This includes changing the focus as views are removed or hidden, or as new
490 * views become available. Views indicate their willingness to take focus
491 * through the {@link #isFocusable} method. To change whether a view can take
492 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
493 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
494 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
495 * </p>
496 * <p>
497 * Focus movement is based on an algorithm which finds the nearest neighbor in a
498 * given direction. In rare cases, the default algorithm may not match the
499 * intended behavior of the developer. In these situations, you can provide
500 * explicit overrides by using these XML attributes in the layout file:
501 * <pre>
502 * nextFocusDown
503 * nextFocusLeft
504 * nextFocusRight
505 * nextFocusUp
506 * </pre>
507 * </p>
508 *
509 *
510 * <p>
511 * To get a particular view to take focus, call {@link #requestFocus()}.
512 * </p>
513 *
514 * <a name="TouchMode"></a>
515 * <h3>Touch Mode</h3>
516 * <p>
517 * When a user is navigating a user interface via directional keys such as a D-pad, it is
518 * necessary to give focus to actionable items such as buttons so the user can see
519 * what will take input.  If the device has touch capabilities, however, and the user
520 * begins interacting with the interface by touching it, it is no longer necessary to
521 * always highlight, or give focus to, a particular view.  This motivates a mode
522 * for interaction named 'touch mode'.
523 * </p>
524 * <p>
525 * For a touch capable device, once the user touches the screen, the device
526 * will enter touch mode.  From this point onward, only views for which
527 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
528 * Other views that are touchable, like buttons, will not take focus when touched; they will
529 * only fire the on click listeners.
530 * </p>
531 * <p>
532 * Any time a user hits a directional key, such as a D-pad direction, the view device will
533 * exit touch mode, and find a view to take focus, so that the user may resume interacting
534 * with the user interface without touching the screen again.
535 * </p>
536 * <p>
537 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
538 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
539 * </p>
540 *
541 * <a name="Scrolling"></a>
542 * <h3>Scrolling</h3>
543 * <p>
544 * The framework provides basic support for views that wish to internally
545 * scroll their content. This includes keeping track of the X and Y scroll
546 * offset as well as mechanisms for drawing scrollbars. See
547 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
548 * {@link #awakenScrollBars()} for more details.
549 * </p>
550 *
551 * <a name="Tags"></a>
552 * <h3>Tags</h3>
553 * <p>
554 * Unlike IDs, tags are not used to identify views. Tags are essentially an
555 * extra piece of information that can be associated with a view. They are most
556 * often used as a convenience to store data related to views in the views
557 * themselves rather than by putting them in a separate structure.
558 * </p>
559 *
560 * <a name="Properties"></a>
561 * <h3>Properties</h3>
562 * <p>
563 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
564 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
565 * available both in the {@link Property} form as well as in similarly-named setter/getter
566 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
567 * be used to set persistent state associated with these rendering-related properties on the view.
568 * The properties and methods can also be used in conjunction with
569 * {@link android.animation.Animator Animator}-based animations, described more in the
570 * <a href="#Animation">Animation</a> section.
571 * </p>
572 *
573 * <a name="Animation"></a>
574 * <h3>Animation</h3>
575 * <p>
576 * Starting with Android 3.0, the preferred way of animating views is to use the
577 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
578 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
579 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
580 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
581 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
582 * makes animating these View properties particularly easy and efficient.
583 * </p>
584 * <p>
585 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
586 * You can attach an {@link Animation} object to a view using
587 * {@link #setAnimation(Animation)} or
588 * {@link #startAnimation(Animation)}. The animation can alter the scale,
589 * rotation, translation and alpha of a view over time. If the animation is
590 * attached to a view that has children, the animation will affect the entire
591 * subtree rooted by that node. When an animation is started, the framework will
592 * take care of redrawing the appropriate views until the animation completes.
593 * </p>
594 *
595 * <a name="Security"></a>
596 * <h3>Security</h3>
597 * <p>
598 * Sometimes it is essential that an application be able to verify that an action
599 * is being performed with the full knowledge and consent of the user, such as
600 * granting a permission request, making a purchase or clicking on an advertisement.
601 * Unfortunately, a malicious application could try to spoof the user into
602 * performing these actions, unaware, by concealing the intended purpose of the view.
603 * As a remedy, the framework offers a touch filtering mechanism that can be used to
604 * improve the security of views that provide access to sensitive functionality.
605 * </p><p>
606 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
607 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
608 * will discard touches that are received whenever the view's window is obscured by
609 * another visible window.  As a result, the view will not receive touches whenever a
610 * toast, dialog or other window appears above the view's window.
611 * </p><p>
612 * For more fine-grained control over security, consider overriding the
613 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
614 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
615 * </p>
616 *
617 * @attr ref android.R.styleable#View_alpha
618 * @attr ref android.R.styleable#View_background
619 * @attr ref android.R.styleable#View_clickable
620 * @attr ref android.R.styleable#View_contentDescription
621 * @attr ref android.R.styleable#View_drawingCacheQuality
622 * @attr ref android.R.styleable#View_duplicateParentState
623 * @attr ref android.R.styleable#View_id
624 * @attr ref android.R.styleable#View_requiresFadingEdge
625 * @attr ref android.R.styleable#View_fadeScrollbars
626 * @attr ref android.R.styleable#View_fadingEdgeLength
627 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
628 * @attr ref android.R.styleable#View_fitsSystemWindows
629 * @attr ref android.R.styleable#View_isScrollContainer
630 * @attr ref android.R.styleable#View_focusable
631 * @attr ref android.R.styleable#View_focusableInTouchMode
632 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
633 * @attr ref android.R.styleable#View_keepScreenOn
634 * @attr ref android.R.styleable#View_layerType
635 * @attr ref android.R.styleable#View_layoutDirection
636 * @attr ref android.R.styleable#View_longClickable
637 * @attr ref android.R.styleable#View_minHeight
638 * @attr ref android.R.styleable#View_minWidth
639 * @attr ref android.R.styleable#View_nextFocusDown
640 * @attr ref android.R.styleable#View_nextFocusLeft
641 * @attr ref android.R.styleable#View_nextFocusRight
642 * @attr ref android.R.styleable#View_nextFocusUp
643 * @attr ref android.R.styleable#View_onClick
644 * @attr ref android.R.styleable#View_padding
645 * @attr ref android.R.styleable#View_paddingBottom
646 * @attr ref android.R.styleable#View_paddingLeft
647 * @attr ref android.R.styleable#View_paddingRight
648 * @attr ref android.R.styleable#View_paddingTop
649 * @attr ref android.R.styleable#View_paddingStart
650 * @attr ref android.R.styleable#View_paddingEnd
651 * @attr ref android.R.styleable#View_saveEnabled
652 * @attr ref android.R.styleable#View_rotation
653 * @attr ref android.R.styleable#View_rotationX
654 * @attr ref android.R.styleable#View_rotationY
655 * @attr ref android.R.styleable#View_scaleX
656 * @attr ref android.R.styleable#View_scaleY
657 * @attr ref android.R.styleable#View_scrollX
658 * @attr ref android.R.styleable#View_scrollY
659 * @attr ref android.R.styleable#View_scrollbarSize
660 * @attr ref android.R.styleable#View_scrollbarStyle
661 * @attr ref android.R.styleable#View_scrollbars
662 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
663 * @attr ref android.R.styleable#View_scrollbarFadeDuration
664 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
665 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
666 * @attr ref android.R.styleable#View_scrollbarThumbVertical
667 * @attr ref android.R.styleable#View_scrollbarTrackVertical
668 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
670 * @attr ref android.R.styleable#View_sharedElementName
671 * @attr ref android.R.styleable#View_soundEffectsEnabled
672 * @attr ref android.R.styleable#View_tag
673 * @attr ref android.R.styleable#View_textAlignment
674 * @attr ref android.R.styleable#View_textDirection
675 * @attr ref android.R.styleable#View_transformPivotX
676 * @attr ref android.R.styleable#View_transformPivotY
677 * @attr ref android.R.styleable#View_translationX
678 * @attr ref android.R.styleable#View_translationY
679 * @attr ref android.R.styleable#View_translationZ
680 * @attr ref android.R.styleable#View_visibility
681 *
682 * @see android.view.ViewGroup
683 */
684public class View implements Drawable.Callback, KeyEvent.Callback,
685        AccessibilityEventSource {
686    private static final boolean DBG = false;
687
688    /**
689     * The logging tag used by this class with android.util.Log.
690     */
691    protected static final String VIEW_LOG_TAG = "View";
692
693    /**
694     * When set to true, apps will draw debugging information about their layouts.
695     *
696     * @hide
697     */
698    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
699
700    /**
701     * Used to mark a View that has no ID.
702     */
703    public static final int NO_ID = -1;
704
705    /**
706     * Signals that compatibility booleans have been initialized according to
707     * target SDK versions.
708     */
709    private static boolean sCompatibilityDone = false;
710
711    /**
712     * Use the old (broken) way of building MeasureSpecs.
713     */
714    private static boolean sUseBrokenMakeMeasureSpec = false;
715
716    /**
717     * Ignore any optimizations using the measure cache.
718     */
719    private static boolean sIgnoreMeasureCache = false;
720
721    /**
722     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
723     * calling setFlags.
724     */
725    private static final int NOT_FOCUSABLE = 0x00000000;
726
727    /**
728     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
729     * setFlags.
730     */
731    private static final int FOCUSABLE = 0x00000001;
732
733    /**
734     * Mask for use with setFlags indicating bits used for focus.
735     */
736    private static final int FOCUSABLE_MASK = 0x00000001;
737
738    /**
739     * This view will adjust its padding to fit sytem windows (e.g. status bar)
740     */
741    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
742
743    /** @hide */
744    @IntDef({VISIBLE, INVISIBLE, GONE})
745    @Retention(RetentionPolicy.SOURCE)
746    public @interface Visibility {}
747
748    /**
749     * This view is visible.
750     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
751     * android:visibility}.
752     */
753    public static final int VISIBLE = 0x00000000;
754
755    /**
756     * This view is invisible, but it still takes up space for layout purposes.
757     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
758     * android:visibility}.
759     */
760    public static final int INVISIBLE = 0x00000004;
761
762    /**
763     * This view is invisible, and it doesn't take any space for layout
764     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
765     * android:visibility}.
766     */
767    public static final int GONE = 0x00000008;
768
769    /**
770     * Mask for use with setFlags indicating bits used for visibility.
771     * {@hide}
772     */
773    static final int VISIBILITY_MASK = 0x0000000C;
774
775    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
776
777    /**
778     * This view is enabled. Interpretation varies by subclass.
779     * Use with ENABLED_MASK when calling setFlags.
780     * {@hide}
781     */
782    static final int ENABLED = 0x00000000;
783
784    /**
785     * This view is disabled. Interpretation varies by subclass.
786     * Use with ENABLED_MASK when calling setFlags.
787     * {@hide}
788     */
789    static final int DISABLED = 0x00000020;
790
791   /**
792    * Mask for use with setFlags indicating bits used for indicating whether
793    * this view is enabled
794    * {@hide}
795    */
796    static final int ENABLED_MASK = 0x00000020;
797
798    /**
799     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
800     * called and further optimizations will be performed. It is okay to have
801     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
802     * {@hide}
803     */
804    static final int WILL_NOT_DRAW = 0x00000080;
805
806    /**
807     * Mask for use with setFlags indicating bits used for indicating whether
808     * this view is will draw
809     * {@hide}
810     */
811    static final int DRAW_MASK = 0x00000080;
812
813    /**
814     * <p>This view doesn't show scrollbars.</p>
815     * {@hide}
816     */
817    static final int SCROLLBARS_NONE = 0x00000000;
818
819    /**
820     * <p>This view shows horizontal scrollbars.</p>
821     * {@hide}
822     */
823    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
824
825    /**
826     * <p>This view shows vertical scrollbars.</p>
827     * {@hide}
828     */
829    static final int SCROLLBARS_VERTICAL = 0x00000200;
830
831    /**
832     * <p>Mask for use with setFlags indicating bits used for indicating which
833     * scrollbars are enabled.</p>
834     * {@hide}
835     */
836    static final int SCROLLBARS_MASK = 0x00000300;
837
838    /**
839     * Indicates that the view should filter touches when its window is obscured.
840     * Refer to the class comments for more information about this security feature.
841     * {@hide}
842     */
843    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
844
845    /**
846     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
847     * that they are optional and should be skipped if the window has
848     * requested system UI flags that ignore those insets for layout.
849     */
850    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
851
852    /**
853     * <p>This view doesn't show fading edges.</p>
854     * {@hide}
855     */
856    static final int FADING_EDGE_NONE = 0x00000000;
857
858    /**
859     * <p>This view shows horizontal fading edges.</p>
860     * {@hide}
861     */
862    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
863
864    /**
865     * <p>This view shows vertical fading edges.</p>
866     * {@hide}
867     */
868    static final int FADING_EDGE_VERTICAL = 0x00002000;
869
870    /**
871     * <p>Mask for use with setFlags indicating bits used for indicating which
872     * fading edges are enabled.</p>
873     * {@hide}
874     */
875    static final int FADING_EDGE_MASK = 0x00003000;
876
877    /**
878     * <p>Indicates this view can be clicked. When clickable, a View reacts
879     * to clicks by notifying the OnClickListener.<p>
880     * {@hide}
881     */
882    static final int CLICKABLE = 0x00004000;
883
884    /**
885     * <p>Indicates this view is caching its drawing into a bitmap.</p>
886     * {@hide}
887     */
888    static final int DRAWING_CACHE_ENABLED = 0x00008000;
889
890    /**
891     * <p>Indicates that no icicle should be saved for this view.<p>
892     * {@hide}
893     */
894    static final int SAVE_DISABLED = 0x000010000;
895
896    /**
897     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
898     * property.</p>
899     * {@hide}
900     */
901    static final int SAVE_DISABLED_MASK = 0x000010000;
902
903    /**
904     * <p>Indicates that no drawing cache should ever be created for this view.<p>
905     * {@hide}
906     */
907    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
908
909    /**
910     * <p>Indicates this view can take / keep focus when int touch mode.</p>
911     * {@hide}
912     */
913    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
914
915    /** @hide */
916    @Retention(RetentionPolicy.SOURCE)
917    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
918    public @interface DrawingCacheQuality {}
919
920    /**
921     * <p>Enables low quality mode for the drawing cache.</p>
922     */
923    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
924
925    /**
926     * <p>Enables high quality mode for the drawing cache.</p>
927     */
928    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
929
930    /**
931     * <p>Enables automatic quality mode for the drawing cache.</p>
932     */
933    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
934
935    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
936            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
937    };
938
939    /**
940     * <p>Mask for use with setFlags indicating bits used for the cache
941     * quality property.</p>
942     * {@hide}
943     */
944    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
945
946    /**
947     * <p>
948     * Indicates this view can be long clicked. When long clickable, a View
949     * reacts to long clicks by notifying the OnLongClickListener or showing a
950     * context menu.
951     * </p>
952     * {@hide}
953     */
954    static final int LONG_CLICKABLE = 0x00200000;
955
956    /**
957     * <p>Indicates that this view gets its drawable states from its direct parent
958     * and ignores its original internal states.</p>
959     *
960     * @hide
961     */
962    static final int DUPLICATE_PARENT_STATE = 0x00400000;
963
964    /** @hide */
965    @IntDef({
966        SCROLLBARS_INSIDE_OVERLAY,
967        SCROLLBARS_INSIDE_INSET,
968        SCROLLBARS_OUTSIDE_OVERLAY,
969        SCROLLBARS_OUTSIDE_INSET
970    })
971    @Retention(RetentionPolicy.SOURCE)
972    public @interface ScrollBarStyle {}
973
974    /**
975     * The scrollbar style to display the scrollbars inside the content area,
976     * without increasing the padding. The scrollbars will be overlaid with
977     * translucency on the view's content.
978     */
979    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
980
981    /**
982     * The scrollbar style to display the scrollbars inside the padded area,
983     * increasing the padding of the view. The scrollbars will not overlap the
984     * content area of the view.
985     */
986    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
987
988    /**
989     * The scrollbar style to display the scrollbars at the edge of the view,
990     * without increasing the padding. The scrollbars will be overlaid with
991     * translucency.
992     */
993    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
994
995    /**
996     * The scrollbar style to display the scrollbars at the edge of the view,
997     * increasing the padding of the view. The scrollbars will only overlap the
998     * background, if any.
999     */
1000    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1001
1002    /**
1003     * Mask to check if the scrollbar style is overlay or inset.
1004     * {@hide}
1005     */
1006    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1007
1008    /**
1009     * Mask to check if the scrollbar style is inside or outside.
1010     * {@hide}
1011     */
1012    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1013
1014    /**
1015     * Mask for scrollbar style.
1016     * {@hide}
1017     */
1018    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1019
1020    /**
1021     * View flag indicating that the screen should remain on while the
1022     * window containing this view is visible to the user.  This effectively
1023     * takes care of automatically setting the WindowManager's
1024     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1025     */
1026    public static final int KEEP_SCREEN_ON = 0x04000000;
1027
1028    /**
1029     * View flag indicating whether this view should have sound effects enabled
1030     * for events such as clicking and touching.
1031     */
1032    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1033
1034    /**
1035     * View flag indicating whether this view should have haptic feedback
1036     * enabled for events such as long presses.
1037     */
1038    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1039
1040    /**
1041     * <p>Indicates that the view hierarchy should stop saving state when
1042     * it reaches this view.  If state saving is initiated immediately at
1043     * the view, it will be allowed.
1044     * {@hide}
1045     */
1046    static final int PARENT_SAVE_DISABLED = 0x20000000;
1047
1048    /**
1049     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1050     * {@hide}
1051     */
1052    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1053
1054    /** @hide */
1055    @IntDef(flag = true,
1056            value = {
1057                FOCUSABLES_ALL,
1058                FOCUSABLES_TOUCH_MODE
1059            })
1060    @Retention(RetentionPolicy.SOURCE)
1061    public @interface FocusableMode {}
1062
1063    /**
1064     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1065     * should add all focusable Views regardless if they are focusable in touch mode.
1066     */
1067    public static final int FOCUSABLES_ALL = 0x00000000;
1068
1069    /**
1070     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1071     * should add only Views focusable in touch mode.
1072     */
1073    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1074
1075    /** @hide */
1076    @IntDef({
1077            FOCUS_BACKWARD,
1078            FOCUS_FORWARD,
1079            FOCUS_LEFT,
1080            FOCUS_UP,
1081            FOCUS_RIGHT,
1082            FOCUS_DOWN
1083    })
1084    @Retention(RetentionPolicy.SOURCE)
1085    public @interface FocusDirection {}
1086
1087    /** @hide */
1088    @IntDef({
1089            FOCUS_LEFT,
1090            FOCUS_UP,
1091            FOCUS_RIGHT,
1092            FOCUS_DOWN
1093    })
1094    @Retention(RetentionPolicy.SOURCE)
1095    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1096
1097    /**
1098     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1099     * item.
1100     */
1101    public static final int FOCUS_BACKWARD = 0x00000001;
1102
1103    /**
1104     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1105     * item.
1106     */
1107    public static final int FOCUS_FORWARD = 0x00000002;
1108
1109    /**
1110     * Use with {@link #focusSearch(int)}. Move focus to the left.
1111     */
1112    public static final int FOCUS_LEFT = 0x00000011;
1113
1114    /**
1115     * Use with {@link #focusSearch(int)}. Move focus up.
1116     */
1117    public static final int FOCUS_UP = 0x00000021;
1118
1119    /**
1120     * Use with {@link #focusSearch(int)}. Move focus to the right.
1121     */
1122    public static final int FOCUS_RIGHT = 0x00000042;
1123
1124    /**
1125     * Use with {@link #focusSearch(int)}. Move focus down.
1126     */
1127    public static final int FOCUS_DOWN = 0x00000082;
1128
1129    /**
1130     * Bits of {@link #getMeasuredWidthAndState()} and
1131     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1132     */
1133    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1134
1135    /**
1136     * Bits of {@link #getMeasuredWidthAndState()} and
1137     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1138     */
1139    public static final int MEASURED_STATE_MASK = 0xff000000;
1140
1141    /**
1142     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1143     * for functions that combine both width and height into a single int,
1144     * such as {@link #getMeasuredState()} and the childState argument of
1145     * {@link #resolveSizeAndState(int, int, int)}.
1146     */
1147    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1148
1149    /**
1150     * Bit of {@link #getMeasuredWidthAndState()} and
1151     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1152     * is smaller that the space the view would like to have.
1153     */
1154    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1155
1156    /**
1157     * Base View state sets
1158     */
1159    // Singles
1160    /**
1161     * Indicates the view has no states set. States are used with
1162     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1163     * view depending on its state.
1164     *
1165     * @see android.graphics.drawable.Drawable
1166     * @see #getDrawableState()
1167     */
1168    protected static final int[] EMPTY_STATE_SET;
1169    /**
1170     * Indicates the view is enabled. States are used with
1171     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1172     * view depending on its state.
1173     *
1174     * @see android.graphics.drawable.Drawable
1175     * @see #getDrawableState()
1176     */
1177    protected static final int[] ENABLED_STATE_SET;
1178    /**
1179     * Indicates the view is focused. States are used with
1180     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1181     * view depending on its state.
1182     *
1183     * @see android.graphics.drawable.Drawable
1184     * @see #getDrawableState()
1185     */
1186    protected static final int[] FOCUSED_STATE_SET;
1187    /**
1188     * Indicates the view is selected. States are used with
1189     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1190     * view depending on its state.
1191     *
1192     * @see android.graphics.drawable.Drawable
1193     * @see #getDrawableState()
1194     */
1195    protected static final int[] SELECTED_STATE_SET;
1196    /**
1197     * Indicates the view is pressed. States are used with
1198     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1199     * view depending on its state.
1200     *
1201     * @see android.graphics.drawable.Drawable
1202     * @see #getDrawableState()
1203     */
1204    protected static final int[] PRESSED_STATE_SET;
1205    /**
1206     * Indicates the view's window has focus. States are used with
1207     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1208     * view depending on its state.
1209     *
1210     * @see android.graphics.drawable.Drawable
1211     * @see #getDrawableState()
1212     */
1213    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1214    // Doubles
1215    /**
1216     * Indicates the view is enabled and has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     */
1221    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1222    /**
1223     * Indicates the view is enabled and selected.
1224     *
1225     * @see #ENABLED_STATE_SET
1226     * @see #SELECTED_STATE_SET
1227     */
1228    protected static final int[] ENABLED_SELECTED_STATE_SET;
1229    /**
1230     * Indicates the view is enabled and that its window has focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #WINDOW_FOCUSED_STATE_SET
1234     */
1235    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1236    /**
1237     * Indicates the view is focused and selected.
1238     *
1239     * @see #FOCUSED_STATE_SET
1240     * @see #SELECTED_STATE_SET
1241     */
1242    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1243    /**
1244     * Indicates the view has the focus and that its window has the focus.
1245     *
1246     * @see #FOCUSED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is selected and that its window has the focus.
1252     *
1253     * @see #SELECTED_STATE_SET
1254     * @see #WINDOW_FOCUSED_STATE_SET
1255     */
1256    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1257    // Triples
1258    /**
1259     * Indicates the view is enabled, focused and selected.
1260     *
1261     * @see #ENABLED_STATE_SET
1262     * @see #FOCUSED_STATE_SET
1263     * @see #SELECTED_STATE_SET
1264     */
1265    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1266    /**
1267     * Indicates the view is enabled, focused and its window has the focus.
1268     *
1269     * @see #ENABLED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #WINDOW_FOCUSED_STATE_SET
1272     */
1273    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1274    /**
1275     * Indicates the view is enabled, selected and its window has the focus.
1276     *
1277     * @see #ENABLED_STATE_SET
1278     * @see #SELECTED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1282    /**
1283     * Indicates the view is focused, selected and its window has the focus.
1284     *
1285     * @see #FOCUSED_STATE_SET
1286     * @see #SELECTED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is enabled, focused, selected and its window
1292     * has the focus.
1293     *
1294     * @see #ENABLED_STATE_SET
1295     * @see #FOCUSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #WINDOW_FOCUSED_STATE_SET
1298     */
1299    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed and its window has the focus.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #WINDOW_FOCUSED_STATE_SET
1305     */
1306    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1307    /**
1308     * Indicates the view is pressed and selected.
1309     *
1310     * @see #PRESSED_STATE_SET
1311     * @see #SELECTED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_SELECTED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, selected and its window has the focus.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #SELECTED_STATE_SET
1319     * @see #WINDOW_FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed and focused.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, focused and its window has the focus.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #FOCUSED_STATE_SET
1334     * @see #WINDOW_FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, focused and selected.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #SELECTED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, focused, selected and its window has the focus.
1347     *
1348     * @see #PRESSED_STATE_SET
1349     * @see #FOCUSED_STATE_SET
1350     * @see #SELECTED_STATE_SET
1351     * @see #WINDOW_FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed and enabled.
1356     *
1357     * @see #PRESSED_STATE_SET
1358     * @see #ENABLED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_ENABLED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed, enabled and its window has the focus.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #ENABLED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled and selected.
1371     *
1372     * @see #PRESSED_STATE_SET
1373     * @see #ENABLED_STATE_SET
1374     * @see #SELECTED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1377    /**
1378     * Indicates the view is pressed, enabled, selected and its window has the
1379     * focus.
1380     *
1381     * @see #PRESSED_STATE_SET
1382     * @see #ENABLED_STATE_SET
1383     * @see #SELECTED_STATE_SET
1384     * @see #WINDOW_FOCUSED_STATE_SET
1385     */
1386    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1387    /**
1388     * Indicates the view is pressed, enabled and focused.
1389     *
1390     * @see #PRESSED_STATE_SET
1391     * @see #ENABLED_STATE_SET
1392     * @see #FOCUSED_STATE_SET
1393     */
1394    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1395    /**
1396     * Indicates the view is pressed, enabled, focused and its window has the
1397     * focus.
1398     *
1399     * @see #PRESSED_STATE_SET
1400     * @see #ENABLED_STATE_SET
1401     * @see #FOCUSED_STATE_SET
1402     * @see #WINDOW_FOCUSED_STATE_SET
1403     */
1404    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1405    /**
1406     * Indicates the view is pressed, enabled, focused and selected.
1407     *
1408     * @see #PRESSED_STATE_SET
1409     * @see #ENABLED_STATE_SET
1410     * @see #SELECTED_STATE_SET
1411     * @see #FOCUSED_STATE_SET
1412     */
1413    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1414    /**
1415     * Indicates the view is pressed, enabled, focused, selected and its window
1416     * has the focus.
1417     *
1418     * @see #PRESSED_STATE_SET
1419     * @see #ENABLED_STATE_SET
1420     * @see #SELECTED_STATE_SET
1421     * @see #FOCUSED_STATE_SET
1422     * @see #WINDOW_FOCUSED_STATE_SET
1423     */
1424    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1425
1426    /**
1427     * The order here is very important to {@link #getDrawableState()}
1428     */
1429    private static final int[][] VIEW_STATE_SETS;
1430
1431    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1432    static final int VIEW_STATE_SELECTED = 1 << 1;
1433    static final int VIEW_STATE_FOCUSED = 1 << 2;
1434    static final int VIEW_STATE_ENABLED = 1 << 3;
1435    static final int VIEW_STATE_PRESSED = 1 << 4;
1436    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1437    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1438    static final int VIEW_STATE_HOVERED = 1 << 7;
1439    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1440    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1441
1442    static final int[] VIEW_STATE_IDS = new int[] {
1443        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1444        R.attr.state_selected,          VIEW_STATE_SELECTED,
1445        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1446        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1447        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1448        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1449        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1450        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1451        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1452        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1453    };
1454
1455    static {
1456        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1457            throw new IllegalStateException(
1458                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1459        }
1460        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1461        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1462            int viewState = R.styleable.ViewDrawableStates[i];
1463            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1464                if (VIEW_STATE_IDS[j] == viewState) {
1465                    orderedIds[i * 2] = viewState;
1466                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1467                }
1468            }
1469        }
1470        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1471        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1472        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1473            int numBits = Integer.bitCount(i);
1474            int[] set = new int[numBits];
1475            int pos = 0;
1476            for (int j = 0; j < orderedIds.length; j += 2) {
1477                if ((i & orderedIds[j+1]) != 0) {
1478                    set[pos++] = orderedIds[j];
1479                }
1480            }
1481            VIEW_STATE_SETS[i] = set;
1482        }
1483
1484        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1485        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1486        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1487        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1488                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1489        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1490        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1492        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1494        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1496                | VIEW_STATE_FOCUSED];
1497        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1498        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1499                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1500        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1502        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1504                | VIEW_STATE_ENABLED];
1505        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1507        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1509                | VIEW_STATE_ENABLED];
1510        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1515                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1516
1517        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1518        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1519                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1520        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1521                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1522        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1523                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1524                | VIEW_STATE_PRESSED];
1525        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1527        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1529                | VIEW_STATE_PRESSED];
1530        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1535                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1536        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1538        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1539                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1540                | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1546                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1549                | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1552                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1555                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1558                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1559                | VIEW_STATE_PRESSED];
1560    }
1561
1562    /**
1563     * Accessibility event types that are dispatched for text population.
1564     */
1565    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1566            AccessibilityEvent.TYPE_VIEW_CLICKED
1567            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1568            | AccessibilityEvent.TYPE_VIEW_SELECTED
1569            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1570            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1571            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1572            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1573            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1574            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1575            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1576            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1577
1578    /**
1579     * Temporary Rect currently for use in setBackground().  This will probably
1580     * be extended in the future to hold our own class with more than just
1581     * a Rect. :)
1582     */
1583    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1584
1585    /**
1586     * Map used to store views' tags.
1587     */
1588    private SparseArray<Object> mKeyedTags;
1589
1590    /**
1591     * The next available accessibility id.
1592     */
1593    private static int sNextAccessibilityViewId;
1594
1595    /**
1596     * The animation currently associated with this view.
1597     * @hide
1598     */
1599    protected Animation mCurrentAnimation = null;
1600
1601    /**
1602     * Width as measured during measure pass.
1603     * {@hide}
1604     */
1605    @ViewDebug.ExportedProperty(category = "measurement")
1606    int mMeasuredWidth;
1607
1608    /**
1609     * Height as measured during measure pass.
1610     * {@hide}
1611     */
1612    @ViewDebug.ExportedProperty(category = "measurement")
1613    int mMeasuredHeight;
1614
1615    /**
1616     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1617     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1618     * its display list. This flag, used only when hw accelerated, allows us to clear the
1619     * flag while retaining this information until it's needed (at getDisplayList() time and
1620     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1621     *
1622     * {@hide}
1623     */
1624    boolean mRecreateDisplayList = false;
1625
1626    /**
1627     * The view's identifier.
1628     * {@hide}
1629     *
1630     * @see #setId(int)
1631     * @see #getId()
1632     */
1633    @ViewDebug.ExportedProperty(resolveId = true)
1634    int mID = NO_ID;
1635
1636    /**
1637     * The stable ID of this view for accessibility purposes.
1638     */
1639    int mAccessibilityViewId = NO_ID;
1640
1641    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1642
1643    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1644
1645    /**
1646     * The view's tag.
1647     * {@hide}
1648     *
1649     * @see #setTag(Object)
1650     * @see #getTag()
1651     */
1652    protected Object mTag = null;
1653
1654    // for mPrivateFlags:
1655    /** {@hide} */
1656    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1657    /** {@hide} */
1658    static final int PFLAG_FOCUSED                     = 0x00000002;
1659    /** {@hide} */
1660    static final int PFLAG_SELECTED                    = 0x00000004;
1661    /** {@hide} */
1662    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1663    /** {@hide} */
1664    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1665    /** {@hide} */
1666    static final int PFLAG_DRAWN                       = 0x00000020;
1667    /**
1668     * When this flag is set, this view is running an animation on behalf of its
1669     * children and should therefore not cancel invalidate requests, even if they
1670     * lie outside of this view's bounds.
1671     *
1672     * {@hide}
1673     */
1674    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1675    /** {@hide} */
1676    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1677    /** {@hide} */
1678    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1679    /** {@hide} */
1680    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1681    /** {@hide} */
1682    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1683    /** {@hide} */
1684    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1685    /** {@hide} */
1686    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1687    /** {@hide} */
1688    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1689
1690    private static final int PFLAG_PRESSED             = 0x00004000;
1691
1692    /** {@hide} */
1693    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1694    /**
1695     * Flag used to indicate that this view should be drawn once more (and only once
1696     * more) after its animation has completed.
1697     * {@hide}
1698     */
1699    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1700
1701    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1702
1703    /**
1704     * Indicates that the View returned true when onSetAlpha() was called and that
1705     * the alpha must be restored.
1706     * {@hide}
1707     */
1708    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1709
1710    /**
1711     * Set by {@link #setScrollContainer(boolean)}.
1712     */
1713    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1714
1715    /**
1716     * Set by {@link #setScrollContainer(boolean)}.
1717     */
1718    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1719
1720    /**
1721     * View flag indicating whether this view was invalidated (fully or partially.)
1722     *
1723     * @hide
1724     */
1725    static final int PFLAG_DIRTY                       = 0x00200000;
1726
1727    /**
1728     * View flag indicating whether this view was invalidated by an opaque
1729     * invalidate request.
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1734
1735    /**
1736     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1737     *
1738     * @hide
1739     */
1740    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1741
1742    /**
1743     * Indicates whether the background is opaque.
1744     *
1745     * @hide
1746     */
1747    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1748
1749    /**
1750     * Indicates whether the scrollbars are opaque.
1751     *
1752     * @hide
1753     */
1754    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1755
1756    /**
1757     * Indicates whether the view is opaque.
1758     *
1759     * @hide
1760     */
1761    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1762
1763    /**
1764     * Indicates a prepressed state;
1765     * the short time between ACTION_DOWN and recognizing
1766     * a 'real' press. Prepressed is used to recognize quick taps
1767     * even when they are shorter than ViewConfiguration.getTapTimeout().
1768     *
1769     * @hide
1770     */
1771    private static final int PFLAG_PREPRESSED          = 0x02000000;
1772
1773    /**
1774     * Indicates whether the view is temporarily detached.
1775     *
1776     * @hide
1777     */
1778    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1779
1780    /**
1781     * Indicates that we should awaken scroll bars once attached
1782     *
1783     * @hide
1784     */
1785    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1786
1787    /**
1788     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1789     * @hide
1790     */
1791    private static final int PFLAG_HOVERED             = 0x10000000;
1792
1793    /**
1794     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1795     * for transform operations
1796     *
1797     * @hide
1798     */
1799    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1800
1801    /** {@hide} */
1802    static final int PFLAG_ACTIVATED                   = 0x40000000;
1803
1804    /**
1805     * Indicates that this view was specifically invalidated, not just dirtied because some
1806     * child view was invalidated. The flag is used to determine when we need to recreate
1807     * a view's display list (as opposed to just returning a reference to its existing
1808     * display list).
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_INVALIDATED                 = 0x80000000;
1813
1814    /**
1815     * Masks for mPrivateFlags2, as generated by dumpFlags():
1816     *
1817     * |-------|-------|-------|-------|
1818     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1819     *                                1  PFLAG2_DRAG_HOVERED
1820     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1821     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1822     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1823     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1824     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1825     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1826     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1827     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1828     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1829     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1830     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1831     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1832     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1833     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1834     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1835     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1836     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1837     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1838     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1839     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1840     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1841     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1842     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1843     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1844     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1845     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1846     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1847     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1848     *    1                              PFLAG2_PADDING_RESOLVED
1849     *   1                               PFLAG2_DRAWABLE_RESOLVED
1850     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1851     * |-------|-------|-------|-------|
1852     */
1853
1854    /**
1855     * Indicates that this view has reported that it can accept the current drag's content.
1856     * Cleared when the drag operation concludes.
1857     * @hide
1858     */
1859    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1860
1861    /**
1862     * Indicates that this view is currently directly under the drag location in a
1863     * drag-and-drop operation involving content that it can accept.  Cleared when
1864     * the drag exits the view, or when the drag operation concludes.
1865     * @hide
1866     */
1867    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1868
1869    /** @hide */
1870    @IntDef({
1871        LAYOUT_DIRECTION_LTR,
1872        LAYOUT_DIRECTION_RTL,
1873        LAYOUT_DIRECTION_INHERIT,
1874        LAYOUT_DIRECTION_LOCALE
1875    })
1876    @Retention(RetentionPolicy.SOURCE)
1877    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1878    public @interface LayoutDir {}
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL
1884    })
1885    @Retention(RetentionPolicy.SOURCE)
1886    public @interface ResolvedLayoutDir {}
1887
1888    /**
1889     * Horizontal layout direction of this view is from Left to Right.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1893
1894    /**
1895     * Horizontal layout direction of this view is from Right to Left.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1899
1900    /**
1901     * Horizontal layout direction of this view is inherited from its parent.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1905
1906    /**
1907     * Horizontal layout direction of this view is from deduced from the default language
1908     * script for the locale. Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1911
1912    /**
1913     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1917
1918    /**
1919     * Mask for use with private flags indicating bits used for horizontal layout direction.
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1923
1924    /**
1925     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1926     * right-to-left direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1942            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /*
1945     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1946     * flag value.
1947     * @hide
1948     */
1949    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1950            LAYOUT_DIRECTION_LTR,
1951            LAYOUT_DIRECTION_RTL,
1952            LAYOUT_DIRECTION_INHERIT,
1953            LAYOUT_DIRECTION_LOCALE
1954    };
1955
1956    /**
1957     * Default horizontal layout direction.
1958     */
1959    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1960
1961    /**
1962     * Default horizontal layout direction.
1963     * @hide
1964     */
1965    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1966
1967    /**
1968     * Text direction is inherited thru {@link ViewGroup}
1969     */
1970    public static final int TEXT_DIRECTION_INHERIT = 0;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is the view's resolved layout direction.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1978
1979    /**
1980     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1981     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1982     * If there are neither, the paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1985
1986    /**
1987     * Text direction is forced to LTR.
1988     */
1989    public static final int TEXT_DIRECTION_LTR = 3;
1990
1991    /**
1992     * Text direction is forced to RTL.
1993     */
1994    public static final int TEXT_DIRECTION_RTL = 4;
1995
1996    /**
1997     * Text direction is coming from the system Locale.
1998     */
1999    public static final int TEXT_DIRECTION_LOCALE = 5;
2000
2001    /**
2002     * Default text direction is inherited
2003     */
2004    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2005
2006    /**
2007     * Default resolved text direction
2008     * @hide
2009     */
2010    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2011
2012    /**
2013     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2017
2018    /**
2019     * Mask for use with private flags indicating bits used for text direction.
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2023            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2024
2025    /**
2026     * Array of text direction flags for mapping attribute "textDirection" to correct
2027     * flag value.
2028     * @hide
2029     */
2030    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2031            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2036            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2037    };
2038
2039    /**
2040     * Indicates whether the view text direction has been resolved.
2041     * @hide
2042     */
2043    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2044            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for resolved text direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2057            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2058
2059    /**
2060     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2064            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /** @hide */
2067    @IntDef({
2068        TEXT_ALIGNMENT_INHERIT,
2069        TEXT_ALIGNMENT_GRAVITY,
2070        TEXT_ALIGNMENT_CENTER,
2071        TEXT_ALIGNMENT_TEXT_START,
2072        TEXT_ALIGNMENT_TEXT_END,
2073        TEXT_ALIGNMENT_VIEW_START,
2074        TEXT_ALIGNMENT_VIEW_END
2075    })
2076    @Retention(RetentionPolicy.SOURCE)
2077    public @interface TextAlignment {}
2078
2079    /**
2080     * Default text alignment. The text alignment of this View is inherited from its parent.
2081     * Use with {@link #setTextAlignment(int)}
2082     */
2083    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2084
2085    /**
2086     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2087     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2088     *
2089     * Use with {@link #setTextAlignment(int)}
2090     */
2091    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2092
2093    /**
2094     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2099
2100    /**
2101     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2106
2107    /**
2108     * Center the paragraph, e.g. ALIGN_CENTER.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_CENTER = 4;
2113
2114    /**
2115     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2116     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2117     *
2118     * Use with {@link #setTextAlignment(int)}
2119     */
2120    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2121
2122    /**
2123     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2124     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2125     *
2126     * Use with {@link #setTextAlignment(int)}
2127     */
2128    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2129
2130    /**
2131     * Default text alignment is inherited
2132     */
2133    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2134
2135    /**
2136     * Default resolved text alignment
2137     * @hide
2138     */
2139    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2140
2141    /**
2142      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2143      * @hide
2144      */
2145    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2146
2147    /**
2148      * Mask for use with private flags indicating bits used for text alignment.
2149      * @hide
2150      */
2151    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2152
2153    /**
2154     * Array of text direction flags for mapping attribute "textAlignment" to correct
2155     * flag value.
2156     * @hide
2157     */
2158    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2159            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2166    };
2167
2168    /**
2169     * Indicates whether the view text alignment has been resolved.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2173
2174    /**
2175     * Bit shift to get the resolved text alignment.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2179
2180    /**
2181     * Mask for use with private flags indicating bits used for text alignment.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2185            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2186
2187    /**
2188     * Indicates whether if the view text alignment has been resolved to gravity
2189     */
2190    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2191            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2192
2193    // Accessiblity constants for mPrivateFlags2
2194
2195    /**
2196     * Shift for the bits in {@link #mPrivateFlags2} related to the
2197     * "importantForAccessibility" attribute.
2198     */
2199    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2200
2201    /**
2202     * Automatically determine whether a view is important for accessibility.
2203     */
2204    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2205
2206    /**
2207     * The view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2210
2211    /**
2212     * The view is not important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2215
2216    /**
2217     * The view is not important for accessibility, nor are any of its
2218     * descendant views.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2221
2222    /**
2223     * The default whether the view is important for accessibility.
2224     */
2225    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2226
2227    /**
2228     * Mask for obtainig the bits which specify how to determine
2229     * whether a view is important for accessibility.
2230     */
2231    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2232        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2233        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2234        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2235
2236    /**
2237     * Shift for the bits in {@link #mPrivateFlags2} related to the
2238     * "accessibilityLiveRegion" attribute.
2239     */
2240    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2241
2242    /**
2243     * Live region mode specifying that accessibility services should not
2244     * automatically announce changes to this view. This is the default live
2245     * region mode for most views.
2246     * <p>
2247     * Use with {@link #setAccessibilityLiveRegion(int)}.
2248     */
2249    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2250
2251    /**
2252     * Live region mode specifying that accessibility services should announce
2253     * changes to this view.
2254     * <p>
2255     * Use with {@link #setAccessibilityLiveRegion(int)}.
2256     */
2257    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2258
2259    /**
2260     * Live region mode specifying that accessibility services should interrupt
2261     * ongoing speech to immediately announce changes to this view.
2262     * <p>
2263     * Use with {@link #setAccessibilityLiveRegion(int)}.
2264     */
2265    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2266
2267    /**
2268     * The default whether the view is important for accessibility.
2269     */
2270    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2271
2272    /**
2273     * Mask for obtaining the bits which specify a view's accessibility live
2274     * region mode.
2275     */
2276    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2277            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2278            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2279
2280    /**
2281     * Flag indicating whether a view has accessibility focus.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2284
2285    /**
2286     * Flag whether the accessibility state of the subtree rooted at this view changed.
2287     */
2288    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2289
2290    /**
2291     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2292     * is used to check whether later changes to the view's transform should invalidate the
2293     * view to force the quickReject test to run again.
2294     */
2295    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2296
2297    /**
2298     * Flag indicating that start/end padding has been resolved into left/right padding
2299     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2300     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2301     * during measurement. In some special cases this is required such as when an adapter-based
2302     * view measures prospective children without attaching them to a window.
2303     */
2304    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2305
2306    /**
2307     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2308     */
2309    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2310
2311    /**
2312     * Indicates that the view is tracking some sort of transient state
2313     * that the app should not need to be aware of, but that the framework
2314     * should take special care to preserve.
2315     */
2316    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2317
2318    /**
2319     * Group of bits indicating that RTL properties resolution is done.
2320     */
2321    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2322            PFLAG2_TEXT_DIRECTION_RESOLVED |
2323            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2324            PFLAG2_PADDING_RESOLVED |
2325            PFLAG2_DRAWABLE_RESOLVED;
2326
2327    // There are a couple of flags left in mPrivateFlags2
2328
2329    /* End of masks for mPrivateFlags2 */
2330
2331    /**
2332     * Masks for mPrivateFlags3, as generated by dumpFlags():
2333     *
2334     * |-------|-------|-------|-------|
2335     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2336     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2337     *                               1   PFLAG3_IS_LAID_OUT
2338     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2339     *                             1     PFLAG3_CALLED_SUPER
2340     * |-------|-------|-------|-------|
2341     */
2342
2343    /**
2344     * Flag indicating that view has a transform animation set on it. This is used to track whether
2345     * an animation is cleared between successive frames, in order to tell the associated
2346     * DisplayList to clear its animation matrix.
2347     */
2348    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2349
2350    /**
2351     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2352     * animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to restore its alpha value.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2356
2357    /**
2358     * Flag indicating that the view has been through at least one layout since it
2359     * was last attached to a window.
2360     */
2361    static final int PFLAG3_IS_LAID_OUT = 0x4;
2362
2363    /**
2364     * Flag indicating that a call to measure() was skipped and should be done
2365     * instead when layout() is invoked.
2366     */
2367    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2368
2369    /**
2370     * Flag indicating that an overridden method correctly  called down to
2371     * the superclass implementation as required by the API spec.
2372     */
2373    static final int PFLAG3_CALLED_SUPER = 0x10;
2374
2375    /**
2376     * Flag indicating that an view will be clipped to its outline.
2377     */
2378    static final int PFLAG3_CLIP_TO_OUTLINE = 0x20;
2379
2380    /**
2381     * Flag indicating that a view's outline has been specifically defined.
2382     */
2383    static final int PFLAG3_OUTLINE_DEFINED = 0x40;
2384
2385    /**
2386     * Flag indicating that we're in the process of applying window insets.
2387     */
2388    static final int PFLAG3_APPLYING_INSETS = 0x80;
2389
2390    /**
2391     * Flag indicating that we're in the process of fitting system windows using the old method.
2392     */
2393    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x100;
2394
2395    /* End of masks for mPrivateFlags3 */
2396
2397    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2398
2399    /**
2400     * Always allow a user to over-scroll this view, provided it is a
2401     * view that can scroll.
2402     *
2403     * @see #getOverScrollMode()
2404     * @see #setOverScrollMode(int)
2405     */
2406    public static final int OVER_SCROLL_ALWAYS = 0;
2407
2408    /**
2409     * Allow a user to over-scroll this view only if the content is large
2410     * enough to meaningfully scroll, provided it is a view that can scroll.
2411     *
2412     * @see #getOverScrollMode()
2413     * @see #setOverScrollMode(int)
2414     */
2415    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2416
2417    /**
2418     * Never allow a user to over-scroll this view.
2419     *
2420     * @see #getOverScrollMode()
2421     * @see #setOverScrollMode(int)
2422     */
2423    public static final int OVER_SCROLL_NEVER = 2;
2424
2425    /**
2426     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2427     * requested the system UI (status bar) to be visible (the default).
2428     *
2429     * @see #setSystemUiVisibility(int)
2430     */
2431    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2432
2433    /**
2434     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2435     * system UI to enter an unobtrusive "low profile" mode.
2436     *
2437     * <p>This is for use in games, book readers, video players, or any other
2438     * "immersive" application where the usual system chrome is deemed too distracting.
2439     *
2440     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2441     *
2442     * @see #setSystemUiVisibility(int)
2443     */
2444    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2445
2446    /**
2447     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2448     * system navigation be temporarily hidden.
2449     *
2450     * <p>This is an even less obtrusive state than that called for by
2451     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2452     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2453     * those to disappear. This is useful (in conjunction with the
2454     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2455     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2456     * window flags) for displaying content using every last pixel on the display.
2457     *
2458     * <p>There is a limitation: because navigation controls are so important, the least user
2459     * interaction will cause them to reappear immediately.  When this happens, both
2460     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2461     * so that both elements reappear at the same time.
2462     *
2463     * @see #setSystemUiVisibility(int)
2464     */
2465    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2466
2467    /**
2468     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2469     * into the normal fullscreen mode so that its content can take over the screen
2470     * while still allowing the user to interact with the application.
2471     *
2472     * <p>This has the same visual effect as
2473     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2474     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2475     * meaning that non-critical screen decorations (such as the status bar) will be
2476     * hidden while the user is in the View's window, focusing the experience on
2477     * that content.  Unlike the window flag, if you are using ActionBar in
2478     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2479     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2480     * hide the action bar.
2481     *
2482     * <p>This approach to going fullscreen is best used over the window flag when
2483     * it is a transient state -- that is, the application does this at certain
2484     * points in its user interaction where it wants to allow the user to focus
2485     * on content, but not as a continuous state.  For situations where the application
2486     * would like to simply stay full screen the entire time (such as a game that
2487     * wants to take over the screen), the
2488     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2489     * is usually a better approach.  The state set here will be removed by the system
2490     * in various situations (such as the user moving to another application) like
2491     * the other system UI states.
2492     *
2493     * <p>When using this flag, the application should provide some easy facility
2494     * for the user to go out of it.  A common example would be in an e-book
2495     * reader, where tapping on the screen brings back whatever screen and UI
2496     * decorations that had been hidden while the user was immersed in reading
2497     * the book.
2498     *
2499     * @see #setSystemUiVisibility(int)
2500     */
2501    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2502
2503    /**
2504     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2505     * flags, we would like a stable view of the content insets given to
2506     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2507     * will always represent the worst case that the application can expect
2508     * as a continuous state.  In the stock Android UI this is the space for
2509     * the system bar, nav bar, and status bar, but not more transient elements
2510     * such as an input method.
2511     *
2512     * The stable layout your UI sees is based on the system UI modes you can
2513     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2514     * then you will get a stable layout for changes of the
2515     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2516     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2517     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2518     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2519     * with a stable layout.  (Note that you should avoid using
2520     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2521     *
2522     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2523     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2524     * then a hidden status bar will be considered a "stable" state for purposes
2525     * here.  This allows your UI to continually hide the status bar, while still
2526     * using the system UI flags to hide the action bar while still retaining
2527     * a stable layout.  Note that changing the window fullscreen flag will never
2528     * provide a stable layout for a clean transition.
2529     *
2530     * <p>If you are using ActionBar in
2531     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2532     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2533     * insets it adds to those given to the application.
2534     */
2535    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2536
2537    /**
2538     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2539     * to be layed out as if it has requested
2540     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2541     * allows it to avoid artifacts when switching in and out of that mode, at
2542     * the expense that some of its user interface may be covered by screen
2543     * decorations when they are shown.  You can perform layout of your inner
2544     * UI elements to account for the navigation system UI through the
2545     * {@link #fitSystemWindows(Rect)} method.
2546     */
2547    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2548
2549    /**
2550     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2551     * to be layed out as if it has requested
2552     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2553     * allows it to avoid artifacts when switching in and out of that mode, at
2554     * the expense that some of its user interface may be covered by screen
2555     * decorations when they are shown.  You can perform layout of your inner
2556     * UI elements to account for non-fullscreen system UI through the
2557     * {@link #fitSystemWindows(Rect)} method.
2558     */
2559    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2560
2561    /**
2562     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2563     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2564     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2565     * user interaction.
2566     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2567     * has an effect when used in combination with that flag.</p>
2568     */
2569    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2570
2571    /**
2572     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2573     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2574     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2575     * experience while also hiding the system bars.  If this flag is not set,
2576     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2577     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2578     * if the user swipes from the top of the screen.
2579     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2580     * system gestures, such as swiping from the top of the screen.  These transient system bars
2581     * will overlay app’s content, may have some degree of transparency, and will automatically
2582     * hide after a short timeout.
2583     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2584     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2585     * with one or both of those flags.</p>
2586     */
2587    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2588
2589    /**
2590     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2591     */
2592    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2593
2594    /**
2595     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2596     */
2597    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2598
2599    /**
2600     * @hide
2601     *
2602     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2603     * out of the public fields to keep the undefined bits out of the developer's way.
2604     *
2605     * Flag to make the status bar not expandable.  Unless you also
2606     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2607     */
2608    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2609
2610    /**
2611     * @hide
2612     *
2613     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2614     * out of the public fields to keep the undefined bits out of the developer's way.
2615     *
2616     * Flag to hide notification icons and scrolling ticker text.
2617     */
2618    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2619
2620    /**
2621     * @hide
2622     *
2623     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2624     * out of the public fields to keep the undefined bits out of the developer's way.
2625     *
2626     * Flag to disable incoming notification alerts.  This will not block
2627     * icons, but it will block sound, vibrating and other visual or aural notifications.
2628     */
2629    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2630
2631    /**
2632     * @hide
2633     *
2634     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2635     * out of the public fields to keep the undefined bits out of the developer's way.
2636     *
2637     * Flag to hide only the scrolling ticker.  Note that
2638     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2639     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2640     */
2641    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2642
2643    /**
2644     * @hide
2645     *
2646     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2647     * out of the public fields to keep the undefined bits out of the developer's way.
2648     *
2649     * Flag to hide the center system info area.
2650     */
2651    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2652
2653    /**
2654     * @hide
2655     *
2656     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2657     * out of the public fields to keep the undefined bits out of the developer's way.
2658     *
2659     * Flag to hide only the home button.  Don't use this
2660     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2661     */
2662    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2663
2664    /**
2665     * @hide
2666     *
2667     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2668     * out of the public fields to keep the undefined bits out of the developer's way.
2669     *
2670     * Flag to hide only the back button. Don't use this
2671     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2672     */
2673    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2674
2675    /**
2676     * @hide
2677     *
2678     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2679     * out of the public fields to keep the undefined bits out of the developer's way.
2680     *
2681     * Flag to hide only the clock.  You might use this if your activity has
2682     * its own clock making the status bar's clock redundant.
2683     */
2684    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2685
2686    /**
2687     * @hide
2688     *
2689     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2690     * out of the public fields to keep the undefined bits out of the developer's way.
2691     *
2692     * Flag to hide only the recent apps button. Don't use this
2693     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2694     */
2695    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2696
2697    /**
2698     * @hide
2699     *
2700     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2701     * out of the public fields to keep the undefined bits out of the developer's way.
2702     *
2703     * Flag to disable the global search gesture. Don't use this
2704     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2705     */
2706    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2707
2708    /**
2709     * @hide
2710     *
2711     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2712     * out of the public fields to keep the undefined bits out of the developer's way.
2713     *
2714     * Flag to specify that the status bar is displayed in transient mode.
2715     */
2716    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2717
2718    /**
2719     * @hide
2720     *
2721     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2722     * out of the public fields to keep the undefined bits out of the developer's way.
2723     *
2724     * Flag to specify that the navigation bar is displayed in transient mode.
2725     */
2726    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2727
2728    /**
2729     * @hide
2730     *
2731     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2732     * out of the public fields to keep the undefined bits out of the developer's way.
2733     *
2734     * Flag to specify that the hidden status bar would like to be shown.
2735     */
2736    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2737
2738    /**
2739     * @hide
2740     *
2741     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2742     * out of the public fields to keep the undefined bits out of the developer's way.
2743     *
2744     * Flag to specify that the hidden navigation bar would like to be shown.
2745     */
2746    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2747
2748    /**
2749     * @hide
2750     *
2751     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2752     * out of the public fields to keep the undefined bits out of the developer's way.
2753     *
2754     * Flag to specify that the status bar is displayed in translucent mode.
2755     */
2756    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2757
2758    /**
2759     * @hide
2760     *
2761     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2762     * out of the public fields to keep the undefined bits out of the developer's way.
2763     *
2764     * Flag to specify that the navigation bar is displayed in translucent mode.
2765     */
2766    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2767
2768    /**
2769     * @hide
2770     */
2771    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2772
2773    /**
2774     * These are the system UI flags that can be cleared by events outside
2775     * of an application.  Currently this is just the ability to tap on the
2776     * screen while hiding the navigation bar to have it return.
2777     * @hide
2778     */
2779    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2780            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2781            | SYSTEM_UI_FLAG_FULLSCREEN;
2782
2783    /**
2784     * Flags that can impact the layout in relation to system UI.
2785     */
2786    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2787            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2788            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2789
2790    /** @hide */
2791    @IntDef(flag = true,
2792            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2793    @Retention(RetentionPolicy.SOURCE)
2794    public @interface FindViewFlags {}
2795
2796    /**
2797     * Find views that render the specified text.
2798     *
2799     * @see #findViewsWithText(ArrayList, CharSequence, int)
2800     */
2801    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2802
2803    /**
2804     * Find find views that contain the specified content description.
2805     *
2806     * @see #findViewsWithText(ArrayList, CharSequence, int)
2807     */
2808    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2809
2810    /**
2811     * Find views that contain {@link AccessibilityNodeProvider}. Such
2812     * a View is a root of virtual view hierarchy and may contain the searched
2813     * text. If this flag is set Views with providers are automatically
2814     * added and it is a responsibility of the client to call the APIs of
2815     * the provider to determine whether the virtual tree rooted at this View
2816     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2817     * representing the virtual views with this text.
2818     *
2819     * @see #findViewsWithText(ArrayList, CharSequence, int)
2820     *
2821     * @hide
2822     */
2823    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2824
2825    /**
2826     * The undefined cursor position.
2827     *
2828     * @hide
2829     */
2830    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2831
2832    /**
2833     * Indicates that the screen has changed state and is now off.
2834     *
2835     * @see #onScreenStateChanged(int)
2836     */
2837    public static final int SCREEN_STATE_OFF = 0x0;
2838
2839    /**
2840     * Indicates that the screen has changed state and is now on.
2841     *
2842     * @see #onScreenStateChanged(int)
2843     */
2844    public static final int SCREEN_STATE_ON = 0x1;
2845
2846    /**
2847     * Controls the over-scroll mode for this view.
2848     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2849     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2850     * and {@link #OVER_SCROLL_NEVER}.
2851     */
2852    private int mOverScrollMode;
2853
2854    /**
2855     * The parent this view is attached to.
2856     * {@hide}
2857     *
2858     * @see #getParent()
2859     */
2860    protected ViewParent mParent;
2861
2862    /**
2863     * {@hide}
2864     */
2865    AttachInfo mAttachInfo;
2866
2867    /**
2868     * {@hide}
2869     */
2870    @ViewDebug.ExportedProperty(flagMapping = {
2871        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2872                name = "FORCE_LAYOUT"),
2873        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2874                name = "LAYOUT_REQUIRED"),
2875        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2876            name = "DRAWING_CACHE_INVALID", outputIf = false),
2877        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2878        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2879        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2880        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2881    })
2882    int mPrivateFlags;
2883    int mPrivateFlags2;
2884    int mPrivateFlags3;
2885
2886    /**
2887     * This view's request for the visibility of the status bar.
2888     * @hide
2889     */
2890    @ViewDebug.ExportedProperty(flagMapping = {
2891        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2892                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2893                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2894        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2895                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2896                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2897        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2898                                equals = SYSTEM_UI_FLAG_VISIBLE,
2899                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2900    })
2901    int mSystemUiVisibility;
2902
2903    /**
2904     * Reference count for transient state.
2905     * @see #setHasTransientState(boolean)
2906     */
2907    int mTransientStateCount = 0;
2908
2909    /**
2910     * Count of how many windows this view has been attached to.
2911     */
2912    int mWindowAttachCount;
2913
2914    /**
2915     * The layout parameters associated with this view and used by the parent
2916     * {@link android.view.ViewGroup} to determine how this view should be
2917     * laid out.
2918     * {@hide}
2919     */
2920    protected ViewGroup.LayoutParams mLayoutParams;
2921
2922    /**
2923     * The view flags hold various views states.
2924     * {@hide}
2925     */
2926    @ViewDebug.ExportedProperty
2927    int mViewFlags;
2928
2929    static class TransformationInfo {
2930        /**
2931         * The transform matrix for the View. This transform is calculated internally
2932         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2933         * is used by default. Do *not* use this variable directly; instead call
2934         * getMatrix(), which will automatically recalculate the matrix if necessary
2935         * to get the correct matrix based on the latest rotation and scale properties.
2936         */
2937        private final Matrix mMatrix = new Matrix();
2938
2939        /**
2940         * The transform matrix for the View. This transform is calculated internally
2941         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2942         * is used by default. Do *not* use this variable directly; instead call
2943         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2944         * to get the correct matrix based on the latest rotation and scale properties.
2945         */
2946        private Matrix mInverseMatrix;
2947
2948        /**
2949         * An internal variable that tracks whether we need to recalculate the
2950         * transform matrix, based on whether the rotation or scaleX/Y properties
2951         * have changed since the matrix was last calculated.
2952         */
2953        boolean mMatrixDirty = false;
2954
2955        /**
2956         * An internal variable that tracks whether we need to recalculate the
2957         * transform matrix, based on whether the rotation or scaleX/Y properties
2958         * have changed since the matrix was last calculated.
2959         */
2960        private boolean mInverseMatrixDirty = true;
2961
2962        /**
2963         * A variable that tracks whether we need to recalculate the
2964         * transform matrix, based on whether the rotation or scaleX/Y properties
2965         * have changed since the matrix was last calculated. This variable
2966         * is only valid after a call to updateMatrix() or to a function that
2967         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2968         */
2969        private boolean mMatrixIsIdentity = true;
2970
2971        /**
2972         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2973         */
2974        private Camera mCamera = null;
2975
2976        /**
2977         * This matrix is used when computing the matrix for 3D rotations.
2978         */
2979        private Matrix matrix3D = null;
2980
2981        /**
2982         * These prev values are used to recalculate a centered pivot point when necessary. The
2983         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2984         * set), so thes values are only used then as well.
2985         */
2986        private int mPrevWidth = -1;
2987        private int mPrevHeight = -1;
2988
2989        /**
2990         * The degrees rotation around the vertical axis through the pivot point.
2991         */
2992        @ViewDebug.ExportedProperty
2993        float mRotationY = 0f;
2994
2995        /**
2996         * The degrees rotation around the horizontal axis through the pivot point.
2997         */
2998        @ViewDebug.ExportedProperty
2999        float mRotationX = 0f;
3000
3001        /**
3002         * The degrees rotation around the pivot point.
3003         */
3004        @ViewDebug.ExportedProperty
3005        float mRotation = 0f;
3006
3007        /**
3008         * The amount of translation of the object away from its left property (post-layout).
3009         */
3010        @ViewDebug.ExportedProperty
3011        float mTranslationX = 0f;
3012
3013        /**
3014         * The amount of translation of the object away from its top property (post-layout).
3015         */
3016        @ViewDebug.ExportedProperty
3017        float mTranslationY = 0f;
3018
3019        @ViewDebug.ExportedProperty
3020        float mTranslationZ = 0f;
3021
3022        /**
3023         * The amount of scale in the x direction around the pivot point. A
3024         * value of 1 means no scaling is applied.
3025         */
3026        @ViewDebug.ExportedProperty
3027        float mScaleX = 1f;
3028
3029        /**
3030         * The amount of scale in the y direction around the pivot point. A
3031         * value of 1 means no scaling is applied.
3032         */
3033        @ViewDebug.ExportedProperty
3034        float mScaleY = 1f;
3035
3036        /**
3037         * The x location of the point around which the view is rotated and scaled.
3038         */
3039        @ViewDebug.ExportedProperty
3040        float mPivotX = 0f;
3041
3042        /**
3043         * The y location of the point around which the view is rotated and scaled.
3044         */
3045        @ViewDebug.ExportedProperty
3046        float mPivotY = 0f;
3047
3048        /**
3049         * The opacity of the View. This is a value from 0 to 1, where 0 means
3050         * completely transparent and 1 means completely opaque.
3051         */
3052        @ViewDebug.ExportedProperty
3053        float mAlpha = 1f;
3054
3055        /**
3056         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3057         * property only used by transitions, which is composited with the other alpha
3058         * values to calculate the final visual alpha value.
3059         */
3060        float mTransitionAlpha = 1f;
3061    }
3062
3063    TransformationInfo mTransformationInfo;
3064
3065    /**
3066     * Current clip bounds. to which all drawing of this view are constrained.
3067     */
3068    private Rect mClipBounds = null;
3069
3070    private boolean mLastIsOpaque;
3071
3072    /**
3073     * Convenience value to check for float values that are close enough to zero to be considered
3074     * zero.
3075     */
3076    private static final float NONZERO_EPSILON = .001f;
3077
3078    /**
3079     * The distance in pixels from the left edge of this view's parent
3080     * to the left edge of this view.
3081     * {@hide}
3082     */
3083    @ViewDebug.ExportedProperty(category = "layout")
3084    protected int mLeft;
3085    /**
3086     * The distance in pixels from the left edge of this view's parent
3087     * to the right edge of this view.
3088     * {@hide}
3089     */
3090    @ViewDebug.ExportedProperty(category = "layout")
3091    protected int mRight;
3092    /**
3093     * The distance in pixels from the top edge of this view's parent
3094     * to the top edge of this view.
3095     * {@hide}
3096     */
3097    @ViewDebug.ExportedProperty(category = "layout")
3098    protected int mTop;
3099    /**
3100     * The distance in pixels from the top edge of this view's parent
3101     * to the bottom edge of this view.
3102     * {@hide}
3103     */
3104    @ViewDebug.ExportedProperty(category = "layout")
3105    protected int mBottom;
3106
3107    /**
3108     * The offset, in pixels, by which the content of this view is scrolled
3109     * horizontally.
3110     * {@hide}
3111     */
3112    @ViewDebug.ExportedProperty(category = "scrolling")
3113    protected int mScrollX;
3114    /**
3115     * The offset, in pixels, by which the content of this view is scrolled
3116     * vertically.
3117     * {@hide}
3118     */
3119    @ViewDebug.ExportedProperty(category = "scrolling")
3120    protected int mScrollY;
3121
3122    /**
3123     * The left padding in pixels, that is the distance in pixels between the
3124     * left edge of this view and the left edge of its content.
3125     * {@hide}
3126     */
3127    @ViewDebug.ExportedProperty(category = "padding")
3128    protected int mPaddingLeft = 0;
3129    /**
3130     * The right padding in pixels, that is the distance in pixels between the
3131     * right edge of this view and the right edge of its content.
3132     * {@hide}
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    protected int mPaddingRight = 0;
3136    /**
3137     * The top padding in pixels, that is the distance in pixels between the
3138     * top edge of this view and the top edge of its content.
3139     * {@hide}
3140     */
3141    @ViewDebug.ExportedProperty(category = "padding")
3142    protected int mPaddingTop;
3143    /**
3144     * The bottom padding in pixels, that is the distance in pixels between the
3145     * bottom edge of this view and the bottom edge of its content.
3146     * {@hide}
3147     */
3148    @ViewDebug.ExportedProperty(category = "padding")
3149    protected int mPaddingBottom;
3150
3151    /**
3152     * The layout insets in pixels, that is the distance in pixels between the
3153     * visible edges of this view its bounds.
3154     */
3155    private Insets mLayoutInsets;
3156
3157    /**
3158     * Briefly describes the view and is primarily used for accessibility support.
3159     */
3160    private CharSequence mContentDescription;
3161
3162    /**
3163     * Specifies the id of a view for which this view serves as a label for
3164     * accessibility purposes.
3165     */
3166    private int mLabelForId = View.NO_ID;
3167
3168    /**
3169     * Predicate for matching labeled view id with its label for
3170     * accessibility purposes.
3171     */
3172    private MatchLabelForPredicate mMatchLabelForPredicate;
3173
3174    /**
3175     * Predicate for matching a view by its id.
3176     */
3177    private MatchIdPredicate mMatchIdPredicate;
3178
3179    /**
3180     * Cache the paddingRight set by the user to append to the scrollbar's size.
3181     *
3182     * @hide
3183     */
3184    @ViewDebug.ExportedProperty(category = "padding")
3185    protected int mUserPaddingRight;
3186
3187    /**
3188     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3189     *
3190     * @hide
3191     */
3192    @ViewDebug.ExportedProperty(category = "padding")
3193    protected int mUserPaddingBottom;
3194
3195    /**
3196     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3197     *
3198     * @hide
3199     */
3200    @ViewDebug.ExportedProperty(category = "padding")
3201    protected int mUserPaddingLeft;
3202
3203    /**
3204     * Cache the paddingStart set by the user to append to the scrollbar's size.
3205     *
3206     */
3207    @ViewDebug.ExportedProperty(category = "padding")
3208    int mUserPaddingStart;
3209
3210    /**
3211     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3212     *
3213     */
3214    @ViewDebug.ExportedProperty(category = "padding")
3215    int mUserPaddingEnd;
3216
3217    /**
3218     * Cache initial left padding.
3219     *
3220     * @hide
3221     */
3222    int mUserPaddingLeftInitial;
3223
3224    /**
3225     * Cache initial right padding.
3226     *
3227     * @hide
3228     */
3229    int mUserPaddingRightInitial;
3230
3231    /**
3232     * Default undefined padding
3233     */
3234    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3235
3236    /**
3237     * Cache if a left padding has been defined
3238     */
3239    private boolean mLeftPaddingDefined = false;
3240
3241    /**
3242     * Cache if a right padding has been defined
3243     */
3244    private boolean mRightPaddingDefined = false;
3245
3246    /**
3247     * @hide
3248     */
3249    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3250    /**
3251     * @hide
3252     */
3253    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3254
3255    private LongSparseLongArray mMeasureCache;
3256
3257    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3258    private Drawable mBackground;
3259
3260    /**
3261     * Display list used for backgrounds.
3262     * <p>
3263     * When non-null and valid, this is expected to contain an up-to-date copy
3264     * of the background drawable. It is cleared on temporary detach and reset
3265     * on cleanup.
3266     */
3267    private RenderNode mBackgroundDisplayList;
3268
3269    private int mBackgroundResource;
3270    private boolean mBackgroundSizeChanged;
3271
3272    static class ListenerInfo {
3273        /**
3274         * Listener used to dispatch focus change events.
3275         * This field should be made private, so it is hidden from the SDK.
3276         * {@hide}
3277         */
3278        protected OnFocusChangeListener mOnFocusChangeListener;
3279
3280        /**
3281         * Listeners for layout change events.
3282         */
3283        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3284
3285        /**
3286         * Listeners for attach events.
3287         */
3288        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3289
3290        /**
3291         * Listener used to dispatch click events.
3292         * This field should be made private, so it is hidden from the SDK.
3293         * {@hide}
3294         */
3295        public OnClickListener mOnClickListener;
3296
3297        /**
3298         * Listener used to dispatch long click events.
3299         * This field should be made private, so it is hidden from the SDK.
3300         * {@hide}
3301         */
3302        protected OnLongClickListener mOnLongClickListener;
3303
3304        /**
3305         * Listener used to build the context menu.
3306         * This field should be made private, so it is hidden from the SDK.
3307         * {@hide}
3308         */
3309        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3310
3311        private OnKeyListener mOnKeyListener;
3312
3313        private OnTouchListener mOnTouchListener;
3314
3315        private OnHoverListener mOnHoverListener;
3316
3317        private OnGenericMotionListener mOnGenericMotionListener;
3318
3319        private OnDragListener mOnDragListener;
3320
3321        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3322
3323        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3324    }
3325
3326    ListenerInfo mListenerInfo;
3327
3328    /**
3329     * The application environment this view lives in.
3330     * This field should be made private, so it is hidden from the SDK.
3331     * {@hide}
3332     */
3333    protected Context mContext;
3334
3335    private final Resources mResources;
3336
3337    private ScrollabilityCache mScrollCache;
3338
3339    private int[] mDrawableState = null;
3340
3341    /**
3342     * Stores the outline of the view, passed down to the DisplayList level for
3343     * defining shadow shape and clipping.
3344     *
3345     * TODO: once RenderNode is long-lived, remove this and rely on native copy.
3346     */
3347    private Outline mOutline;
3348
3349    /**
3350     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3351     * the user may specify which view to go to next.
3352     */
3353    private int mNextFocusLeftId = View.NO_ID;
3354
3355    /**
3356     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3357     * the user may specify which view to go to next.
3358     */
3359    private int mNextFocusRightId = View.NO_ID;
3360
3361    /**
3362     * When this view has focus and the next focus is {@link #FOCUS_UP},
3363     * the user may specify which view to go to next.
3364     */
3365    private int mNextFocusUpId = View.NO_ID;
3366
3367    /**
3368     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3369     * the user may specify which view to go to next.
3370     */
3371    private int mNextFocusDownId = View.NO_ID;
3372
3373    /**
3374     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3375     * the user may specify which view to go to next.
3376     */
3377    int mNextFocusForwardId = View.NO_ID;
3378
3379    private CheckForLongPress mPendingCheckForLongPress;
3380    private CheckForTap mPendingCheckForTap = null;
3381    private PerformClick mPerformClick;
3382    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3383
3384    private UnsetPressedState mUnsetPressedState;
3385
3386    /**
3387     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3388     * up event while a long press is invoked as soon as the long press duration is reached, so
3389     * a long press could be performed before the tap is checked, in which case the tap's action
3390     * should not be invoked.
3391     */
3392    private boolean mHasPerformedLongPress;
3393
3394    /**
3395     * The minimum height of the view. We'll try our best to have the height
3396     * of this view to at least this amount.
3397     */
3398    @ViewDebug.ExportedProperty(category = "measurement")
3399    private int mMinHeight;
3400
3401    /**
3402     * The minimum width of the view. We'll try our best to have the width
3403     * of this view to at least this amount.
3404     */
3405    @ViewDebug.ExportedProperty(category = "measurement")
3406    private int mMinWidth;
3407
3408    /**
3409     * The delegate to handle touch events that are physically in this view
3410     * but should be handled by another view.
3411     */
3412    private TouchDelegate mTouchDelegate = null;
3413
3414    /**
3415     * Solid color to use as a background when creating the drawing cache. Enables
3416     * the cache to use 16 bit bitmaps instead of 32 bit.
3417     */
3418    private int mDrawingCacheBackgroundColor = 0;
3419
3420    /**
3421     * Special tree observer used when mAttachInfo is null.
3422     */
3423    private ViewTreeObserver mFloatingTreeObserver;
3424
3425    /**
3426     * Cache the touch slop from the context that created the view.
3427     */
3428    private int mTouchSlop;
3429
3430    /**
3431     * Object that handles automatic animation of view properties.
3432     */
3433    private ViewPropertyAnimator mAnimator = null;
3434
3435    /**
3436     * Flag indicating that a drag can cross window boundaries.  When
3437     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3438     * with this flag set, all visible applications will be able to participate
3439     * in the drag operation and receive the dragged content.
3440     *
3441     * @hide
3442     */
3443    public static final int DRAG_FLAG_GLOBAL = 1;
3444
3445    /**
3446     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3447     */
3448    private float mVerticalScrollFactor;
3449
3450    /**
3451     * Position of the vertical scroll bar.
3452     */
3453    private int mVerticalScrollbarPosition;
3454
3455    /**
3456     * Position the scroll bar at the default position as determined by the system.
3457     */
3458    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3459
3460    /**
3461     * Position the scroll bar along the left edge.
3462     */
3463    public static final int SCROLLBAR_POSITION_LEFT = 1;
3464
3465    /**
3466     * Position the scroll bar along the right edge.
3467     */
3468    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3469
3470    /**
3471     * Indicates that the view does not have a layer.
3472     *
3473     * @see #getLayerType()
3474     * @see #setLayerType(int, android.graphics.Paint)
3475     * @see #LAYER_TYPE_SOFTWARE
3476     * @see #LAYER_TYPE_HARDWARE
3477     */
3478    public static final int LAYER_TYPE_NONE = 0;
3479
3480    /**
3481     * <p>Indicates that the view has a software layer. A software layer is backed
3482     * by a bitmap and causes the view to be rendered using Android's software
3483     * rendering pipeline, even if hardware acceleration is enabled.</p>
3484     *
3485     * <p>Software layers have various usages:</p>
3486     * <p>When the application is not using hardware acceleration, a software layer
3487     * is useful to apply a specific color filter and/or blending mode and/or
3488     * translucency to a view and all its children.</p>
3489     * <p>When the application is using hardware acceleration, a software layer
3490     * is useful to render drawing primitives not supported by the hardware
3491     * accelerated pipeline. It can also be used to cache a complex view tree
3492     * into a texture and reduce the complexity of drawing operations. For instance,
3493     * when animating a complex view tree with a translation, a software layer can
3494     * be used to render the view tree only once.</p>
3495     * <p>Software layers should be avoided when the affected view tree updates
3496     * often. Every update will require to re-render the software layer, which can
3497     * potentially be slow (particularly when hardware acceleration is turned on
3498     * since the layer will have to be uploaded into a hardware texture after every
3499     * update.)</p>
3500     *
3501     * @see #getLayerType()
3502     * @see #setLayerType(int, android.graphics.Paint)
3503     * @see #LAYER_TYPE_NONE
3504     * @see #LAYER_TYPE_HARDWARE
3505     */
3506    public static final int LAYER_TYPE_SOFTWARE = 1;
3507
3508    /**
3509     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3510     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3511     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3512     * rendering pipeline, but only if hardware acceleration is turned on for the
3513     * view hierarchy. When hardware acceleration is turned off, hardware layers
3514     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3515     *
3516     * <p>A hardware layer is useful to apply a specific color filter and/or
3517     * blending mode and/or translucency to a view and all its children.</p>
3518     * <p>A hardware layer can be used to cache a complex view tree into a
3519     * texture and reduce the complexity of drawing operations. For instance,
3520     * when animating a complex view tree with a translation, a hardware layer can
3521     * be used to render the view tree only once.</p>
3522     * <p>A hardware layer can also be used to increase the rendering quality when
3523     * rotation transformations are applied on a view. It can also be used to
3524     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3525     *
3526     * @see #getLayerType()
3527     * @see #setLayerType(int, android.graphics.Paint)
3528     * @see #LAYER_TYPE_NONE
3529     * @see #LAYER_TYPE_SOFTWARE
3530     */
3531    public static final int LAYER_TYPE_HARDWARE = 2;
3532
3533    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3534            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3535            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3536            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3537    })
3538    int mLayerType = LAYER_TYPE_NONE;
3539    Paint mLayerPaint;
3540    Rect mLocalDirtyRect;
3541    private HardwareLayer mHardwareLayer;
3542
3543    /**
3544     * Set to true when drawing cache is enabled and cannot be created.
3545     *
3546     * @hide
3547     */
3548    public boolean mCachingFailed;
3549    private Bitmap mDrawingCache;
3550    private Bitmap mUnscaledDrawingCache;
3551
3552    /**
3553     * Display list used for the View content.
3554     * <p>
3555     * When non-null and valid, this is expected to contain an up-to-date copy
3556     * of the View content. It is cleared on temporary detach and reset on
3557     * cleanup.
3558     */
3559    RenderNode mDisplayList;
3560
3561    /**
3562     * Set to true when the view is sending hover accessibility events because it
3563     * is the innermost hovered view.
3564     */
3565    private boolean mSendingHoverAccessibilityEvents;
3566
3567    /**
3568     * Delegate for injecting accessibility functionality.
3569     */
3570    AccessibilityDelegate mAccessibilityDelegate;
3571
3572    /**
3573     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3574     * and add/remove objects to/from the overlay directly through the Overlay methods.
3575     */
3576    ViewOverlay mOverlay;
3577
3578    /**
3579     * Consistency verifier for debugging purposes.
3580     * @hide
3581     */
3582    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3583            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3584                    new InputEventConsistencyVerifier(this, 0) : null;
3585
3586    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3587
3588    /**
3589     * Simple constructor to use when creating a view from code.
3590     *
3591     * @param context The Context the view is running in, through which it can
3592     *        access the current theme, resources, etc.
3593     */
3594    public View(Context context) {
3595        mContext = context;
3596        mResources = context != null ? context.getResources() : null;
3597        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3598        // Set some flags defaults
3599        mPrivateFlags2 =
3600                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3601                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3602                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3603                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3604                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3605                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3606        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3607        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3608        mUserPaddingStart = UNDEFINED_PADDING;
3609        mUserPaddingEnd = UNDEFINED_PADDING;
3610
3611        if (!sCompatibilityDone && context != null) {
3612            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3613
3614            // Older apps may need this compatibility hack for measurement.
3615            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3616
3617            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3618            // of whether a layout was requested on that View.
3619            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3620
3621            sCompatibilityDone = true;
3622        }
3623    }
3624
3625    /**
3626     * Constructor that is called when inflating a view from XML. This is called
3627     * when a view is being constructed from an XML file, supplying attributes
3628     * that were specified in the XML file. This version uses a default style of
3629     * 0, so the only attribute values applied are those in the Context's Theme
3630     * and the given AttributeSet.
3631     *
3632     * <p>
3633     * The method onFinishInflate() will be called after all children have been
3634     * added.
3635     *
3636     * @param context The Context the view is running in, through which it can
3637     *        access the current theme, resources, etc.
3638     * @param attrs The attributes of the XML tag that is inflating the view.
3639     * @see #View(Context, AttributeSet, int)
3640     */
3641    public View(Context context, AttributeSet attrs) {
3642        this(context, attrs, 0);
3643    }
3644
3645    /**
3646     * Perform inflation from XML and apply a class-specific base style from a
3647     * theme attribute. This constructor of View allows subclasses to use their
3648     * own base style when they are inflating. For example, a Button class's
3649     * constructor would call this version of the super class constructor and
3650     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3651     * allows the theme's button style to modify all of the base view attributes
3652     * (in particular its background) as well as the Button class's attributes.
3653     *
3654     * @param context The Context the view is running in, through which it can
3655     *        access the current theme, resources, etc.
3656     * @param attrs The attributes of the XML tag that is inflating the view.
3657     * @param defStyleAttr An attribute in the current theme that contains a
3658     *        reference to a style resource that supplies default values for
3659     *        the view. Can be 0 to not look for defaults.
3660     * @see #View(Context, AttributeSet)
3661     */
3662    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3663        this(context, attrs, defStyleAttr, 0);
3664    }
3665
3666    /**
3667     * Perform inflation from XML and apply a class-specific base style from a
3668     * theme attribute or style resource. This constructor of View allows
3669     * subclasses to use their own base style when they are inflating.
3670     * <p>
3671     * When determining the final value of a particular attribute, there are
3672     * four inputs that come into play:
3673     * <ol>
3674     * <li>Any attribute values in the given AttributeSet.
3675     * <li>The style resource specified in the AttributeSet (named "style").
3676     * <li>The default style specified by <var>defStyleAttr</var>.
3677     * <li>The default style specified by <var>defStyleRes</var>.
3678     * <li>The base values in this theme.
3679     * </ol>
3680     * <p>
3681     * Each of these inputs is considered in-order, with the first listed taking
3682     * precedence over the following ones. In other words, if in the
3683     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3684     * , then the button's text will <em>always</em> be black, regardless of
3685     * what is specified in any of the styles.
3686     *
3687     * @param context The Context the view is running in, through which it can
3688     *        access the current theme, resources, etc.
3689     * @param attrs The attributes of the XML tag that is inflating the view.
3690     * @param defStyleAttr An attribute in the current theme that contains a
3691     *        reference to a style resource that supplies default values for
3692     *        the view. Can be 0 to not look for defaults.
3693     * @param defStyleRes A resource identifier of a style resource that
3694     *        supplies default values for the view, used only if
3695     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3696     *        to not look for defaults.
3697     * @see #View(Context, AttributeSet, int)
3698     */
3699    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3700        this(context);
3701
3702        final TypedArray a = context.obtainStyledAttributes(
3703                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3704
3705        Drawable background = null;
3706
3707        int leftPadding = -1;
3708        int topPadding = -1;
3709        int rightPadding = -1;
3710        int bottomPadding = -1;
3711        int startPadding = UNDEFINED_PADDING;
3712        int endPadding = UNDEFINED_PADDING;
3713
3714        int padding = -1;
3715
3716        int viewFlagValues = 0;
3717        int viewFlagMasks = 0;
3718
3719        boolean setScrollContainer = false;
3720
3721        int x = 0;
3722        int y = 0;
3723
3724        float tx = 0;
3725        float ty = 0;
3726        float tz = 0;
3727        float rotation = 0;
3728        float rotationX = 0;
3729        float rotationY = 0;
3730        float sx = 1f;
3731        float sy = 1f;
3732        boolean transformSet = false;
3733
3734        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3735        int overScrollMode = mOverScrollMode;
3736        boolean initializeScrollbars = false;
3737
3738        boolean startPaddingDefined = false;
3739        boolean endPaddingDefined = false;
3740        boolean leftPaddingDefined = false;
3741        boolean rightPaddingDefined = false;
3742
3743        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3744
3745        final int N = a.getIndexCount();
3746        for (int i = 0; i < N; i++) {
3747            int attr = a.getIndex(i);
3748            switch (attr) {
3749                case com.android.internal.R.styleable.View_background:
3750                    background = a.getDrawable(attr);
3751                    break;
3752                case com.android.internal.R.styleable.View_padding:
3753                    padding = a.getDimensionPixelSize(attr, -1);
3754                    mUserPaddingLeftInitial = padding;
3755                    mUserPaddingRightInitial = padding;
3756                    leftPaddingDefined = true;
3757                    rightPaddingDefined = true;
3758                    break;
3759                 case com.android.internal.R.styleable.View_paddingLeft:
3760                    leftPadding = a.getDimensionPixelSize(attr, -1);
3761                    mUserPaddingLeftInitial = leftPadding;
3762                    leftPaddingDefined = true;
3763                    break;
3764                case com.android.internal.R.styleable.View_paddingTop:
3765                    topPadding = a.getDimensionPixelSize(attr, -1);
3766                    break;
3767                case com.android.internal.R.styleable.View_paddingRight:
3768                    rightPadding = a.getDimensionPixelSize(attr, -1);
3769                    mUserPaddingRightInitial = rightPadding;
3770                    rightPaddingDefined = true;
3771                    break;
3772                case com.android.internal.R.styleable.View_paddingBottom:
3773                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3774                    break;
3775                case com.android.internal.R.styleable.View_paddingStart:
3776                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3777                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3778                    break;
3779                case com.android.internal.R.styleable.View_paddingEnd:
3780                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3781                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3782                    break;
3783                case com.android.internal.R.styleable.View_scrollX:
3784                    x = a.getDimensionPixelOffset(attr, 0);
3785                    break;
3786                case com.android.internal.R.styleable.View_scrollY:
3787                    y = a.getDimensionPixelOffset(attr, 0);
3788                    break;
3789                case com.android.internal.R.styleable.View_alpha:
3790                    setAlpha(a.getFloat(attr, 1f));
3791                    break;
3792                case com.android.internal.R.styleable.View_transformPivotX:
3793                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3794                    break;
3795                case com.android.internal.R.styleable.View_transformPivotY:
3796                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3797                    break;
3798                case com.android.internal.R.styleable.View_translationX:
3799                    tx = a.getDimensionPixelOffset(attr, 0);
3800                    transformSet = true;
3801                    break;
3802                case com.android.internal.R.styleable.View_translationY:
3803                    ty = a.getDimensionPixelOffset(attr, 0);
3804                    transformSet = true;
3805                    break;
3806                case com.android.internal.R.styleable.View_translationZ:
3807                    tz = a.getDimensionPixelOffset(attr, 0);
3808                    transformSet = true;
3809                    break;
3810                case com.android.internal.R.styleable.View_rotation:
3811                    rotation = a.getFloat(attr, 0);
3812                    transformSet = true;
3813                    break;
3814                case com.android.internal.R.styleable.View_rotationX:
3815                    rotationX = a.getFloat(attr, 0);
3816                    transformSet = true;
3817                    break;
3818                case com.android.internal.R.styleable.View_rotationY:
3819                    rotationY = a.getFloat(attr, 0);
3820                    transformSet = true;
3821                    break;
3822                case com.android.internal.R.styleable.View_scaleX:
3823                    sx = a.getFloat(attr, 1f);
3824                    transformSet = true;
3825                    break;
3826                case com.android.internal.R.styleable.View_scaleY:
3827                    sy = a.getFloat(attr, 1f);
3828                    transformSet = true;
3829                    break;
3830                case com.android.internal.R.styleable.View_id:
3831                    mID = a.getResourceId(attr, NO_ID);
3832                    break;
3833                case com.android.internal.R.styleable.View_tag:
3834                    mTag = a.getText(attr);
3835                    break;
3836                case com.android.internal.R.styleable.View_fitsSystemWindows:
3837                    if (a.getBoolean(attr, false)) {
3838                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3839                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3840                    }
3841                    break;
3842                case com.android.internal.R.styleable.View_focusable:
3843                    if (a.getBoolean(attr, false)) {
3844                        viewFlagValues |= FOCUSABLE;
3845                        viewFlagMasks |= FOCUSABLE_MASK;
3846                    }
3847                    break;
3848                case com.android.internal.R.styleable.View_focusableInTouchMode:
3849                    if (a.getBoolean(attr, false)) {
3850                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3851                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3852                    }
3853                    break;
3854                case com.android.internal.R.styleable.View_clickable:
3855                    if (a.getBoolean(attr, false)) {
3856                        viewFlagValues |= CLICKABLE;
3857                        viewFlagMasks |= CLICKABLE;
3858                    }
3859                    break;
3860                case com.android.internal.R.styleable.View_longClickable:
3861                    if (a.getBoolean(attr, false)) {
3862                        viewFlagValues |= LONG_CLICKABLE;
3863                        viewFlagMasks |= LONG_CLICKABLE;
3864                    }
3865                    break;
3866                case com.android.internal.R.styleable.View_saveEnabled:
3867                    if (!a.getBoolean(attr, true)) {
3868                        viewFlagValues |= SAVE_DISABLED;
3869                        viewFlagMasks |= SAVE_DISABLED_MASK;
3870                    }
3871                    break;
3872                case com.android.internal.R.styleable.View_duplicateParentState:
3873                    if (a.getBoolean(attr, false)) {
3874                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3875                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3876                    }
3877                    break;
3878                case com.android.internal.R.styleable.View_visibility:
3879                    final int visibility = a.getInt(attr, 0);
3880                    if (visibility != 0) {
3881                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3882                        viewFlagMasks |= VISIBILITY_MASK;
3883                    }
3884                    break;
3885                case com.android.internal.R.styleable.View_layoutDirection:
3886                    // Clear any layout direction flags (included resolved bits) already set
3887                    mPrivateFlags2 &=
3888                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3889                    // Set the layout direction flags depending on the value of the attribute
3890                    final int layoutDirection = a.getInt(attr, -1);
3891                    final int value = (layoutDirection != -1) ?
3892                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3893                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3894                    break;
3895                case com.android.internal.R.styleable.View_drawingCacheQuality:
3896                    final int cacheQuality = a.getInt(attr, 0);
3897                    if (cacheQuality != 0) {
3898                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3899                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3900                    }
3901                    break;
3902                case com.android.internal.R.styleable.View_contentDescription:
3903                    setContentDescription(a.getString(attr));
3904                    break;
3905                case com.android.internal.R.styleable.View_labelFor:
3906                    setLabelFor(a.getResourceId(attr, NO_ID));
3907                    break;
3908                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3909                    if (!a.getBoolean(attr, true)) {
3910                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3911                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3912                    }
3913                    break;
3914                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3915                    if (!a.getBoolean(attr, true)) {
3916                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3917                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3918                    }
3919                    break;
3920                case R.styleable.View_scrollbars:
3921                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3922                    if (scrollbars != SCROLLBARS_NONE) {
3923                        viewFlagValues |= scrollbars;
3924                        viewFlagMasks |= SCROLLBARS_MASK;
3925                        initializeScrollbars = true;
3926                    }
3927                    break;
3928                //noinspection deprecation
3929                case R.styleable.View_fadingEdge:
3930                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3931                        // Ignore the attribute starting with ICS
3932                        break;
3933                    }
3934                    // With builds < ICS, fall through and apply fading edges
3935                case R.styleable.View_requiresFadingEdge:
3936                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3937                    if (fadingEdge != FADING_EDGE_NONE) {
3938                        viewFlagValues |= fadingEdge;
3939                        viewFlagMasks |= FADING_EDGE_MASK;
3940                        initializeFadingEdge(a);
3941                    }
3942                    break;
3943                case R.styleable.View_scrollbarStyle:
3944                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3945                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3946                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3947                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3948                    }
3949                    break;
3950                case R.styleable.View_isScrollContainer:
3951                    setScrollContainer = true;
3952                    if (a.getBoolean(attr, false)) {
3953                        setScrollContainer(true);
3954                    }
3955                    break;
3956                case com.android.internal.R.styleable.View_keepScreenOn:
3957                    if (a.getBoolean(attr, false)) {
3958                        viewFlagValues |= KEEP_SCREEN_ON;
3959                        viewFlagMasks |= KEEP_SCREEN_ON;
3960                    }
3961                    break;
3962                case R.styleable.View_filterTouchesWhenObscured:
3963                    if (a.getBoolean(attr, false)) {
3964                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3965                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3966                    }
3967                    break;
3968                case R.styleable.View_nextFocusLeft:
3969                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3970                    break;
3971                case R.styleable.View_nextFocusRight:
3972                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3973                    break;
3974                case R.styleable.View_nextFocusUp:
3975                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3976                    break;
3977                case R.styleable.View_nextFocusDown:
3978                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3979                    break;
3980                case R.styleable.View_nextFocusForward:
3981                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3982                    break;
3983                case R.styleable.View_minWidth:
3984                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3985                    break;
3986                case R.styleable.View_minHeight:
3987                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3988                    break;
3989                case R.styleable.View_onClick:
3990                    if (context.isRestricted()) {
3991                        throw new IllegalStateException("The android:onClick attribute cannot "
3992                                + "be used within a restricted context");
3993                    }
3994
3995                    final String handlerName = a.getString(attr);
3996                    if (handlerName != null) {
3997                        setOnClickListener(new OnClickListener() {
3998                            private Method mHandler;
3999
4000                            public void onClick(View v) {
4001                                if (mHandler == null) {
4002                                    try {
4003                                        mHandler = getContext().getClass().getMethod(handlerName,
4004                                                View.class);
4005                                    } catch (NoSuchMethodException e) {
4006                                        int id = getId();
4007                                        String idText = id == NO_ID ? "" : " with id '"
4008                                                + getContext().getResources().getResourceEntryName(
4009                                                    id) + "'";
4010                                        throw new IllegalStateException("Could not find a method " +
4011                                                handlerName + "(View) in the activity "
4012                                                + getContext().getClass() + " for onClick handler"
4013                                                + " on view " + View.this.getClass() + idText, e);
4014                                    }
4015                                }
4016
4017                                try {
4018                                    mHandler.invoke(getContext(), View.this);
4019                                } catch (IllegalAccessException e) {
4020                                    throw new IllegalStateException("Could not execute non "
4021                                            + "public method of the activity", e);
4022                                } catch (InvocationTargetException e) {
4023                                    throw new IllegalStateException("Could not execute "
4024                                            + "method of the activity", e);
4025                                }
4026                            }
4027                        });
4028                    }
4029                    break;
4030                case R.styleable.View_overScrollMode:
4031                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4032                    break;
4033                case R.styleable.View_verticalScrollbarPosition:
4034                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4035                    break;
4036                case R.styleable.View_layerType:
4037                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4038                    break;
4039                case R.styleable.View_textDirection:
4040                    // Clear any text direction flag already set
4041                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4042                    // Set the text direction flags depending on the value of the attribute
4043                    final int textDirection = a.getInt(attr, -1);
4044                    if (textDirection != -1) {
4045                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4046                    }
4047                    break;
4048                case R.styleable.View_textAlignment:
4049                    // Clear any text alignment flag already set
4050                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4051                    // Set the text alignment flag depending on the value of the attribute
4052                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4053                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4054                    break;
4055                case R.styleable.View_importantForAccessibility:
4056                    setImportantForAccessibility(a.getInt(attr,
4057                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4058                    break;
4059                case R.styleable.View_accessibilityLiveRegion:
4060                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4061                    break;
4062                case R.styleable.View_sharedElementName:
4063                    setSharedElementName(a.getString(attr));
4064                    break;
4065            }
4066        }
4067
4068        setOverScrollMode(overScrollMode);
4069
4070        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4071        // the resolved layout direction). Those cached values will be used later during padding
4072        // resolution.
4073        mUserPaddingStart = startPadding;
4074        mUserPaddingEnd = endPadding;
4075
4076        if (background != null) {
4077            setBackground(background);
4078        }
4079
4080        // setBackground above will record that padding is currently provided by the background.
4081        // If we have padding specified via xml, record that here instead and use it.
4082        mLeftPaddingDefined = leftPaddingDefined;
4083        mRightPaddingDefined = rightPaddingDefined;
4084
4085        if (padding >= 0) {
4086            leftPadding = padding;
4087            topPadding = padding;
4088            rightPadding = padding;
4089            bottomPadding = padding;
4090            mUserPaddingLeftInitial = padding;
4091            mUserPaddingRightInitial = padding;
4092        }
4093
4094        if (isRtlCompatibilityMode()) {
4095            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4096            // left / right padding are used if defined (meaning here nothing to do). If they are not
4097            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4098            // start / end and resolve them as left / right (layout direction is not taken into account).
4099            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4100            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4101            // defined.
4102            if (!mLeftPaddingDefined && startPaddingDefined) {
4103                leftPadding = startPadding;
4104            }
4105            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4106            if (!mRightPaddingDefined && endPaddingDefined) {
4107                rightPadding = endPadding;
4108            }
4109            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4110        } else {
4111            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4112            // values defined. Otherwise, left /right values are used.
4113            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4114            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4115            // defined.
4116            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4117
4118            if (mLeftPaddingDefined && !hasRelativePadding) {
4119                mUserPaddingLeftInitial = leftPadding;
4120            }
4121            if (mRightPaddingDefined && !hasRelativePadding) {
4122                mUserPaddingRightInitial = rightPadding;
4123            }
4124        }
4125
4126        internalSetPadding(
4127                mUserPaddingLeftInitial,
4128                topPadding >= 0 ? topPadding : mPaddingTop,
4129                mUserPaddingRightInitial,
4130                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4131
4132        if (viewFlagMasks != 0) {
4133            setFlags(viewFlagValues, viewFlagMasks);
4134        }
4135
4136        if (initializeScrollbars) {
4137            initializeScrollbars(a);
4138        }
4139
4140        a.recycle();
4141
4142        // Needs to be called after mViewFlags is set
4143        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4144            recomputePadding();
4145        }
4146
4147        if (x != 0 || y != 0) {
4148            scrollTo(x, y);
4149        }
4150
4151        if (transformSet) {
4152            setTranslationX(tx);
4153            setTranslationY(ty);
4154            setTranslationZ(tz);
4155            setRotation(rotation);
4156            setRotationX(rotationX);
4157            setRotationY(rotationY);
4158            setScaleX(sx);
4159            setScaleY(sy);
4160        }
4161
4162        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4163            setScrollContainer(true);
4164        }
4165
4166        computeOpaqueFlags();
4167    }
4168
4169    /**
4170     * Non-public constructor for use in testing
4171     */
4172    View() {
4173        mResources = null;
4174    }
4175
4176    public String toString() {
4177        StringBuilder out = new StringBuilder(128);
4178        out.append(getClass().getName());
4179        out.append('{');
4180        out.append(Integer.toHexString(System.identityHashCode(this)));
4181        out.append(' ');
4182        switch (mViewFlags&VISIBILITY_MASK) {
4183            case VISIBLE: out.append('V'); break;
4184            case INVISIBLE: out.append('I'); break;
4185            case GONE: out.append('G'); break;
4186            default: out.append('.'); break;
4187        }
4188        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4189        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4190        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4191        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4192        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4193        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4194        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4195        out.append(' ');
4196        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4197        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4198        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4199        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4200            out.append('p');
4201        } else {
4202            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4203        }
4204        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4205        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4206        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4207        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4208        out.append(' ');
4209        out.append(mLeft);
4210        out.append(',');
4211        out.append(mTop);
4212        out.append('-');
4213        out.append(mRight);
4214        out.append(',');
4215        out.append(mBottom);
4216        final int id = getId();
4217        if (id != NO_ID) {
4218            out.append(" #");
4219            out.append(Integer.toHexString(id));
4220            final Resources r = mResources;
4221            if (id != 0 && r != null) {
4222                try {
4223                    String pkgname;
4224                    switch (id&0xff000000) {
4225                        case 0x7f000000:
4226                            pkgname="app";
4227                            break;
4228                        case 0x01000000:
4229                            pkgname="android";
4230                            break;
4231                        default:
4232                            pkgname = r.getResourcePackageName(id);
4233                            break;
4234                    }
4235                    String typename = r.getResourceTypeName(id);
4236                    String entryname = r.getResourceEntryName(id);
4237                    out.append(" ");
4238                    out.append(pkgname);
4239                    out.append(":");
4240                    out.append(typename);
4241                    out.append("/");
4242                    out.append(entryname);
4243                } catch (Resources.NotFoundException e) {
4244                }
4245            }
4246        }
4247        out.append("}");
4248        return out.toString();
4249    }
4250
4251    /**
4252     * <p>
4253     * Initializes the fading edges from a given set of styled attributes. This
4254     * method should be called by subclasses that need fading edges and when an
4255     * instance of these subclasses is created programmatically rather than
4256     * being inflated from XML. This method is automatically called when the XML
4257     * is inflated.
4258     * </p>
4259     *
4260     * @param a the styled attributes set to initialize the fading edges from
4261     */
4262    protected void initializeFadingEdge(TypedArray a) {
4263        initScrollCache();
4264
4265        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4266                R.styleable.View_fadingEdgeLength,
4267                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4268    }
4269
4270    /**
4271     * Returns the size of the vertical faded edges used to indicate that more
4272     * content in this view is visible.
4273     *
4274     * @return The size in pixels of the vertical faded edge or 0 if vertical
4275     *         faded edges are not enabled for this view.
4276     * @attr ref android.R.styleable#View_fadingEdgeLength
4277     */
4278    public int getVerticalFadingEdgeLength() {
4279        if (isVerticalFadingEdgeEnabled()) {
4280            ScrollabilityCache cache = mScrollCache;
4281            if (cache != null) {
4282                return cache.fadingEdgeLength;
4283            }
4284        }
4285        return 0;
4286    }
4287
4288    /**
4289     * Set the size of the faded edge used to indicate that more content in this
4290     * view is available.  Will not change whether the fading edge is enabled; use
4291     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4292     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4293     * for the vertical or horizontal fading edges.
4294     *
4295     * @param length The size in pixels of the faded edge used to indicate that more
4296     *        content in this view is visible.
4297     */
4298    public void setFadingEdgeLength(int length) {
4299        initScrollCache();
4300        mScrollCache.fadingEdgeLength = length;
4301    }
4302
4303    /**
4304     * Returns the size of the horizontal faded edges used to indicate that more
4305     * content in this view is visible.
4306     *
4307     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4308     *         faded edges are not enabled for this view.
4309     * @attr ref android.R.styleable#View_fadingEdgeLength
4310     */
4311    public int getHorizontalFadingEdgeLength() {
4312        if (isHorizontalFadingEdgeEnabled()) {
4313            ScrollabilityCache cache = mScrollCache;
4314            if (cache != null) {
4315                return cache.fadingEdgeLength;
4316            }
4317        }
4318        return 0;
4319    }
4320
4321    /**
4322     * Returns the width of the vertical scrollbar.
4323     *
4324     * @return The width in pixels of the vertical scrollbar or 0 if there
4325     *         is no vertical scrollbar.
4326     */
4327    public int getVerticalScrollbarWidth() {
4328        ScrollabilityCache cache = mScrollCache;
4329        if (cache != null) {
4330            ScrollBarDrawable scrollBar = cache.scrollBar;
4331            if (scrollBar != null) {
4332                int size = scrollBar.getSize(true);
4333                if (size <= 0) {
4334                    size = cache.scrollBarSize;
4335                }
4336                return size;
4337            }
4338            return 0;
4339        }
4340        return 0;
4341    }
4342
4343    /**
4344     * Returns the height of the horizontal scrollbar.
4345     *
4346     * @return The height in pixels of the horizontal scrollbar or 0 if
4347     *         there is no horizontal scrollbar.
4348     */
4349    protected int getHorizontalScrollbarHeight() {
4350        ScrollabilityCache cache = mScrollCache;
4351        if (cache != null) {
4352            ScrollBarDrawable scrollBar = cache.scrollBar;
4353            if (scrollBar != null) {
4354                int size = scrollBar.getSize(false);
4355                if (size <= 0) {
4356                    size = cache.scrollBarSize;
4357                }
4358                return size;
4359            }
4360            return 0;
4361        }
4362        return 0;
4363    }
4364
4365    /**
4366     * <p>
4367     * Initializes the scrollbars from a given set of styled attributes. This
4368     * method should be called by subclasses that need scrollbars and when an
4369     * instance of these subclasses is created programmatically rather than
4370     * being inflated from XML. This method is automatically called when the XML
4371     * is inflated.
4372     * </p>
4373     *
4374     * @param a the styled attributes set to initialize the scrollbars from
4375     */
4376    protected void initializeScrollbars(TypedArray a) {
4377        initScrollCache();
4378
4379        final ScrollabilityCache scrollabilityCache = mScrollCache;
4380
4381        if (scrollabilityCache.scrollBar == null) {
4382            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4383        }
4384
4385        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4386
4387        if (!fadeScrollbars) {
4388            scrollabilityCache.state = ScrollabilityCache.ON;
4389        }
4390        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4391
4392
4393        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4394                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4395                        .getScrollBarFadeDuration());
4396        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4397                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4398                ViewConfiguration.getScrollDefaultDelay());
4399
4400
4401        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4402                com.android.internal.R.styleable.View_scrollbarSize,
4403                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4404
4405        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4406        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4407
4408        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4409        if (thumb != null) {
4410            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4411        }
4412
4413        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4414                false);
4415        if (alwaysDraw) {
4416            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4417        }
4418
4419        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4420        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4421
4422        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4423        if (thumb != null) {
4424            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4425        }
4426
4427        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4428                false);
4429        if (alwaysDraw) {
4430            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4431        }
4432
4433        // Apply layout direction to the new Drawables if needed
4434        final int layoutDirection = getLayoutDirection();
4435        if (track != null) {
4436            track.setLayoutDirection(layoutDirection);
4437        }
4438        if (thumb != null) {
4439            thumb.setLayoutDirection(layoutDirection);
4440        }
4441
4442        // Re-apply user/background padding so that scrollbar(s) get added
4443        resolvePadding();
4444    }
4445
4446    /**
4447     * <p>
4448     * Initalizes the scrollability cache if necessary.
4449     * </p>
4450     */
4451    private void initScrollCache() {
4452        if (mScrollCache == null) {
4453            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4454        }
4455    }
4456
4457    private ScrollabilityCache getScrollCache() {
4458        initScrollCache();
4459        return mScrollCache;
4460    }
4461
4462    /**
4463     * Set the position of the vertical scroll bar. Should be one of
4464     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4465     * {@link #SCROLLBAR_POSITION_RIGHT}.
4466     *
4467     * @param position Where the vertical scroll bar should be positioned.
4468     */
4469    public void setVerticalScrollbarPosition(int position) {
4470        if (mVerticalScrollbarPosition != position) {
4471            mVerticalScrollbarPosition = position;
4472            computeOpaqueFlags();
4473            resolvePadding();
4474        }
4475    }
4476
4477    /**
4478     * @return The position where the vertical scroll bar will show, if applicable.
4479     * @see #setVerticalScrollbarPosition(int)
4480     */
4481    public int getVerticalScrollbarPosition() {
4482        return mVerticalScrollbarPosition;
4483    }
4484
4485    ListenerInfo getListenerInfo() {
4486        if (mListenerInfo != null) {
4487            return mListenerInfo;
4488        }
4489        mListenerInfo = new ListenerInfo();
4490        return mListenerInfo;
4491    }
4492
4493    /**
4494     * Register a callback to be invoked when focus of this view changed.
4495     *
4496     * @param l The callback that will run.
4497     */
4498    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4499        getListenerInfo().mOnFocusChangeListener = l;
4500    }
4501
4502    /**
4503     * Add a listener that will be called when the bounds of the view change due to
4504     * layout processing.
4505     *
4506     * @param listener The listener that will be called when layout bounds change.
4507     */
4508    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4509        ListenerInfo li = getListenerInfo();
4510        if (li.mOnLayoutChangeListeners == null) {
4511            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4512        }
4513        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4514            li.mOnLayoutChangeListeners.add(listener);
4515        }
4516    }
4517
4518    /**
4519     * Remove a listener for layout changes.
4520     *
4521     * @param listener The listener for layout bounds change.
4522     */
4523    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4524        ListenerInfo li = mListenerInfo;
4525        if (li == null || li.mOnLayoutChangeListeners == null) {
4526            return;
4527        }
4528        li.mOnLayoutChangeListeners.remove(listener);
4529    }
4530
4531    /**
4532     * Add a listener for attach state changes.
4533     *
4534     * This listener will be called whenever this view is attached or detached
4535     * from a window. Remove the listener using
4536     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4537     *
4538     * @param listener Listener to attach
4539     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4540     */
4541    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4542        ListenerInfo li = getListenerInfo();
4543        if (li.mOnAttachStateChangeListeners == null) {
4544            li.mOnAttachStateChangeListeners
4545                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4546        }
4547        li.mOnAttachStateChangeListeners.add(listener);
4548    }
4549
4550    /**
4551     * Remove a listener for attach state changes. The listener will receive no further
4552     * notification of window attach/detach events.
4553     *
4554     * @param listener Listener to remove
4555     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4556     */
4557    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4558        ListenerInfo li = mListenerInfo;
4559        if (li == null || li.mOnAttachStateChangeListeners == null) {
4560            return;
4561        }
4562        li.mOnAttachStateChangeListeners.remove(listener);
4563    }
4564
4565    /**
4566     * Returns the focus-change callback registered for this view.
4567     *
4568     * @return The callback, or null if one is not registered.
4569     */
4570    public OnFocusChangeListener getOnFocusChangeListener() {
4571        ListenerInfo li = mListenerInfo;
4572        return li != null ? li.mOnFocusChangeListener : null;
4573    }
4574
4575    /**
4576     * Register a callback to be invoked when this view is clicked. If this view is not
4577     * clickable, it becomes clickable.
4578     *
4579     * @param l The callback that will run
4580     *
4581     * @see #setClickable(boolean)
4582     */
4583    public void setOnClickListener(OnClickListener l) {
4584        if (!isClickable()) {
4585            setClickable(true);
4586        }
4587        getListenerInfo().mOnClickListener = l;
4588    }
4589
4590    /**
4591     * Return whether this view has an attached OnClickListener.  Returns
4592     * true if there is a listener, false if there is none.
4593     */
4594    public boolean hasOnClickListeners() {
4595        ListenerInfo li = mListenerInfo;
4596        return (li != null && li.mOnClickListener != null);
4597    }
4598
4599    /**
4600     * Register a callback to be invoked when this view is clicked and held. If this view is not
4601     * long clickable, it becomes long clickable.
4602     *
4603     * @param l The callback that will run
4604     *
4605     * @see #setLongClickable(boolean)
4606     */
4607    public void setOnLongClickListener(OnLongClickListener l) {
4608        if (!isLongClickable()) {
4609            setLongClickable(true);
4610        }
4611        getListenerInfo().mOnLongClickListener = l;
4612    }
4613
4614    /**
4615     * Register a callback to be invoked when the context menu for this view is
4616     * being built. If this view is not long clickable, it becomes long clickable.
4617     *
4618     * @param l The callback that will run
4619     *
4620     */
4621    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4622        if (!isLongClickable()) {
4623            setLongClickable(true);
4624        }
4625        getListenerInfo().mOnCreateContextMenuListener = l;
4626    }
4627
4628    /**
4629     * Call this view's OnClickListener, if it is defined.  Performs all normal
4630     * actions associated with clicking: reporting accessibility event, playing
4631     * a sound, etc.
4632     *
4633     * @return True there was an assigned OnClickListener that was called, false
4634     *         otherwise is returned.
4635     */
4636    public boolean performClick() {
4637        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4638
4639        ListenerInfo li = mListenerInfo;
4640        if (li != null && li.mOnClickListener != null) {
4641            playSoundEffect(SoundEffectConstants.CLICK);
4642            li.mOnClickListener.onClick(this);
4643            return true;
4644        }
4645
4646        return false;
4647    }
4648
4649    /**
4650     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4651     * this only calls the listener, and does not do any associated clicking
4652     * actions like reporting an accessibility event.
4653     *
4654     * @return True there was an assigned OnClickListener that was called, false
4655     *         otherwise is returned.
4656     */
4657    public boolean callOnClick() {
4658        ListenerInfo li = mListenerInfo;
4659        if (li != null && li.mOnClickListener != null) {
4660            li.mOnClickListener.onClick(this);
4661            return true;
4662        }
4663        return false;
4664    }
4665
4666    /**
4667     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4668     * OnLongClickListener did not consume the event.
4669     *
4670     * @return True if one of the above receivers consumed the event, false otherwise.
4671     */
4672    public boolean performLongClick() {
4673        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4674
4675        boolean handled = false;
4676        ListenerInfo li = mListenerInfo;
4677        if (li != null && li.mOnLongClickListener != null) {
4678            handled = li.mOnLongClickListener.onLongClick(View.this);
4679        }
4680        if (!handled) {
4681            handled = showContextMenu();
4682        }
4683        if (handled) {
4684            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4685        }
4686        return handled;
4687    }
4688
4689    /**
4690     * Performs button-related actions during a touch down event.
4691     *
4692     * @param event The event.
4693     * @return True if the down was consumed.
4694     *
4695     * @hide
4696     */
4697    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4698        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4699            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4700                return true;
4701            }
4702        }
4703        return false;
4704    }
4705
4706    /**
4707     * Bring up the context menu for this view.
4708     *
4709     * @return Whether a context menu was displayed.
4710     */
4711    public boolean showContextMenu() {
4712        return getParent().showContextMenuForChild(this);
4713    }
4714
4715    /**
4716     * Bring up the context menu for this view, referring to the item under the specified point.
4717     *
4718     * @param x The referenced x coordinate.
4719     * @param y The referenced y coordinate.
4720     * @param metaState The keyboard modifiers that were pressed.
4721     * @return Whether a context menu was displayed.
4722     *
4723     * @hide
4724     */
4725    public boolean showContextMenu(float x, float y, int metaState) {
4726        return showContextMenu();
4727    }
4728
4729    /**
4730     * Start an action mode.
4731     *
4732     * @param callback Callback that will control the lifecycle of the action mode
4733     * @return The new action mode if it is started, null otherwise
4734     *
4735     * @see ActionMode
4736     */
4737    public ActionMode startActionMode(ActionMode.Callback callback) {
4738        ViewParent parent = getParent();
4739        if (parent == null) return null;
4740        return parent.startActionModeForChild(this, callback);
4741    }
4742
4743    /**
4744     * Register a callback to be invoked when a hardware key is pressed in this view.
4745     * Key presses in software input methods will generally not trigger the methods of
4746     * this listener.
4747     * @param l the key listener to attach to this view
4748     */
4749    public void setOnKeyListener(OnKeyListener l) {
4750        getListenerInfo().mOnKeyListener = l;
4751    }
4752
4753    /**
4754     * Register a callback to be invoked when a touch event is sent to this view.
4755     * @param l the touch listener to attach to this view
4756     */
4757    public void setOnTouchListener(OnTouchListener l) {
4758        getListenerInfo().mOnTouchListener = l;
4759    }
4760
4761    /**
4762     * Register a callback to be invoked when a generic motion event is sent to this view.
4763     * @param l the generic motion listener to attach to this view
4764     */
4765    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4766        getListenerInfo().mOnGenericMotionListener = l;
4767    }
4768
4769    /**
4770     * Register a callback to be invoked when a hover event is sent to this view.
4771     * @param l the hover listener to attach to this view
4772     */
4773    public void setOnHoverListener(OnHoverListener l) {
4774        getListenerInfo().mOnHoverListener = l;
4775    }
4776
4777    /**
4778     * Register a drag event listener callback object for this View. The parameter is
4779     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4780     * View, the system calls the
4781     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4782     * @param l An implementation of {@link android.view.View.OnDragListener}.
4783     */
4784    public void setOnDragListener(OnDragListener l) {
4785        getListenerInfo().mOnDragListener = l;
4786    }
4787
4788    /**
4789     * Give this view focus. This will cause
4790     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4791     *
4792     * Note: this does not check whether this {@link View} should get focus, it just
4793     * gives it focus no matter what.  It should only be called internally by framework
4794     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4795     *
4796     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4797     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4798     *        focus moved when requestFocus() is called. It may not always
4799     *        apply, in which case use the default View.FOCUS_DOWN.
4800     * @param previouslyFocusedRect The rectangle of the view that had focus
4801     *        prior in this View's coordinate system.
4802     */
4803    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4804        if (DBG) {
4805            System.out.println(this + " requestFocus()");
4806        }
4807
4808        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4809            mPrivateFlags |= PFLAG_FOCUSED;
4810
4811            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4812
4813            if (mParent != null) {
4814                mParent.requestChildFocus(this, this);
4815            }
4816
4817            if (mAttachInfo != null) {
4818                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4819            }
4820
4821            manageFocusHotspot(true, oldFocus);
4822            onFocusChanged(true, direction, previouslyFocusedRect);
4823            refreshDrawableState();
4824        }
4825    }
4826
4827    /**
4828     * Forwards focus information to the background drawable, if necessary. When
4829     * the view is gaining focus, <code>v</code> is the previous focus holder.
4830     * When the view is losing focus, <code>v</code> is the next focus holder.
4831     *
4832     * @param focused whether this view is focused
4833     * @param v previous or the next focus holder, or null if none
4834     */
4835    private void manageFocusHotspot(boolean focused, View v) {
4836        if (mBackground != null && mBackground.supportsHotspots()) {
4837            final Rect r = new Rect();
4838            if (v != null) {
4839                v.getBoundsOnScreen(r);
4840                final int[] location = new int[2];
4841                getLocationOnScreen(location);
4842                r.offset(-location[0], -location[1]);
4843            } else {
4844                r.set(mLeft, mTop, mRight, mBottom);
4845            }
4846
4847            final float x = r.exactCenterX();
4848            final float y = r.exactCenterY();
4849            mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y);
4850
4851            if (!focused) {
4852                mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS);
4853            }
4854        }
4855    }
4856
4857    /**
4858     * Request that a rectangle of this view be visible on the screen,
4859     * scrolling if necessary just enough.
4860     *
4861     * <p>A View should call this if it maintains some notion of which part
4862     * of its content is interesting.  For example, a text editing view
4863     * should call this when its cursor moves.
4864     *
4865     * @param rectangle The rectangle.
4866     * @return Whether any parent scrolled.
4867     */
4868    public boolean requestRectangleOnScreen(Rect rectangle) {
4869        return requestRectangleOnScreen(rectangle, false);
4870    }
4871
4872    /**
4873     * Request that a rectangle of this view be visible on the screen,
4874     * scrolling if necessary just enough.
4875     *
4876     * <p>A View should call this if it maintains some notion of which part
4877     * of its content is interesting.  For example, a text editing view
4878     * should call this when its cursor moves.
4879     *
4880     * <p>When <code>immediate</code> is set to true, scrolling will not be
4881     * animated.
4882     *
4883     * @param rectangle The rectangle.
4884     * @param immediate True to forbid animated scrolling, false otherwise
4885     * @return Whether any parent scrolled.
4886     */
4887    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4888        if (mParent == null) {
4889            return false;
4890        }
4891
4892        View child = this;
4893
4894        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4895        position.set(rectangle);
4896
4897        ViewParent parent = mParent;
4898        boolean scrolled = false;
4899        while (parent != null) {
4900            rectangle.set((int) position.left, (int) position.top,
4901                    (int) position.right, (int) position.bottom);
4902
4903            scrolled |= parent.requestChildRectangleOnScreen(child,
4904                    rectangle, immediate);
4905
4906            if (!child.hasIdentityMatrix()) {
4907                child.getMatrix().mapRect(position);
4908            }
4909
4910            position.offset(child.mLeft, child.mTop);
4911
4912            if (!(parent instanceof View)) {
4913                break;
4914            }
4915
4916            View parentView = (View) parent;
4917
4918            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4919
4920            child = parentView;
4921            parent = child.getParent();
4922        }
4923
4924        return scrolled;
4925    }
4926
4927    /**
4928     * Called when this view wants to give up focus. If focus is cleared
4929     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4930     * <p>
4931     * <strong>Note:</strong> When a View clears focus the framework is trying
4932     * to give focus to the first focusable View from the top. Hence, if this
4933     * View is the first from the top that can take focus, then all callbacks
4934     * related to clearing focus will be invoked after wich the framework will
4935     * give focus to this view.
4936     * </p>
4937     */
4938    public void clearFocus() {
4939        if (DBG) {
4940            System.out.println(this + " clearFocus()");
4941        }
4942
4943        clearFocusInternal(null, true, true);
4944    }
4945
4946    /**
4947     * Clears focus from the view, optionally propagating the change up through
4948     * the parent hierarchy and requesting that the root view place new focus.
4949     *
4950     * @param propagate whether to propagate the change up through the parent
4951     *            hierarchy
4952     * @param refocus when propagate is true, specifies whether to request the
4953     *            root view place new focus
4954     */
4955    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4956        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4957            mPrivateFlags &= ~PFLAG_FOCUSED;
4958
4959            if (hasFocus()) {
4960                manageFocusHotspot(false, focused);
4961            }
4962
4963            if (propagate && mParent != null) {
4964                mParent.clearChildFocus(this);
4965            }
4966
4967            onFocusChanged(false, 0, null);
4968
4969            refreshDrawableState();
4970
4971            if (propagate && (!refocus || !rootViewRequestFocus())) {
4972                notifyGlobalFocusCleared(this);
4973            }
4974        }
4975    }
4976
4977    void notifyGlobalFocusCleared(View oldFocus) {
4978        if (oldFocus != null && mAttachInfo != null) {
4979            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4980        }
4981    }
4982
4983    boolean rootViewRequestFocus() {
4984        final View root = getRootView();
4985        return root != null && root.requestFocus();
4986    }
4987
4988    /**
4989     * Called internally by the view system when a new view is getting focus.
4990     * This is what clears the old focus.
4991     * <p>
4992     * <b>NOTE:</b> The parent view's focused child must be updated manually
4993     * after calling this method. Otherwise, the view hierarchy may be left in
4994     * an inconstent state.
4995     */
4996    void unFocus(View focused) {
4997        if (DBG) {
4998            System.out.println(this + " unFocus()");
4999        }
5000
5001        clearFocusInternal(focused, false, false);
5002    }
5003
5004    /**
5005     * Returns true if this view has focus iteself, or is the ancestor of the
5006     * view that has focus.
5007     *
5008     * @return True if this view has or contains focus, false otherwise.
5009     */
5010    @ViewDebug.ExportedProperty(category = "focus")
5011    public boolean hasFocus() {
5012        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5013    }
5014
5015    /**
5016     * Returns true if this view is focusable or if it contains a reachable View
5017     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5018     * is a View whose parents do not block descendants focus.
5019     *
5020     * Only {@link #VISIBLE} views are considered focusable.
5021     *
5022     * @return True if the view is focusable or if the view contains a focusable
5023     *         View, false otherwise.
5024     *
5025     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5026     */
5027    public boolean hasFocusable() {
5028        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5029    }
5030
5031    /**
5032     * Called by the view system when the focus state of this view changes.
5033     * When the focus change event is caused by directional navigation, direction
5034     * and previouslyFocusedRect provide insight into where the focus is coming from.
5035     * When overriding, be sure to call up through to the super class so that
5036     * the standard focus handling will occur.
5037     *
5038     * @param gainFocus True if the View has focus; false otherwise.
5039     * @param direction The direction focus has moved when requestFocus()
5040     *                  is called to give this view focus. Values are
5041     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5042     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5043     *                  It may not always apply, in which case use the default.
5044     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5045     *        system, of the previously focused view.  If applicable, this will be
5046     *        passed in as finer grained information about where the focus is coming
5047     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5048     */
5049    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5050            @Nullable Rect previouslyFocusedRect) {
5051        if (gainFocus) {
5052            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5053        } else {
5054            notifyViewAccessibilityStateChangedIfNeeded(
5055                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5056        }
5057
5058        InputMethodManager imm = InputMethodManager.peekInstance();
5059        if (!gainFocus) {
5060            if (isPressed()) {
5061                setPressed(false);
5062            }
5063            if (imm != null && mAttachInfo != null
5064                    && mAttachInfo.mHasWindowFocus) {
5065                imm.focusOut(this);
5066            }
5067            onFocusLost();
5068        } else if (imm != null && mAttachInfo != null
5069                && mAttachInfo.mHasWindowFocus) {
5070            imm.focusIn(this);
5071        }
5072
5073        invalidate(true);
5074        ListenerInfo li = mListenerInfo;
5075        if (li != null && li.mOnFocusChangeListener != null) {
5076            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5077        }
5078
5079        if (mAttachInfo != null) {
5080            mAttachInfo.mKeyDispatchState.reset(this);
5081        }
5082    }
5083
5084    /**
5085     * Sends an accessibility event of the given type. If accessibility is
5086     * not enabled this method has no effect. The default implementation calls
5087     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5088     * to populate information about the event source (this View), then calls
5089     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5090     * populate the text content of the event source including its descendants,
5091     * and last calls
5092     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5093     * on its parent to resuest sending of the event to interested parties.
5094     * <p>
5095     * If an {@link AccessibilityDelegate} has been specified via calling
5096     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5097     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5098     * responsible for handling this call.
5099     * </p>
5100     *
5101     * @param eventType The type of the event to send, as defined by several types from
5102     * {@link android.view.accessibility.AccessibilityEvent}, such as
5103     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5104     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5105     *
5106     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5107     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5108     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5109     * @see AccessibilityDelegate
5110     */
5111    public void sendAccessibilityEvent(int eventType) {
5112        if (mAccessibilityDelegate != null) {
5113            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5114        } else {
5115            sendAccessibilityEventInternal(eventType);
5116        }
5117    }
5118
5119    /**
5120     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5121     * {@link AccessibilityEvent} to make an announcement which is related to some
5122     * sort of a context change for which none of the events representing UI transitions
5123     * is a good fit. For example, announcing a new page in a book. If accessibility
5124     * is not enabled this method does nothing.
5125     *
5126     * @param text The announcement text.
5127     */
5128    public void announceForAccessibility(CharSequence text) {
5129        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5130            AccessibilityEvent event = AccessibilityEvent.obtain(
5131                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5132            onInitializeAccessibilityEvent(event);
5133            event.getText().add(text);
5134            event.setContentDescription(null);
5135            mParent.requestSendAccessibilityEvent(this, event);
5136        }
5137    }
5138
5139    /**
5140     * @see #sendAccessibilityEvent(int)
5141     *
5142     * Note: Called from the default {@link AccessibilityDelegate}.
5143     */
5144    void sendAccessibilityEventInternal(int eventType) {
5145        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5146            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5147        }
5148    }
5149
5150    /**
5151     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5152     * takes as an argument an empty {@link AccessibilityEvent} and does not
5153     * perform a check whether accessibility is enabled.
5154     * <p>
5155     * If an {@link AccessibilityDelegate} has been specified via calling
5156     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5157     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5158     * is responsible for handling this call.
5159     * </p>
5160     *
5161     * @param event The event to send.
5162     *
5163     * @see #sendAccessibilityEvent(int)
5164     */
5165    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5166        if (mAccessibilityDelegate != null) {
5167            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5168        } else {
5169            sendAccessibilityEventUncheckedInternal(event);
5170        }
5171    }
5172
5173    /**
5174     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5175     *
5176     * Note: Called from the default {@link AccessibilityDelegate}.
5177     */
5178    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5179        if (!isShown()) {
5180            return;
5181        }
5182        onInitializeAccessibilityEvent(event);
5183        // Only a subset of accessibility events populates text content.
5184        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5185            dispatchPopulateAccessibilityEvent(event);
5186        }
5187        // In the beginning we called #isShown(), so we know that getParent() is not null.
5188        getParent().requestSendAccessibilityEvent(this, event);
5189    }
5190
5191    /**
5192     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5193     * to its children for adding their text content to the event. Note that the
5194     * event text is populated in a separate dispatch path since we add to the
5195     * event not only the text of the source but also the text of all its descendants.
5196     * A typical implementation will call
5197     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5198     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5199     * on each child. Override this method if custom population of the event text
5200     * content is required.
5201     * <p>
5202     * If an {@link AccessibilityDelegate} has been specified via calling
5203     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5204     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5205     * is responsible for handling this call.
5206     * </p>
5207     * <p>
5208     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5209     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5210     * </p>
5211     *
5212     * @param event The event.
5213     *
5214     * @return True if the event population was completed.
5215     */
5216    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5217        if (mAccessibilityDelegate != null) {
5218            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5219        } else {
5220            return dispatchPopulateAccessibilityEventInternal(event);
5221        }
5222    }
5223
5224    /**
5225     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5226     *
5227     * Note: Called from the default {@link AccessibilityDelegate}.
5228     */
5229    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5230        onPopulateAccessibilityEvent(event);
5231        return false;
5232    }
5233
5234    /**
5235     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5236     * giving a chance to this View to populate the accessibility event with its
5237     * text content. While this method is free to modify event
5238     * attributes other than text content, doing so should normally be performed in
5239     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5240     * <p>
5241     * Example: Adding formatted date string to an accessibility event in addition
5242     *          to the text added by the super implementation:
5243     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5244     *     super.onPopulateAccessibilityEvent(event);
5245     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5246     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5247     *         mCurrentDate.getTimeInMillis(), flags);
5248     *     event.getText().add(selectedDateUtterance);
5249     * }</pre>
5250     * <p>
5251     * If an {@link AccessibilityDelegate} has been specified via calling
5252     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5253     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5254     * is responsible for handling this call.
5255     * </p>
5256     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5257     * information to the event, in case the default implementation has basic information to add.
5258     * </p>
5259     *
5260     * @param event The accessibility event which to populate.
5261     *
5262     * @see #sendAccessibilityEvent(int)
5263     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5264     */
5265    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5266        if (mAccessibilityDelegate != null) {
5267            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5268        } else {
5269            onPopulateAccessibilityEventInternal(event);
5270        }
5271    }
5272
5273    /**
5274     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5275     *
5276     * Note: Called from the default {@link AccessibilityDelegate}.
5277     */
5278    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5279    }
5280
5281    /**
5282     * Initializes an {@link AccessibilityEvent} with information about
5283     * this View which is the event source. In other words, the source of
5284     * an accessibility event is the view whose state change triggered firing
5285     * the event.
5286     * <p>
5287     * Example: Setting the password property of an event in addition
5288     *          to properties set by the super implementation:
5289     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5290     *     super.onInitializeAccessibilityEvent(event);
5291     *     event.setPassword(true);
5292     * }</pre>
5293     * <p>
5294     * If an {@link AccessibilityDelegate} has been specified via calling
5295     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5296     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5297     * is responsible for handling this call.
5298     * </p>
5299     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5300     * information to the event, in case the default implementation has basic information to add.
5301     * </p>
5302     * @param event The event to initialize.
5303     *
5304     * @see #sendAccessibilityEvent(int)
5305     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5306     */
5307    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5308        if (mAccessibilityDelegate != null) {
5309            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5310        } else {
5311            onInitializeAccessibilityEventInternal(event);
5312        }
5313    }
5314
5315    /**
5316     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5317     *
5318     * Note: Called from the default {@link AccessibilityDelegate}.
5319     */
5320    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5321        event.setSource(this);
5322        event.setClassName(View.class.getName());
5323        event.setPackageName(getContext().getPackageName());
5324        event.setEnabled(isEnabled());
5325        event.setContentDescription(mContentDescription);
5326
5327        switch (event.getEventType()) {
5328            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5329                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5330                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5331                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5332                event.setItemCount(focusablesTempList.size());
5333                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5334                if (mAttachInfo != null) {
5335                    focusablesTempList.clear();
5336                }
5337            } break;
5338            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5339                CharSequence text = getIterableTextForAccessibility();
5340                if (text != null && text.length() > 0) {
5341                    event.setFromIndex(getAccessibilitySelectionStart());
5342                    event.setToIndex(getAccessibilitySelectionEnd());
5343                    event.setItemCount(text.length());
5344                }
5345            } break;
5346        }
5347    }
5348
5349    /**
5350     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5351     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5352     * This method is responsible for obtaining an accessibility node info from a
5353     * pool of reusable instances and calling
5354     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5355     * initialize the former.
5356     * <p>
5357     * Note: The client is responsible for recycling the obtained instance by calling
5358     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5359     * </p>
5360     *
5361     * @return A populated {@link AccessibilityNodeInfo}.
5362     *
5363     * @see AccessibilityNodeInfo
5364     */
5365    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5366        if (mAccessibilityDelegate != null) {
5367            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5368        } else {
5369            return createAccessibilityNodeInfoInternal();
5370        }
5371    }
5372
5373    /**
5374     * @see #createAccessibilityNodeInfo()
5375     */
5376    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5377        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5378        if (provider != null) {
5379            return provider.createAccessibilityNodeInfo(View.NO_ID);
5380        } else {
5381            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5382            onInitializeAccessibilityNodeInfo(info);
5383            return info;
5384        }
5385    }
5386
5387    /**
5388     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5389     * The base implementation sets:
5390     * <ul>
5391     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5392     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5393     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5394     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5395     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5396     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5397     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5398     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5399     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5400     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5401     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5402     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5403     * </ul>
5404     * <p>
5405     * Subclasses should override this method, call the super implementation,
5406     * and set additional attributes.
5407     * </p>
5408     * <p>
5409     * If an {@link AccessibilityDelegate} has been specified via calling
5410     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5411     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5412     * is responsible for handling this call.
5413     * </p>
5414     *
5415     * @param info The instance to initialize.
5416     */
5417    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5418        if (mAccessibilityDelegate != null) {
5419            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5420        } else {
5421            onInitializeAccessibilityNodeInfoInternal(info);
5422        }
5423    }
5424
5425    /**
5426     * Gets the location of this view in screen coordintates.
5427     *
5428     * @param outRect The output location
5429     */
5430    void getBoundsOnScreen(Rect outRect) {
5431        if (mAttachInfo == null) {
5432            return;
5433        }
5434
5435        RectF position = mAttachInfo.mTmpTransformRect;
5436        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5437
5438        if (!hasIdentityMatrix()) {
5439            getMatrix().mapRect(position);
5440        }
5441
5442        position.offset(mLeft, mTop);
5443
5444        ViewParent parent = mParent;
5445        while (parent instanceof View) {
5446            View parentView = (View) parent;
5447
5448            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5449
5450            if (!parentView.hasIdentityMatrix()) {
5451                parentView.getMatrix().mapRect(position);
5452            }
5453
5454            position.offset(parentView.mLeft, parentView.mTop);
5455
5456            parent = parentView.mParent;
5457        }
5458
5459        if (parent instanceof ViewRootImpl) {
5460            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5461            position.offset(0, -viewRootImpl.mCurScrollY);
5462        }
5463
5464        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5465
5466        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5467                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5468    }
5469
5470    /**
5471     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5472     *
5473     * Note: Called from the default {@link AccessibilityDelegate}.
5474     */
5475    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5476        Rect bounds = mAttachInfo.mTmpInvalRect;
5477
5478        getDrawingRect(bounds);
5479        info.setBoundsInParent(bounds);
5480
5481        getBoundsOnScreen(bounds);
5482        info.setBoundsInScreen(bounds);
5483
5484        ViewParent parent = getParentForAccessibility();
5485        if (parent instanceof View) {
5486            info.setParent((View) parent);
5487        }
5488
5489        if (mID != View.NO_ID) {
5490            View rootView = getRootView();
5491            if (rootView == null) {
5492                rootView = this;
5493            }
5494            View label = rootView.findLabelForView(this, mID);
5495            if (label != null) {
5496                info.setLabeledBy(label);
5497            }
5498
5499            if ((mAttachInfo.mAccessibilityFetchFlags
5500                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5501                    && Resources.resourceHasPackage(mID)) {
5502                try {
5503                    String viewId = getResources().getResourceName(mID);
5504                    info.setViewIdResourceName(viewId);
5505                } catch (Resources.NotFoundException nfe) {
5506                    /* ignore */
5507                }
5508            }
5509        }
5510
5511        if (mLabelForId != View.NO_ID) {
5512            View rootView = getRootView();
5513            if (rootView == null) {
5514                rootView = this;
5515            }
5516            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5517            if (labeled != null) {
5518                info.setLabelFor(labeled);
5519            }
5520        }
5521
5522        info.setVisibleToUser(isVisibleToUser());
5523
5524        info.setPackageName(mContext.getPackageName());
5525        info.setClassName(View.class.getName());
5526        info.setContentDescription(getContentDescription());
5527
5528        info.setEnabled(isEnabled());
5529        info.setClickable(isClickable());
5530        info.setFocusable(isFocusable());
5531        info.setFocused(isFocused());
5532        info.setAccessibilityFocused(isAccessibilityFocused());
5533        info.setSelected(isSelected());
5534        info.setLongClickable(isLongClickable());
5535        info.setLiveRegion(getAccessibilityLiveRegion());
5536
5537        // TODO: These make sense only if we are in an AdapterView but all
5538        // views can be selected. Maybe from accessibility perspective
5539        // we should report as selectable view in an AdapterView.
5540        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5541        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5542
5543        if (isFocusable()) {
5544            if (isFocused()) {
5545                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5546            } else {
5547                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5548            }
5549        }
5550
5551        if (!isAccessibilityFocused()) {
5552            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5553        } else {
5554            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5555        }
5556
5557        if (isClickable() && isEnabled()) {
5558            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5559        }
5560
5561        if (isLongClickable() && isEnabled()) {
5562            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5563        }
5564
5565        CharSequence text = getIterableTextForAccessibility();
5566        if (text != null && text.length() > 0) {
5567            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5568
5569            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5570            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5571            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5572            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5573                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5574                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5575        }
5576    }
5577
5578    private View findLabelForView(View view, int labeledId) {
5579        if (mMatchLabelForPredicate == null) {
5580            mMatchLabelForPredicate = new MatchLabelForPredicate();
5581        }
5582        mMatchLabelForPredicate.mLabeledId = labeledId;
5583        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5584    }
5585
5586    /**
5587     * Computes whether this view is visible to the user. Such a view is
5588     * attached, visible, all its predecessors are visible, it is not clipped
5589     * entirely by its predecessors, and has an alpha greater than zero.
5590     *
5591     * @return Whether the view is visible on the screen.
5592     *
5593     * @hide
5594     */
5595    protected boolean isVisibleToUser() {
5596        return isVisibleToUser(null);
5597    }
5598
5599    /**
5600     * Computes whether the given portion of this view is visible to the user.
5601     * Such a view is attached, visible, all its predecessors are visible,
5602     * has an alpha greater than zero, and the specified portion is not
5603     * clipped entirely by its predecessors.
5604     *
5605     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5606     *                    <code>null</code>, and the entire view will be tested in this case.
5607     *                    When <code>true</code> is returned by the function, the actual visible
5608     *                    region will be stored in this parameter; that is, if boundInView is fully
5609     *                    contained within the view, no modification will be made, otherwise regions
5610     *                    outside of the visible area of the view will be clipped.
5611     *
5612     * @return Whether the specified portion of the view is visible on the screen.
5613     *
5614     * @hide
5615     */
5616    protected boolean isVisibleToUser(Rect boundInView) {
5617        if (mAttachInfo != null) {
5618            // Attached to invisible window means this view is not visible.
5619            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5620                return false;
5621            }
5622            // An invisible predecessor or one with alpha zero means
5623            // that this view is not visible to the user.
5624            Object current = this;
5625            while (current instanceof View) {
5626                View view = (View) current;
5627                // We have attach info so this view is attached and there is no
5628                // need to check whether we reach to ViewRootImpl on the way up.
5629                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5630                        view.getVisibility() != VISIBLE) {
5631                    return false;
5632                }
5633                current = view.mParent;
5634            }
5635            // Check if the view is entirely covered by its predecessors.
5636            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5637            Point offset = mAttachInfo.mPoint;
5638            if (!getGlobalVisibleRect(visibleRect, offset)) {
5639                return false;
5640            }
5641            // Check if the visible portion intersects the rectangle of interest.
5642            if (boundInView != null) {
5643                visibleRect.offset(-offset.x, -offset.y);
5644                return boundInView.intersect(visibleRect);
5645            }
5646            return true;
5647        }
5648        return false;
5649    }
5650
5651    /**
5652     * Returns the delegate for implementing accessibility support via
5653     * composition. For more details see {@link AccessibilityDelegate}.
5654     *
5655     * @return The delegate, or null if none set.
5656     *
5657     * @hide
5658     */
5659    public AccessibilityDelegate getAccessibilityDelegate() {
5660        return mAccessibilityDelegate;
5661    }
5662
5663    /**
5664     * Sets a delegate for implementing accessibility support via composition as
5665     * opposed to inheritance. The delegate's primary use is for implementing
5666     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5667     *
5668     * @param delegate The delegate instance.
5669     *
5670     * @see AccessibilityDelegate
5671     */
5672    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5673        mAccessibilityDelegate = delegate;
5674    }
5675
5676    /**
5677     * Gets the provider for managing a virtual view hierarchy rooted at this View
5678     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5679     * that explore the window content.
5680     * <p>
5681     * If this method returns an instance, this instance is responsible for managing
5682     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5683     * View including the one representing the View itself. Similarly the returned
5684     * instance is responsible for performing accessibility actions on any virtual
5685     * view or the root view itself.
5686     * </p>
5687     * <p>
5688     * If an {@link AccessibilityDelegate} has been specified via calling
5689     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5690     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5691     * is responsible for handling this call.
5692     * </p>
5693     *
5694     * @return The provider.
5695     *
5696     * @see AccessibilityNodeProvider
5697     */
5698    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5699        if (mAccessibilityDelegate != null) {
5700            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5701        } else {
5702            return null;
5703        }
5704    }
5705
5706    /**
5707     * Gets the unique identifier of this view on the screen for accessibility purposes.
5708     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5709     *
5710     * @return The view accessibility id.
5711     *
5712     * @hide
5713     */
5714    public int getAccessibilityViewId() {
5715        if (mAccessibilityViewId == NO_ID) {
5716            mAccessibilityViewId = sNextAccessibilityViewId++;
5717        }
5718        return mAccessibilityViewId;
5719    }
5720
5721    /**
5722     * Gets the unique identifier of the window in which this View reseides.
5723     *
5724     * @return The window accessibility id.
5725     *
5726     * @hide
5727     */
5728    public int getAccessibilityWindowId() {
5729        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5730    }
5731
5732    /**
5733     * Gets the {@link View} description. It briefly describes the view and is
5734     * primarily used for accessibility support. Set this property to enable
5735     * better accessibility support for your application. This is especially
5736     * true for views that do not have textual representation (For example,
5737     * ImageButton).
5738     *
5739     * @return The content description.
5740     *
5741     * @attr ref android.R.styleable#View_contentDescription
5742     */
5743    @ViewDebug.ExportedProperty(category = "accessibility")
5744    public CharSequence getContentDescription() {
5745        return mContentDescription;
5746    }
5747
5748    /**
5749     * Sets the {@link View} description. It briefly describes the view and is
5750     * primarily used for accessibility support. Set this property to enable
5751     * better accessibility support for your application. This is especially
5752     * true for views that do not have textual representation (For example,
5753     * ImageButton).
5754     *
5755     * @param contentDescription The content description.
5756     *
5757     * @attr ref android.R.styleable#View_contentDescription
5758     */
5759    @RemotableViewMethod
5760    public void setContentDescription(CharSequence contentDescription) {
5761        if (mContentDescription == null) {
5762            if (contentDescription == null) {
5763                return;
5764            }
5765        } else if (mContentDescription.equals(contentDescription)) {
5766            return;
5767        }
5768        mContentDescription = contentDescription;
5769        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5770        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5771            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5772            notifySubtreeAccessibilityStateChangedIfNeeded();
5773        } else {
5774            notifyViewAccessibilityStateChangedIfNeeded(
5775                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5776        }
5777    }
5778
5779    /**
5780     * Gets the id of a view for which this view serves as a label for
5781     * accessibility purposes.
5782     *
5783     * @return The labeled view id.
5784     */
5785    @ViewDebug.ExportedProperty(category = "accessibility")
5786    public int getLabelFor() {
5787        return mLabelForId;
5788    }
5789
5790    /**
5791     * Sets the id of a view for which this view serves as a label for
5792     * accessibility purposes.
5793     *
5794     * @param id The labeled view id.
5795     */
5796    @RemotableViewMethod
5797    public void setLabelFor(int id) {
5798        mLabelForId = id;
5799        if (mLabelForId != View.NO_ID
5800                && mID == View.NO_ID) {
5801            mID = generateViewId();
5802        }
5803    }
5804
5805    /**
5806     * Invoked whenever this view loses focus, either by losing window focus or by losing
5807     * focus within its window. This method can be used to clear any state tied to the
5808     * focus. For instance, if a button is held pressed with the trackball and the window
5809     * loses focus, this method can be used to cancel the press.
5810     *
5811     * Subclasses of View overriding this method should always call super.onFocusLost().
5812     *
5813     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5814     * @see #onWindowFocusChanged(boolean)
5815     *
5816     * @hide pending API council approval
5817     */
5818    protected void onFocusLost() {
5819        resetPressedState();
5820    }
5821
5822    private void resetPressedState() {
5823        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5824            return;
5825        }
5826
5827        if (isPressed()) {
5828            setPressed(false);
5829
5830            if (!mHasPerformedLongPress) {
5831                removeLongPressCallback();
5832            }
5833        }
5834    }
5835
5836    /**
5837     * Returns true if this view has focus
5838     *
5839     * @return True if this view has focus, false otherwise.
5840     */
5841    @ViewDebug.ExportedProperty(category = "focus")
5842    public boolean isFocused() {
5843        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5844    }
5845
5846    /**
5847     * Find the view in the hierarchy rooted at this view that currently has
5848     * focus.
5849     *
5850     * @return The view that currently has focus, or null if no focused view can
5851     *         be found.
5852     */
5853    public View findFocus() {
5854        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5855    }
5856
5857    /**
5858     * Indicates whether this view is one of the set of scrollable containers in
5859     * its window.
5860     *
5861     * @return whether this view is one of the set of scrollable containers in
5862     * its window
5863     *
5864     * @attr ref android.R.styleable#View_isScrollContainer
5865     */
5866    public boolean isScrollContainer() {
5867        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5868    }
5869
5870    /**
5871     * Change whether this view is one of the set of scrollable containers in
5872     * its window.  This will be used to determine whether the window can
5873     * resize or must pan when a soft input area is open -- scrollable
5874     * containers allow the window to use resize mode since the container
5875     * will appropriately shrink.
5876     *
5877     * @attr ref android.R.styleable#View_isScrollContainer
5878     */
5879    public void setScrollContainer(boolean isScrollContainer) {
5880        if (isScrollContainer) {
5881            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5882                mAttachInfo.mScrollContainers.add(this);
5883                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5884            }
5885            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5886        } else {
5887            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5888                mAttachInfo.mScrollContainers.remove(this);
5889            }
5890            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5891        }
5892    }
5893
5894    /**
5895     * Returns the quality of the drawing cache.
5896     *
5897     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5898     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5899     *
5900     * @see #setDrawingCacheQuality(int)
5901     * @see #setDrawingCacheEnabled(boolean)
5902     * @see #isDrawingCacheEnabled()
5903     *
5904     * @attr ref android.R.styleable#View_drawingCacheQuality
5905     */
5906    @DrawingCacheQuality
5907    public int getDrawingCacheQuality() {
5908        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5909    }
5910
5911    /**
5912     * Set the drawing cache quality of this view. This value is used only when the
5913     * drawing cache is enabled
5914     *
5915     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5916     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5917     *
5918     * @see #getDrawingCacheQuality()
5919     * @see #setDrawingCacheEnabled(boolean)
5920     * @see #isDrawingCacheEnabled()
5921     *
5922     * @attr ref android.R.styleable#View_drawingCacheQuality
5923     */
5924    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5925        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5926    }
5927
5928    /**
5929     * Returns whether the screen should remain on, corresponding to the current
5930     * value of {@link #KEEP_SCREEN_ON}.
5931     *
5932     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5933     *
5934     * @see #setKeepScreenOn(boolean)
5935     *
5936     * @attr ref android.R.styleable#View_keepScreenOn
5937     */
5938    public boolean getKeepScreenOn() {
5939        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5940    }
5941
5942    /**
5943     * Controls whether the screen should remain on, modifying the
5944     * value of {@link #KEEP_SCREEN_ON}.
5945     *
5946     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5947     *
5948     * @see #getKeepScreenOn()
5949     *
5950     * @attr ref android.R.styleable#View_keepScreenOn
5951     */
5952    public void setKeepScreenOn(boolean keepScreenOn) {
5953        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5954    }
5955
5956    /**
5957     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5958     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5959     *
5960     * @attr ref android.R.styleable#View_nextFocusLeft
5961     */
5962    public int getNextFocusLeftId() {
5963        return mNextFocusLeftId;
5964    }
5965
5966    /**
5967     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5968     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5969     * decide automatically.
5970     *
5971     * @attr ref android.R.styleable#View_nextFocusLeft
5972     */
5973    public void setNextFocusLeftId(int nextFocusLeftId) {
5974        mNextFocusLeftId = nextFocusLeftId;
5975    }
5976
5977    /**
5978     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5979     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5980     *
5981     * @attr ref android.R.styleable#View_nextFocusRight
5982     */
5983    public int getNextFocusRightId() {
5984        return mNextFocusRightId;
5985    }
5986
5987    /**
5988     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5989     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5990     * decide automatically.
5991     *
5992     * @attr ref android.R.styleable#View_nextFocusRight
5993     */
5994    public void setNextFocusRightId(int nextFocusRightId) {
5995        mNextFocusRightId = nextFocusRightId;
5996    }
5997
5998    /**
5999     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6000     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6001     *
6002     * @attr ref android.R.styleable#View_nextFocusUp
6003     */
6004    public int getNextFocusUpId() {
6005        return mNextFocusUpId;
6006    }
6007
6008    /**
6009     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6010     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6011     * decide automatically.
6012     *
6013     * @attr ref android.R.styleable#View_nextFocusUp
6014     */
6015    public void setNextFocusUpId(int nextFocusUpId) {
6016        mNextFocusUpId = nextFocusUpId;
6017    }
6018
6019    /**
6020     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6021     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6022     *
6023     * @attr ref android.R.styleable#View_nextFocusDown
6024     */
6025    public int getNextFocusDownId() {
6026        return mNextFocusDownId;
6027    }
6028
6029    /**
6030     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6031     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6032     * decide automatically.
6033     *
6034     * @attr ref android.R.styleable#View_nextFocusDown
6035     */
6036    public void setNextFocusDownId(int nextFocusDownId) {
6037        mNextFocusDownId = nextFocusDownId;
6038    }
6039
6040    /**
6041     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6042     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6043     *
6044     * @attr ref android.R.styleable#View_nextFocusForward
6045     */
6046    public int getNextFocusForwardId() {
6047        return mNextFocusForwardId;
6048    }
6049
6050    /**
6051     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6052     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6053     * decide automatically.
6054     *
6055     * @attr ref android.R.styleable#View_nextFocusForward
6056     */
6057    public void setNextFocusForwardId(int nextFocusForwardId) {
6058        mNextFocusForwardId = nextFocusForwardId;
6059    }
6060
6061    /**
6062     * Returns the visibility of this view and all of its ancestors
6063     *
6064     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6065     */
6066    public boolean isShown() {
6067        View current = this;
6068        //noinspection ConstantConditions
6069        do {
6070            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6071                return false;
6072            }
6073            ViewParent parent = current.mParent;
6074            if (parent == null) {
6075                return false; // We are not attached to the view root
6076            }
6077            if (!(parent instanceof View)) {
6078                return true;
6079            }
6080            current = (View) parent;
6081        } while (current != null);
6082
6083        return false;
6084    }
6085
6086    /**
6087     * Called by the view hierarchy when the content insets for a window have
6088     * changed, to allow it to adjust its content to fit within those windows.
6089     * The content insets tell you the space that the status bar, input method,
6090     * and other system windows infringe on the application's window.
6091     *
6092     * <p>You do not normally need to deal with this function, since the default
6093     * window decoration given to applications takes care of applying it to the
6094     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6095     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6096     * and your content can be placed under those system elements.  You can then
6097     * use this method within your view hierarchy if you have parts of your UI
6098     * which you would like to ensure are not being covered.
6099     *
6100     * <p>The default implementation of this method simply applies the content
6101     * insets to the view's padding, consuming that content (modifying the
6102     * insets to be 0), and returning true.  This behavior is off by default, but can
6103     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6104     *
6105     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6106     * insets object is propagated down the hierarchy, so any changes made to it will
6107     * be seen by all following views (including potentially ones above in
6108     * the hierarchy since this is a depth-first traversal).  The first view
6109     * that returns true will abort the entire traversal.
6110     *
6111     * <p>The default implementation works well for a situation where it is
6112     * used with a container that covers the entire window, allowing it to
6113     * apply the appropriate insets to its content on all edges.  If you need
6114     * a more complicated layout (such as two different views fitting system
6115     * windows, one on the top of the window, and one on the bottom),
6116     * you can override the method and handle the insets however you would like.
6117     * Note that the insets provided by the framework are always relative to the
6118     * far edges of the window, not accounting for the location of the called view
6119     * within that window.  (In fact when this method is called you do not yet know
6120     * where the layout will place the view, as it is done before layout happens.)
6121     *
6122     * <p>Note: unlike many View methods, there is no dispatch phase to this
6123     * call.  If you are overriding it in a ViewGroup and want to allow the
6124     * call to continue to your children, you must be sure to call the super
6125     * implementation.
6126     *
6127     * <p>Here is a sample layout that makes use of fitting system windows
6128     * to have controls for a video view placed inside of the window decorations
6129     * that it hides and shows.  This can be used with code like the second
6130     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6131     *
6132     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6133     *
6134     * @param insets Current content insets of the window.  Prior to
6135     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6136     * the insets or else you and Android will be unhappy.
6137     *
6138     * @return {@code true} if this view applied the insets and it should not
6139     * continue propagating further down the hierarchy, {@code false} otherwise.
6140     * @see #getFitsSystemWindows()
6141     * @see #setFitsSystemWindows(boolean)
6142     * @see #setSystemUiVisibility(int)
6143     *
6144     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6145     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6146     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6147     * to implement handling their own insets.
6148     */
6149    protected boolean fitSystemWindows(Rect insets) {
6150        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6151            // If we're not in the process of dispatching the newer apply insets call,
6152            // that means we're not in the compatibility path. Dispatch into the newer
6153            // apply insets path and take things from there.
6154            try {
6155                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6156                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6157            } finally {
6158                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6159            }
6160        } else {
6161            // We're being called from the newer apply insets path.
6162            // Perform the standard fallback behavior.
6163            return fitSystemWindowsInt(insets);
6164        }
6165    }
6166
6167    private boolean fitSystemWindowsInt(Rect insets) {
6168        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6169            mUserPaddingStart = UNDEFINED_PADDING;
6170            mUserPaddingEnd = UNDEFINED_PADDING;
6171            Rect localInsets = sThreadLocal.get();
6172            if (localInsets == null) {
6173                localInsets = new Rect();
6174                sThreadLocal.set(localInsets);
6175            }
6176            boolean res = computeFitSystemWindows(insets, localInsets);
6177            mUserPaddingLeftInitial = localInsets.left;
6178            mUserPaddingRightInitial = localInsets.right;
6179            internalSetPadding(localInsets.left, localInsets.top,
6180                    localInsets.right, localInsets.bottom);
6181            return res;
6182        }
6183        return false;
6184    }
6185
6186    /**
6187     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6188     *
6189     * <p>This method should be overridden by views that wish to apply a policy different from or
6190     * in addition to the default behavior. Clients that wish to force a view subtree
6191     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6192     *
6193     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6194     * it will be called during dispatch instead of this method. The listener may optionally
6195     * call this method from its own implementation if it wishes to apply the view's default
6196     * insets policy in addition to its own.</p>
6197     *
6198     * <p>Implementations of this method should either return the insets parameter unchanged
6199     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6200     * that this view applied itself. This allows new inset types added in future platform
6201     * versions to pass through existing implementations unchanged without being erroneously
6202     * consumed.</p>
6203     *
6204     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6205     * property is set then the view will consume the system window insets and apply them
6206     * as padding for the view.</p>
6207     *
6208     * @param insets Insets to apply
6209     * @return The supplied insets with any applied insets consumed
6210     */
6211    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6212        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6213            // We weren't called from within a direct call to fitSystemWindows,
6214            // call into it as a fallback in case we're in a class that overrides it
6215            // and has logic to perform.
6216            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6217                return insets.cloneWithSystemWindowInsetsConsumed();
6218            }
6219        } else {
6220            // We were called from within a direct call to fitSystemWindows.
6221            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6222                return insets.cloneWithSystemWindowInsetsConsumed();
6223            }
6224        }
6225        return insets;
6226    }
6227
6228    /**
6229     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6230     * window insets to this view. The listener's
6231     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6232     * method will be called instead of the view's
6233     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6234     *
6235     * @param listener Listener to set
6236     *
6237     * @see #onApplyWindowInsets(WindowInsets)
6238     */
6239    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6240        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6241    }
6242
6243    /**
6244     * Request to apply the given window insets to this view or another view in its subtree.
6245     *
6246     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6247     * obscured by window decorations or overlays. This can include the status and navigation bars,
6248     * action bars, input methods and more. New inset categories may be added in the future.
6249     * The method returns the insets provided minus any that were applied by this view or its
6250     * children.</p>
6251     *
6252     * <p>Clients wishing to provide custom behavior should override the
6253     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6254     * {@link OnApplyWindowInsetsListener} via the
6255     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6256     * method.</p>
6257     *
6258     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6259     * </p>
6260     *
6261     * @param insets Insets to apply
6262     * @return The provided insets minus the insets that were consumed
6263     */
6264    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6265        try {
6266            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6267            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6268                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6269            } else {
6270                return onApplyWindowInsets(insets);
6271            }
6272        } finally {
6273            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6274        }
6275    }
6276
6277    /**
6278     * @hide Compute the insets that should be consumed by this view and the ones
6279     * that should propagate to those under it.
6280     */
6281    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6282        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6283                || mAttachInfo == null
6284                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6285                        && !mAttachInfo.mOverscanRequested)) {
6286            outLocalInsets.set(inoutInsets);
6287            inoutInsets.set(0, 0, 0, 0);
6288            return true;
6289        } else {
6290            // The application wants to take care of fitting system window for
6291            // the content...  however we still need to take care of any overscan here.
6292            final Rect overscan = mAttachInfo.mOverscanInsets;
6293            outLocalInsets.set(overscan);
6294            inoutInsets.left -= overscan.left;
6295            inoutInsets.top -= overscan.top;
6296            inoutInsets.right -= overscan.right;
6297            inoutInsets.bottom -= overscan.bottom;
6298            return false;
6299        }
6300    }
6301
6302    /**
6303     * Sets whether or not this view should account for system screen decorations
6304     * such as the status bar and inset its content; that is, controlling whether
6305     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6306     * executed.  See that method for more details.
6307     *
6308     * <p>Note that if you are providing your own implementation of
6309     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6310     * flag to true -- your implementation will be overriding the default
6311     * implementation that checks this flag.
6312     *
6313     * @param fitSystemWindows If true, then the default implementation of
6314     * {@link #fitSystemWindows(Rect)} will be executed.
6315     *
6316     * @attr ref android.R.styleable#View_fitsSystemWindows
6317     * @see #getFitsSystemWindows()
6318     * @see #fitSystemWindows(Rect)
6319     * @see #setSystemUiVisibility(int)
6320     */
6321    public void setFitsSystemWindows(boolean fitSystemWindows) {
6322        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6323    }
6324
6325    /**
6326     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6327     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6328     * will be executed.
6329     *
6330     * @return {@code true} if the default implementation of
6331     * {@link #fitSystemWindows(Rect)} will be executed.
6332     *
6333     * @attr ref android.R.styleable#View_fitsSystemWindows
6334     * @see #setFitsSystemWindows(boolean)
6335     * @see #fitSystemWindows(Rect)
6336     * @see #setSystemUiVisibility(int)
6337     */
6338    public boolean getFitsSystemWindows() {
6339        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6340    }
6341
6342    /** @hide */
6343    public boolean fitsSystemWindows() {
6344        return getFitsSystemWindows();
6345    }
6346
6347    /**
6348     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6349     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6350     */
6351    public void requestFitSystemWindows() {
6352        if (mParent != null) {
6353            mParent.requestFitSystemWindows();
6354        }
6355    }
6356
6357    /**
6358     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6359     */
6360    public void requestApplyInsets() {
6361        requestFitSystemWindows();
6362    }
6363
6364    /**
6365     * For use by PhoneWindow to make its own system window fitting optional.
6366     * @hide
6367     */
6368    public void makeOptionalFitsSystemWindows() {
6369        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6370    }
6371
6372    /**
6373     * Returns the visibility status for this view.
6374     *
6375     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6376     * @attr ref android.R.styleable#View_visibility
6377     */
6378    @ViewDebug.ExportedProperty(mapping = {
6379        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6380        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6381        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6382    })
6383    @Visibility
6384    public int getVisibility() {
6385        return mViewFlags & VISIBILITY_MASK;
6386    }
6387
6388    /**
6389     * Set the enabled state of this view.
6390     *
6391     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6392     * @attr ref android.R.styleable#View_visibility
6393     */
6394    @RemotableViewMethod
6395    public void setVisibility(@Visibility int visibility) {
6396        setFlags(visibility, VISIBILITY_MASK);
6397        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6398    }
6399
6400    /**
6401     * Returns the enabled status for this view. The interpretation of the
6402     * enabled state varies by subclass.
6403     *
6404     * @return True if this view is enabled, false otherwise.
6405     */
6406    @ViewDebug.ExportedProperty
6407    public boolean isEnabled() {
6408        return (mViewFlags & ENABLED_MASK) == ENABLED;
6409    }
6410
6411    /**
6412     * Set the enabled state of this view. The interpretation of the enabled
6413     * state varies by subclass.
6414     *
6415     * @param enabled True if this view is enabled, false otherwise.
6416     */
6417    @RemotableViewMethod
6418    public void setEnabled(boolean enabled) {
6419        if (enabled == isEnabled()) return;
6420
6421        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6422
6423        /*
6424         * The View most likely has to change its appearance, so refresh
6425         * the drawable state.
6426         */
6427        refreshDrawableState();
6428
6429        // Invalidate too, since the default behavior for views is to be
6430        // be drawn at 50% alpha rather than to change the drawable.
6431        invalidate(true);
6432
6433        if (!enabled) {
6434            cancelPendingInputEvents();
6435        }
6436    }
6437
6438    /**
6439     * Set whether this view can receive the focus.
6440     *
6441     * Setting this to false will also ensure that this view is not focusable
6442     * in touch mode.
6443     *
6444     * @param focusable If true, this view can receive the focus.
6445     *
6446     * @see #setFocusableInTouchMode(boolean)
6447     * @attr ref android.R.styleable#View_focusable
6448     */
6449    public void setFocusable(boolean focusable) {
6450        if (!focusable) {
6451            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6452        }
6453        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6454    }
6455
6456    /**
6457     * Set whether this view can receive focus while in touch mode.
6458     *
6459     * Setting this to true will also ensure that this view is focusable.
6460     *
6461     * @param focusableInTouchMode If true, this view can receive the focus while
6462     *   in touch mode.
6463     *
6464     * @see #setFocusable(boolean)
6465     * @attr ref android.R.styleable#View_focusableInTouchMode
6466     */
6467    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6468        // Focusable in touch mode should always be set before the focusable flag
6469        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6470        // which, in touch mode, will not successfully request focus on this view
6471        // because the focusable in touch mode flag is not set
6472        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6473        if (focusableInTouchMode) {
6474            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6475        }
6476    }
6477
6478    /**
6479     * Set whether this view should have sound effects enabled for events such as
6480     * clicking and touching.
6481     *
6482     * <p>You may wish to disable sound effects for a view if you already play sounds,
6483     * for instance, a dial key that plays dtmf tones.
6484     *
6485     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6486     * @see #isSoundEffectsEnabled()
6487     * @see #playSoundEffect(int)
6488     * @attr ref android.R.styleable#View_soundEffectsEnabled
6489     */
6490    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6491        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6492    }
6493
6494    /**
6495     * @return whether this view should have sound effects enabled for events such as
6496     *     clicking and touching.
6497     *
6498     * @see #setSoundEffectsEnabled(boolean)
6499     * @see #playSoundEffect(int)
6500     * @attr ref android.R.styleable#View_soundEffectsEnabled
6501     */
6502    @ViewDebug.ExportedProperty
6503    public boolean isSoundEffectsEnabled() {
6504        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6505    }
6506
6507    /**
6508     * Set whether this view should have haptic feedback for events such as
6509     * long presses.
6510     *
6511     * <p>You may wish to disable haptic feedback if your view already controls
6512     * its own haptic feedback.
6513     *
6514     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6515     * @see #isHapticFeedbackEnabled()
6516     * @see #performHapticFeedback(int)
6517     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6518     */
6519    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6520        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6521    }
6522
6523    /**
6524     * @return whether this view should have haptic feedback enabled for events
6525     * long presses.
6526     *
6527     * @see #setHapticFeedbackEnabled(boolean)
6528     * @see #performHapticFeedback(int)
6529     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6530     */
6531    @ViewDebug.ExportedProperty
6532    public boolean isHapticFeedbackEnabled() {
6533        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6534    }
6535
6536    /**
6537     * Returns the layout direction for this view.
6538     *
6539     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6540     *   {@link #LAYOUT_DIRECTION_RTL},
6541     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6542     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6543     *
6544     * @attr ref android.R.styleable#View_layoutDirection
6545     *
6546     * @hide
6547     */
6548    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6549        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6550        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6551        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6552        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6553    })
6554    @LayoutDir
6555    public int getRawLayoutDirection() {
6556        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6557    }
6558
6559    /**
6560     * Set the layout direction for this view. This will propagate a reset of layout direction
6561     * resolution to the view's children and resolve layout direction for this view.
6562     *
6563     * @param layoutDirection the layout direction to set. Should be one of:
6564     *
6565     * {@link #LAYOUT_DIRECTION_LTR},
6566     * {@link #LAYOUT_DIRECTION_RTL},
6567     * {@link #LAYOUT_DIRECTION_INHERIT},
6568     * {@link #LAYOUT_DIRECTION_LOCALE}.
6569     *
6570     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6571     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6572     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6573     *
6574     * @attr ref android.R.styleable#View_layoutDirection
6575     */
6576    @RemotableViewMethod
6577    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6578        if (getRawLayoutDirection() != layoutDirection) {
6579            // Reset the current layout direction and the resolved one
6580            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6581            resetRtlProperties();
6582            // Set the new layout direction (filtered)
6583            mPrivateFlags2 |=
6584                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6585            // We need to resolve all RTL properties as they all depend on layout direction
6586            resolveRtlPropertiesIfNeeded();
6587            requestLayout();
6588            invalidate(true);
6589        }
6590    }
6591
6592    /**
6593     * Returns the resolved layout direction for this view.
6594     *
6595     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6596     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6597     *
6598     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6599     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6600     *
6601     * @attr ref android.R.styleable#View_layoutDirection
6602     */
6603    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6604        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6605        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6606    })
6607    @ResolvedLayoutDir
6608    public int getLayoutDirection() {
6609        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6610        if (targetSdkVersion < JELLY_BEAN_MR1) {
6611            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6612            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6613        }
6614        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6615                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6616    }
6617
6618    /**
6619     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6620     * layout attribute and/or the inherited value from the parent
6621     *
6622     * @return true if the layout is right-to-left.
6623     *
6624     * @hide
6625     */
6626    @ViewDebug.ExportedProperty(category = "layout")
6627    public boolean isLayoutRtl() {
6628        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6629    }
6630
6631    /**
6632     * Indicates whether the view is currently tracking transient state that the
6633     * app should not need to concern itself with saving and restoring, but that
6634     * the framework should take special note to preserve when possible.
6635     *
6636     * <p>A view with transient state cannot be trivially rebound from an external
6637     * data source, such as an adapter binding item views in a list. This may be
6638     * because the view is performing an animation, tracking user selection
6639     * of content, or similar.</p>
6640     *
6641     * @return true if the view has transient state
6642     */
6643    @ViewDebug.ExportedProperty(category = "layout")
6644    public boolean hasTransientState() {
6645        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6646    }
6647
6648    /**
6649     * Set whether this view is currently tracking transient state that the
6650     * framework should attempt to preserve when possible. This flag is reference counted,
6651     * so every call to setHasTransientState(true) should be paired with a later call
6652     * to setHasTransientState(false).
6653     *
6654     * <p>A view with transient state cannot be trivially rebound from an external
6655     * data source, such as an adapter binding item views in a list. This may be
6656     * because the view is performing an animation, tracking user selection
6657     * of content, or similar.</p>
6658     *
6659     * @param hasTransientState true if this view has transient state
6660     */
6661    public void setHasTransientState(boolean hasTransientState) {
6662        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6663                mTransientStateCount - 1;
6664        if (mTransientStateCount < 0) {
6665            mTransientStateCount = 0;
6666            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6667                    "unmatched pair of setHasTransientState calls");
6668        } else if ((hasTransientState && mTransientStateCount == 1) ||
6669                (!hasTransientState && mTransientStateCount == 0)) {
6670            // update flag if we've just incremented up from 0 or decremented down to 0
6671            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6672                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6673            if (mParent != null) {
6674                try {
6675                    mParent.childHasTransientStateChanged(this, hasTransientState);
6676                } catch (AbstractMethodError e) {
6677                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6678                            " does not fully implement ViewParent", e);
6679                }
6680            }
6681        }
6682    }
6683
6684    /**
6685     * Returns true if this view is currently attached to a window.
6686     */
6687    public boolean isAttachedToWindow() {
6688        return mAttachInfo != null;
6689    }
6690
6691    /**
6692     * Returns true if this view has been through at least one layout since it
6693     * was last attached to or detached from a window.
6694     */
6695    public boolean isLaidOut() {
6696        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6697    }
6698
6699    /**
6700     * If this view doesn't do any drawing on its own, set this flag to
6701     * allow further optimizations. By default, this flag is not set on
6702     * View, but could be set on some View subclasses such as ViewGroup.
6703     *
6704     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6705     * you should clear this flag.
6706     *
6707     * @param willNotDraw whether or not this View draw on its own
6708     */
6709    public void setWillNotDraw(boolean willNotDraw) {
6710        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6711    }
6712
6713    /**
6714     * Returns whether or not this View draws on its own.
6715     *
6716     * @return true if this view has nothing to draw, false otherwise
6717     */
6718    @ViewDebug.ExportedProperty(category = "drawing")
6719    public boolean willNotDraw() {
6720        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6721    }
6722
6723    /**
6724     * When a View's drawing cache is enabled, drawing is redirected to an
6725     * offscreen bitmap. Some views, like an ImageView, must be able to
6726     * bypass this mechanism if they already draw a single bitmap, to avoid
6727     * unnecessary usage of the memory.
6728     *
6729     * @param willNotCacheDrawing true if this view does not cache its
6730     *        drawing, false otherwise
6731     */
6732    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6733        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6734    }
6735
6736    /**
6737     * Returns whether or not this View can cache its drawing or not.
6738     *
6739     * @return true if this view does not cache its drawing, false otherwise
6740     */
6741    @ViewDebug.ExportedProperty(category = "drawing")
6742    public boolean willNotCacheDrawing() {
6743        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6744    }
6745
6746    /**
6747     * Indicates whether this view reacts to click events or not.
6748     *
6749     * @return true if the view is clickable, false otherwise
6750     *
6751     * @see #setClickable(boolean)
6752     * @attr ref android.R.styleable#View_clickable
6753     */
6754    @ViewDebug.ExportedProperty
6755    public boolean isClickable() {
6756        return (mViewFlags & CLICKABLE) == CLICKABLE;
6757    }
6758
6759    /**
6760     * Enables or disables click events for this view. When a view
6761     * is clickable it will change its state to "pressed" on every click.
6762     * Subclasses should set the view clickable to visually react to
6763     * user's clicks.
6764     *
6765     * @param clickable true to make the view clickable, false otherwise
6766     *
6767     * @see #isClickable()
6768     * @attr ref android.R.styleable#View_clickable
6769     */
6770    public void setClickable(boolean clickable) {
6771        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6772    }
6773
6774    /**
6775     * Indicates whether this view reacts to long click events or not.
6776     *
6777     * @return true if the view is long clickable, false otherwise
6778     *
6779     * @see #setLongClickable(boolean)
6780     * @attr ref android.R.styleable#View_longClickable
6781     */
6782    public boolean isLongClickable() {
6783        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6784    }
6785
6786    /**
6787     * Enables or disables long click events for this view. When a view is long
6788     * clickable it reacts to the user holding down the button for a longer
6789     * duration than a tap. This event can either launch the listener or a
6790     * context menu.
6791     *
6792     * @param longClickable true to make the view long clickable, false otherwise
6793     * @see #isLongClickable()
6794     * @attr ref android.R.styleable#View_longClickable
6795     */
6796    public void setLongClickable(boolean longClickable) {
6797        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6798    }
6799
6800    /**
6801     * Sets the pressed state for this view.
6802     *
6803     * @see #isClickable()
6804     * @see #setClickable(boolean)
6805     *
6806     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6807     *        the View's internal state from a previously set "pressed" state.
6808     */
6809    public void setPressed(boolean pressed) {
6810        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6811
6812        if (pressed) {
6813            mPrivateFlags |= PFLAG_PRESSED;
6814        } else {
6815            mPrivateFlags &= ~PFLAG_PRESSED;
6816        }
6817
6818        if (needsRefresh) {
6819            refreshDrawableState();
6820        }
6821        dispatchSetPressed(pressed);
6822    }
6823
6824    /**
6825     * Dispatch setPressed to all of this View's children.
6826     *
6827     * @see #setPressed(boolean)
6828     *
6829     * @param pressed The new pressed state
6830     */
6831    protected void dispatchSetPressed(boolean pressed) {
6832    }
6833
6834    /**
6835     * Indicates whether the view is currently in pressed state. Unless
6836     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6837     * the pressed state.
6838     *
6839     * @see #setPressed(boolean)
6840     * @see #isClickable()
6841     * @see #setClickable(boolean)
6842     *
6843     * @return true if the view is currently pressed, false otherwise
6844     */
6845    public boolean isPressed() {
6846        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6847    }
6848
6849    /**
6850     * Indicates whether this view will save its state (that is,
6851     * whether its {@link #onSaveInstanceState} method will be called).
6852     *
6853     * @return Returns true if the view state saving is enabled, else false.
6854     *
6855     * @see #setSaveEnabled(boolean)
6856     * @attr ref android.R.styleable#View_saveEnabled
6857     */
6858    public boolean isSaveEnabled() {
6859        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6860    }
6861
6862    /**
6863     * Controls whether the saving of this view's state is
6864     * enabled (that is, whether its {@link #onSaveInstanceState} method
6865     * will be called).  Note that even if freezing is enabled, the
6866     * view still must have an id assigned to it (via {@link #setId(int)})
6867     * for its state to be saved.  This flag can only disable the
6868     * saving of this view; any child views may still have their state saved.
6869     *
6870     * @param enabled Set to false to <em>disable</em> state saving, or true
6871     * (the default) to allow it.
6872     *
6873     * @see #isSaveEnabled()
6874     * @see #setId(int)
6875     * @see #onSaveInstanceState()
6876     * @attr ref android.R.styleable#View_saveEnabled
6877     */
6878    public void setSaveEnabled(boolean enabled) {
6879        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6880    }
6881
6882    /**
6883     * Gets whether the framework should discard touches when the view's
6884     * window is obscured by another visible window.
6885     * Refer to the {@link View} security documentation for more details.
6886     *
6887     * @return True if touch filtering is enabled.
6888     *
6889     * @see #setFilterTouchesWhenObscured(boolean)
6890     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6891     */
6892    @ViewDebug.ExportedProperty
6893    public boolean getFilterTouchesWhenObscured() {
6894        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6895    }
6896
6897    /**
6898     * Sets whether the framework should discard touches when the view's
6899     * window is obscured by another visible window.
6900     * Refer to the {@link View} security documentation for more details.
6901     *
6902     * @param enabled True if touch filtering should be enabled.
6903     *
6904     * @see #getFilterTouchesWhenObscured
6905     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6906     */
6907    public void setFilterTouchesWhenObscured(boolean enabled) {
6908        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6909                FILTER_TOUCHES_WHEN_OBSCURED);
6910    }
6911
6912    /**
6913     * Indicates whether the entire hierarchy under this view will save its
6914     * state when a state saving traversal occurs from its parent.  The default
6915     * is true; if false, these views will not be saved unless
6916     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6917     *
6918     * @return Returns true if the view state saving from parent is enabled, else false.
6919     *
6920     * @see #setSaveFromParentEnabled(boolean)
6921     */
6922    public boolean isSaveFromParentEnabled() {
6923        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6924    }
6925
6926    /**
6927     * Controls whether the entire hierarchy under this view will save its
6928     * state when a state saving traversal occurs from its parent.  The default
6929     * is true; if false, these views will not be saved unless
6930     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6931     *
6932     * @param enabled Set to false to <em>disable</em> state saving, or true
6933     * (the default) to allow it.
6934     *
6935     * @see #isSaveFromParentEnabled()
6936     * @see #setId(int)
6937     * @see #onSaveInstanceState()
6938     */
6939    public void setSaveFromParentEnabled(boolean enabled) {
6940        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6941    }
6942
6943
6944    /**
6945     * Returns whether this View is able to take focus.
6946     *
6947     * @return True if this view can take focus, or false otherwise.
6948     * @attr ref android.R.styleable#View_focusable
6949     */
6950    @ViewDebug.ExportedProperty(category = "focus")
6951    public final boolean isFocusable() {
6952        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6953    }
6954
6955    /**
6956     * When a view is focusable, it may not want to take focus when in touch mode.
6957     * For example, a button would like focus when the user is navigating via a D-pad
6958     * so that the user can click on it, but once the user starts touching the screen,
6959     * the button shouldn't take focus
6960     * @return Whether the view is focusable in touch mode.
6961     * @attr ref android.R.styleable#View_focusableInTouchMode
6962     */
6963    @ViewDebug.ExportedProperty
6964    public final boolean isFocusableInTouchMode() {
6965        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6966    }
6967
6968    /**
6969     * Find the nearest view in the specified direction that can take focus.
6970     * This does not actually give focus to that view.
6971     *
6972     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6973     *
6974     * @return The nearest focusable in the specified direction, or null if none
6975     *         can be found.
6976     */
6977    public View focusSearch(@FocusRealDirection int direction) {
6978        if (mParent != null) {
6979            return mParent.focusSearch(this, direction);
6980        } else {
6981            return null;
6982        }
6983    }
6984
6985    /**
6986     * This method is the last chance for the focused view and its ancestors to
6987     * respond to an arrow key. This is called when the focused view did not
6988     * consume the key internally, nor could the view system find a new view in
6989     * the requested direction to give focus to.
6990     *
6991     * @param focused The currently focused view.
6992     * @param direction The direction focus wants to move. One of FOCUS_UP,
6993     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6994     * @return True if the this view consumed this unhandled move.
6995     */
6996    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6997        return false;
6998    }
6999
7000    /**
7001     * If a user manually specified the next view id for a particular direction,
7002     * use the root to look up the view.
7003     * @param root The root view of the hierarchy containing this view.
7004     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7005     * or FOCUS_BACKWARD.
7006     * @return The user specified next view, or null if there is none.
7007     */
7008    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7009        switch (direction) {
7010            case FOCUS_LEFT:
7011                if (mNextFocusLeftId == View.NO_ID) return null;
7012                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7013            case FOCUS_RIGHT:
7014                if (mNextFocusRightId == View.NO_ID) return null;
7015                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7016            case FOCUS_UP:
7017                if (mNextFocusUpId == View.NO_ID) return null;
7018                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7019            case FOCUS_DOWN:
7020                if (mNextFocusDownId == View.NO_ID) return null;
7021                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7022            case FOCUS_FORWARD:
7023                if (mNextFocusForwardId == View.NO_ID) return null;
7024                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7025            case FOCUS_BACKWARD: {
7026                if (mID == View.NO_ID) return null;
7027                final int id = mID;
7028                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7029                    @Override
7030                    public boolean apply(View t) {
7031                        return t.mNextFocusForwardId == id;
7032                    }
7033                });
7034            }
7035        }
7036        return null;
7037    }
7038
7039    private View findViewInsideOutShouldExist(View root, int id) {
7040        if (mMatchIdPredicate == null) {
7041            mMatchIdPredicate = new MatchIdPredicate();
7042        }
7043        mMatchIdPredicate.mId = id;
7044        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7045        if (result == null) {
7046            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7047        }
7048        return result;
7049    }
7050
7051    /**
7052     * Find and return all focusable views that are descendants of this view,
7053     * possibly including this view if it is focusable itself.
7054     *
7055     * @param direction The direction of the focus
7056     * @return A list of focusable views
7057     */
7058    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7059        ArrayList<View> result = new ArrayList<View>(24);
7060        addFocusables(result, direction);
7061        return result;
7062    }
7063
7064    /**
7065     * Add any focusable views that are descendants of this view (possibly
7066     * including this view if it is focusable itself) to views.  If we are in touch mode,
7067     * only add views that are also focusable in touch mode.
7068     *
7069     * @param views Focusable views found so far
7070     * @param direction The direction of the focus
7071     */
7072    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7073        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7074    }
7075
7076    /**
7077     * Adds any focusable views that are descendants of this view (possibly
7078     * including this view if it is focusable itself) to views. This method
7079     * adds all focusable views regardless if we are in touch mode or
7080     * only views focusable in touch mode if we are in touch mode or
7081     * only views that can take accessibility focus if accessibility is enabeld
7082     * depending on the focusable mode paramater.
7083     *
7084     * @param views Focusable views found so far or null if all we are interested is
7085     *        the number of focusables.
7086     * @param direction The direction of the focus.
7087     * @param focusableMode The type of focusables to be added.
7088     *
7089     * @see #FOCUSABLES_ALL
7090     * @see #FOCUSABLES_TOUCH_MODE
7091     */
7092    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7093            @FocusableMode int focusableMode) {
7094        if (views == null) {
7095            return;
7096        }
7097        if (!isFocusable()) {
7098            return;
7099        }
7100        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7101                && isInTouchMode() && !isFocusableInTouchMode()) {
7102            return;
7103        }
7104        views.add(this);
7105    }
7106
7107    /**
7108     * Finds the Views that contain given text. The containment is case insensitive.
7109     * The search is performed by either the text that the View renders or the content
7110     * description that describes the view for accessibility purposes and the view does
7111     * not render or both. Clients can specify how the search is to be performed via
7112     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7113     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7114     *
7115     * @param outViews The output list of matching Views.
7116     * @param searched The text to match against.
7117     *
7118     * @see #FIND_VIEWS_WITH_TEXT
7119     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7120     * @see #setContentDescription(CharSequence)
7121     */
7122    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7123            @FindViewFlags int flags) {
7124        if (getAccessibilityNodeProvider() != null) {
7125            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7126                outViews.add(this);
7127            }
7128        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7129                && (searched != null && searched.length() > 0)
7130                && (mContentDescription != null && mContentDescription.length() > 0)) {
7131            String searchedLowerCase = searched.toString().toLowerCase();
7132            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7133            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7134                outViews.add(this);
7135            }
7136        }
7137    }
7138
7139    /**
7140     * Find and return all touchable views that are descendants of this view,
7141     * possibly including this view if it is touchable itself.
7142     *
7143     * @return A list of touchable views
7144     */
7145    public ArrayList<View> getTouchables() {
7146        ArrayList<View> result = new ArrayList<View>();
7147        addTouchables(result);
7148        return result;
7149    }
7150
7151    /**
7152     * Add any touchable views that are descendants of this view (possibly
7153     * including this view if it is touchable itself) to views.
7154     *
7155     * @param views Touchable views found so far
7156     */
7157    public void addTouchables(ArrayList<View> views) {
7158        final int viewFlags = mViewFlags;
7159
7160        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7161                && (viewFlags & ENABLED_MASK) == ENABLED) {
7162            views.add(this);
7163        }
7164    }
7165
7166    /**
7167     * Returns whether this View is accessibility focused.
7168     *
7169     * @return True if this View is accessibility focused.
7170     */
7171    public boolean isAccessibilityFocused() {
7172        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7173    }
7174
7175    /**
7176     * Call this to try to give accessibility focus to this view.
7177     *
7178     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7179     * returns false or the view is no visible or the view already has accessibility
7180     * focus.
7181     *
7182     * See also {@link #focusSearch(int)}, which is what you call to say that you
7183     * have focus, and you want your parent to look for the next one.
7184     *
7185     * @return Whether this view actually took accessibility focus.
7186     *
7187     * @hide
7188     */
7189    public boolean requestAccessibilityFocus() {
7190        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7191        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7192            return false;
7193        }
7194        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7195            return false;
7196        }
7197        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7198            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7199            ViewRootImpl viewRootImpl = getViewRootImpl();
7200            if (viewRootImpl != null) {
7201                viewRootImpl.setAccessibilityFocus(this, null);
7202            }
7203            invalidate();
7204            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7205            return true;
7206        }
7207        return false;
7208    }
7209
7210    /**
7211     * Call this to try to clear accessibility focus of this view.
7212     *
7213     * See also {@link #focusSearch(int)}, which is what you call to say that you
7214     * have focus, and you want your parent to look for the next one.
7215     *
7216     * @hide
7217     */
7218    public void clearAccessibilityFocus() {
7219        clearAccessibilityFocusNoCallbacks();
7220        // Clear the global reference of accessibility focus if this
7221        // view or any of its descendants had accessibility focus.
7222        ViewRootImpl viewRootImpl = getViewRootImpl();
7223        if (viewRootImpl != null) {
7224            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7225            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7226                viewRootImpl.setAccessibilityFocus(null, null);
7227            }
7228        }
7229    }
7230
7231    private void sendAccessibilityHoverEvent(int eventType) {
7232        // Since we are not delivering to a client accessibility events from not
7233        // important views (unless the clinet request that) we need to fire the
7234        // event from the deepest view exposed to the client. As a consequence if
7235        // the user crosses a not exposed view the client will see enter and exit
7236        // of the exposed predecessor followed by and enter and exit of that same
7237        // predecessor when entering and exiting the not exposed descendant. This
7238        // is fine since the client has a clear idea which view is hovered at the
7239        // price of a couple more events being sent. This is a simple and
7240        // working solution.
7241        View source = this;
7242        while (true) {
7243            if (source.includeForAccessibility()) {
7244                source.sendAccessibilityEvent(eventType);
7245                return;
7246            }
7247            ViewParent parent = source.getParent();
7248            if (parent instanceof View) {
7249                source = (View) parent;
7250            } else {
7251                return;
7252            }
7253        }
7254    }
7255
7256    /**
7257     * Clears accessibility focus without calling any callback methods
7258     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7259     * is used for clearing accessibility focus when giving this focus to
7260     * another view.
7261     */
7262    void clearAccessibilityFocusNoCallbacks() {
7263        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7264            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7265            invalidate();
7266            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7267        }
7268    }
7269
7270    /**
7271     * Call this to try to give focus to a specific view or to one of its
7272     * descendants.
7273     *
7274     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7275     * false), or if it is focusable and it is not focusable in touch mode
7276     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7277     *
7278     * See also {@link #focusSearch(int)}, which is what you call to say that you
7279     * have focus, and you want your parent to look for the next one.
7280     *
7281     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7282     * {@link #FOCUS_DOWN} and <code>null</code>.
7283     *
7284     * @return Whether this view or one of its descendants actually took focus.
7285     */
7286    public final boolean requestFocus() {
7287        return requestFocus(View.FOCUS_DOWN);
7288    }
7289
7290    /**
7291     * Call this to try to give focus to a specific view or to one of its
7292     * descendants and give it a hint about what direction focus is heading.
7293     *
7294     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7295     * false), or if it is focusable and it is not focusable in touch mode
7296     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7297     *
7298     * See also {@link #focusSearch(int)}, which is what you call to say that you
7299     * have focus, and you want your parent to look for the next one.
7300     *
7301     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7302     * <code>null</code> set for the previously focused rectangle.
7303     *
7304     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7305     * @return Whether this view or one of its descendants actually took focus.
7306     */
7307    public final boolean requestFocus(int direction) {
7308        return requestFocus(direction, null);
7309    }
7310
7311    /**
7312     * Call this to try to give focus to a specific view or to one of its descendants
7313     * and give it hints about the direction and a specific rectangle that the focus
7314     * is coming from.  The rectangle can help give larger views a finer grained hint
7315     * about where focus is coming from, and therefore, where to show selection, or
7316     * forward focus change internally.
7317     *
7318     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7319     * false), or if it is focusable and it is not focusable in touch mode
7320     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7321     *
7322     * A View will not take focus if it is not visible.
7323     *
7324     * A View will not take focus if one of its parents has
7325     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7326     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7327     *
7328     * See also {@link #focusSearch(int)}, which is what you call to say that you
7329     * have focus, and you want your parent to look for the next one.
7330     *
7331     * You may wish to override this method if your custom {@link View} has an internal
7332     * {@link View} that it wishes to forward the request to.
7333     *
7334     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7335     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7336     *        to give a finer grained hint about where focus is coming from.  May be null
7337     *        if there is no hint.
7338     * @return Whether this view or one of its descendants actually took focus.
7339     */
7340    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7341        return requestFocusNoSearch(direction, previouslyFocusedRect);
7342    }
7343
7344    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7345        // need to be focusable
7346        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7347                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7348            return false;
7349        }
7350
7351        // need to be focusable in touch mode if in touch mode
7352        if (isInTouchMode() &&
7353            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7354               return false;
7355        }
7356
7357        // need to not have any parents blocking us
7358        if (hasAncestorThatBlocksDescendantFocus()) {
7359            return false;
7360        }
7361
7362        handleFocusGainInternal(direction, previouslyFocusedRect);
7363        return true;
7364    }
7365
7366    /**
7367     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7368     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7369     * touch mode to request focus when they are touched.
7370     *
7371     * @return Whether this view or one of its descendants actually took focus.
7372     *
7373     * @see #isInTouchMode()
7374     *
7375     */
7376    public final boolean requestFocusFromTouch() {
7377        // Leave touch mode if we need to
7378        if (isInTouchMode()) {
7379            ViewRootImpl viewRoot = getViewRootImpl();
7380            if (viewRoot != null) {
7381                viewRoot.ensureTouchMode(false);
7382            }
7383        }
7384        return requestFocus(View.FOCUS_DOWN);
7385    }
7386
7387    /**
7388     * @return Whether any ancestor of this view blocks descendant focus.
7389     */
7390    private boolean hasAncestorThatBlocksDescendantFocus() {
7391        ViewParent ancestor = mParent;
7392        while (ancestor instanceof ViewGroup) {
7393            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7394            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7395                return true;
7396            } else {
7397                ancestor = vgAncestor.getParent();
7398            }
7399        }
7400        return false;
7401    }
7402
7403    /**
7404     * Gets the mode for determining whether this View is important for accessibility
7405     * which is if it fires accessibility events and if it is reported to
7406     * accessibility services that query the screen.
7407     *
7408     * @return The mode for determining whether a View is important for accessibility.
7409     *
7410     * @attr ref android.R.styleable#View_importantForAccessibility
7411     *
7412     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7413     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7414     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7415     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7416     */
7417    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7418            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7419            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7420            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7421            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7422                    to = "noHideDescendants")
7423        })
7424    public int getImportantForAccessibility() {
7425        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7426                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7427    }
7428
7429    /**
7430     * Sets the live region mode for this view. This indicates to accessibility
7431     * services whether they should automatically notify the user about changes
7432     * to the view's content description or text, or to the content descriptions
7433     * or text of the view's children (where applicable).
7434     * <p>
7435     * For example, in a login screen with a TextView that displays an "incorrect
7436     * password" notification, that view should be marked as a live region with
7437     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7438     * <p>
7439     * To disable change notifications for this view, use
7440     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7441     * mode for most views.
7442     * <p>
7443     * To indicate that the user should be notified of changes, use
7444     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7445     * <p>
7446     * If the view's changes should interrupt ongoing speech and notify the user
7447     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7448     *
7449     * @param mode The live region mode for this view, one of:
7450     *        <ul>
7451     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7452     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7453     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7454     *        </ul>
7455     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7456     */
7457    public void setAccessibilityLiveRegion(int mode) {
7458        if (mode != getAccessibilityLiveRegion()) {
7459            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7460            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7461                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7462            notifyViewAccessibilityStateChangedIfNeeded(
7463                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7464        }
7465    }
7466
7467    /**
7468     * Gets the live region mode for this View.
7469     *
7470     * @return The live region mode for the view.
7471     *
7472     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7473     *
7474     * @see #setAccessibilityLiveRegion(int)
7475     */
7476    public int getAccessibilityLiveRegion() {
7477        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7478                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7479    }
7480
7481    /**
7482     * Sets how to determine whether this view is important for accessibility
7483     * which is if it fires accessibility events and if it is reported to
7484     * accessibility services that query the screen.
7485     *
7486     * @param mode How to determine whether this view is important for accessibility.
7487     *
7488     * @attr ref android.R.styleable#View_importantForAccessibility
7489     *
7490     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7491     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7492     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7493     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7494     */
7495    public void setImportantForAccessibility(int mode) {
7496        final int oldMode = getImportantForAccessibility();
7497        if (mode != oldMode) {
7498            // If we're moving between AUTO and another state, we might not need
7499            // to send a subtree changed notification. We'll store the computed
7500            // importance, since we'll need to check it later to make sure.
7501            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7502                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7503            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7504            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7505            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7506                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7507            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7508                notifySubtreeAccessibilityStateChangedIfNeeded();
7509            } else {
7510                notifyViewAccessibilityStateChangedIfNeeded(
7511                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7512            }
7513        }
7514    }
7515
7516    /**
7517     * Computes whether this view should be exposed for accessibility. In
7518     * general, views that are interactive or provide information are exposed
7519     * while views that serve only as containers are hidden.
7520     * <p>
7521     * If an ancestor of this view has importance
7522     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7523     * returns <code>false</code>.
7524     * <p>
7525     * Otherwise, the value is computed according to the view's
7526     * {@link #getImportantForAccessibility()} value:
7527     * <ol>
7528     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7529     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7530     * </code>
7531     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7532     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7533     * view satisfies any of the following:
7534     * <ul>
7535     * <li>Is actionable, e.g. {@link #isClickable()},
7536     * {@link #isLongClickable()}, or {@link #isFocusable()}
7537     * <li>Has an {@link AccessibilityDelegate}
7538     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7539     * {@link OnKeyListener}, etc.
7540     * <li>Is an accessibility live region, e.g.
7541     * {@link #getAccessibilityLiveRegion()} is not
7542     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7543     * </ul>
7544     * </ol>
7545     *
7546     * @return Whether the view is exposed for accessibility.
7547     * @see #setImportantForAccessibility(int)
7548     * @see #getImportantForAccessibility()
7549     */
7550    public boolean isImportantForAccessibility() {
7551        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7552                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7553        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7554                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7555            return false;
7556        }
7557
7558        // Check parent mode to ensure we're not hidden.
7559        ViewParent parent = mParent;
7560        while (parent instanceof View) {
7561            if (((View) parent).getImportantForAccessibility()
7562                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7563                return false;
7564            }
7565            parent = parent.getParent();
7566        }
7567
7568        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7569                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7570                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7571    }
7572
7573    /**
7574     * Gets the parent for accessibility purposes. Note that the parent for
7575     * accessibility is not necessary the immediate parent. It is the first
7576     * predecessor that is important for accessibility.
7577     *
7578     * @return The parent for accessibility purposes.
7579     */
7580    public ViewParent getParentForAccessibility() {
7581        if (mParent instanceof View) {
7582            View parentView = (View) mParent;
7583            if (parentView.includeForAccessibility()) {
7584                return mParent;
7585            } else {
7586                return mParent.getParentForAccessibility();
7587            }
7588        }
7589        return null;
7590    }
7591
7592    /**
7593     * Adds the children of a given View for accessibility. Since some Views are
7594     * not important for accessibility the children for accessibility are not
7595     * necessarily direct children of the view, rather they are the first level of
7596     * descendants important for accessibility.
7597     *
7598     * @param children The list of children for accessibility.
7599     */
7600    public void addChildrenForAccessibility(ArrayList<View> children) {
7601
7602    }
7603
7604    /**
7605     * Whether to regard this view for accessibility. A view is regarded for
7606     * accessibility if it is important for accessibility or the querying
7607     * accessibility service has explicitly requested that view not
7608     * important for accessibility are regarded.
7609     *
7610     * @return Whether to regard the view for accessibility.
7611     *
7612     * @hide
7613     */
7614    public boolean includeForAccessibility() {
7615        if (mAttachInfo != null) {
7616            return (mAttachInfo.mAccessibilityFetchFlags
7617                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7618                    || isImportantForAccessibility();
7619        }
7620        return false;
7621    }
7622
7623    /**
7624     * Returns whether the View is considered actionable from
7625     * accessibility perspective. Such view are important for
7626     * accessibility.
7627     *
7628     * @return True if the view is actionable for accessibility.
7629     *
7630     * @hide
7631     */
7632    public boolean isActionableForAccessibility() {
7633        return (isClickable() || isLongClickable() || isFocusable());
7634    }
7635
7636    /**
7637     * Returns whether the View has registered callbacks which makes it
7638     * important for accessibility.
7639     *
7640     * @return True if the view is actionable for accessibility.
7641     */
7642    private boolean hasListenersForAccessibility() {
7643        ListenerInfo info = getListenerInfo();
7644        return mTouchDelegate != null || info.mOnKeyListener != null
7645                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7646                || info.mOnHoverListener != null || info.mOnDragListener != null;
7647    }
7648
7649    /**
7650     * Notifies that the accessibility state of this view changed. The change
7651     * is local to this view and does not represent structural changes such
7652     * as children and parent. For example, the view became focusable. The
7653     * notification is at at most once every
7654     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7655     * to avoid unnecessary load to the system. Also once a view has a pending
7656     * notification this method is a NOP until the notification has been sent.
7657     *
7658     * @hide
7659     */
7660    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7661        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7662            return;
7663        }
7664        if (mSendViewStateChangedAccessibilityEvent == null) {
7665            mSendViewStateChangedAccessibilityEvent =
7666                    new SendViewStateChangedAccessibilityEvent();
7667        }
7668        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7669    }
7670
7671    /**
7672     * Notifies that the accessibility state of this view changed. The change
7673     * is *not* local to this view and does represent structural changes such
7674     * as children and parent. For example, the view size changed. The
7675     * notification is at at most once every
7676     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7677     * to avoid unnecessary load to the system. Also once a view has a pending
7678     * notifucation this method is a NOP until the notification has been sent.
7679     *
7680     * @hide
7681     */
7682    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7683        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7684            return;
7685        }
7686        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7687            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7688            if (mParent != null) {
7689                try {
7690                    mParent.notifySubtreeAccessibilityStateChanged(
7691                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7692                } catch (AbstractMethodError e) {
7693                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7694                            " does not fully implement ViewParent", e);
7695                }
7696            }
7697        }
7698    }
7699
7700    /**
7701     * Reset the flag indicating the accessibility state of the subtree rooted
7702     * at this view changed.
7703     */
7704    void resetSubtreeAccessibilityStateChanged() {
7705        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7706    }
7707
7708    /**
7709     * Performs the specified accessibility action on the view. For
7710     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7711     * <p>
7712     * If an {@link AccessibilityDelegate} has been specified via calling
7713     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7714     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7715     * is responsible for handling this call.
7716     * </p>
7717     *
7718     * @param action The action to perform.
7719     * @param arguments Optional action arguments.
7720     * @return Whether the action was performed.
7721     */
7722    public boolean performAccessibilityAction(int action, Bundle arguments) {
7723      if (mAccessibilityDelegate != null) {
7724          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7725      } else {
7726          return performAccessibilityActionInternal(action, arguments);
7727      }
7728    }
7729
7730   /**
7731    * @see #performAccessibilityAction(int, Bundle)
7732    *
7733    * Note: Called from the default {@link AccessibilityDelegate}.
7734    */
7735    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7736        switch (action) {
7737            case AccessibilityNodeInfo.ACTION_CLICK: {
7738                if (isClickable()) {
7739                    performClick();
7740                    return true;
7741                }
7742            } break;
7743            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7744                if (isLongClickable()) {
7745                    performLongClick();
7746                    return true;
7747                }
7748            } break;
7749            case AccessibilityNodeInfo.ACTION_FOCUS: {
7750                if (!hasFocus()) {
7751                    // Get out of touch mode since accessibility
7752                    // wants to move focus around.
7753                    getViewRootImpl().ensureTouchMode(false);
7754                    return requestFocus();
7755                }
7756            } break;
7757            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7758                if (hasFocus()) {
7759                    clearFocus();
7760                    return !isFocused();
7761                }
7762            } break;
7763            case AccessibilityNodeInfo.ACTION_SELECT: {
7764                if (!isSelected()) {
7765                    setSelected(true);
7766                    return isSelected();
7767                }
7768            } break;
7769            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7770                if (isSelected()) {
7771                    setSelected(false);
7772                    return !isSelected();
7773                }
7774            } break;
7775            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7776                if (!isAccessibilityFocused()) {
7777                    return requestAccessibilityFocus();
7778                }
7779            } break;
7780            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7781                if (isAccessibilityFocused()) {
7782                    clearAccessibilityFocus();
7783                    return true;
7784                }
7785            } break;
7786            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7787                if (arguments != null) {
7788                    final int granularity = arguments.getInt(
7789                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7790                    final boolean extendSelection = arguments.getBoolean(
7791                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7792                    return traverseAtGranularity(granularity, true, extendSelection);
7793                }
7794            } break;
7795            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7796                if (arguments != null) {
7797                    final int granularity = arguments.getInt(
7798                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7799                    final boolean extendSelection = arguments.getBoolean(
7800                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7801                    return traverseAtGranularity(granularity, false, extendSelection);
7802                }
7803            } break;
7804            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7805                CharSequence text = getIterableTextForAccessibility();
7806                if (text == null) {
7807                    return false;
7808                }
7809                final int start = (arguments != null) ? arguments.getInt(
7810                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7811                final int end = (arguments != null) ? arguments.getInt(
7812                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7813                // Only cursor position can be specified (selection length == 0)
7814                if ((getAccessibilitySelectionStart() != start
7815                        || getAccessibilitySelectionEnd() != end)
7816                        && (start == end)) {
7817                    setAccessibilitySelection(start, end);
7818                    notifyViewAccessibilityStateChangedIfNeeded(
7819                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7820                    return true;
7821                }
7822            } break;
7823        }
7824        return false;
7825    }
7826
7827    private boolean traverseAtGranularity(int granularity, boolean forward,
7828            boolean extendSelection) {
7829        CharSequence text = getIterableTextForAccessibility();
7830        if (text == null || text.length() == 0) {
7831            return false;
7832        }
7833        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7834        if (iterator == null) {
7835            return false;
7836        }
7837        int current = getAccessibilitySelectionEnd();
7838        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7839            current = forward ? 0 : text.length();
7840        }
7841        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7842        if (range == null) {
7843            return false;
7844        }
7845        final int segmentStart = range[0];
7846        final int segmentEnd = range[1];
7847        int selectionStart;
7848        int selectionEnd;
7849        if (extendSelection && isAccessibilitySelectionExtendable()) {
7850            selectionStart = getAccessibilitySelectionStart();
7851            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7852                selectionStart = forward ? segmentStart : segmentEnd;
7853            }
7854            selectionEnd = forward ? segmentEnd : segmentStart;
7855        } else {
7856            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7857        }
7858        setAccessibilitySelection(selectionStart, selectionEnd);
7859        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7860                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7861        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7862        return true;
7863    }
7864
7865    /**
7866     * Gets the text reported for accessibility purposes.
7867     *
7868     * @return The accessibility text.
7869     *
7870     * @hide
7871     */
7872    public CharSequence getIterableTextForAccessibility() {
7873        return getContentDescription();
7874    }
7875
7876    /**
7877     * Gets whether accessibility selection can be extended.
7878     *
7879     * @return If selection is extensible.
7880     *
7881     * @hide
7882     */
7883    public boolean isAccessibilitySelectionExtendable() {
7884        return false;
7885    }
7886
7887    /**
7888     * @hide
7889     */
7890    public int getAccessibilitySelectionStart() {
7891        return mAccessibilityCursorPosition;
7892    }
7893
7894    /**
7895     * @hide
7896     */
7897    public int getAccessibilitySelectionEnd() {
7898        return getAccessibilitySelectionStart();
7899    }
7900
7901    /**
7902     * @hide
7903     */
7904    public void setAccessibilitySelection(int start, int end) {
7905        if (start ==  end && end == mAccessibilityCursorPosition) {
7906            return;
7907        }
7908        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7909            mAccessibilityCursorPosition = start;
7910        } else {
7911            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7912        }
7913        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7914    }
7915
7916    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7917            int fromIndex, int toIndex) {
7918        if (mParent == null) {
7919            return;
7920        }
7921        AccessibilityEvent event = AccessibilityEvent.obtain(
7922                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7923        onInitializeAccessibilityEvent(event);
7924        onPopulateAccessibilityEvent(event);
7925        event.setFromIndex(fromIndex);
7926        event.setToIndex(toIndex);
7927        event.setAction(action);
7928        event.setMovementGranularity(granularity);
7929        mParent.requestSendAccessibilityEvent(this, event);
7930    }
7931
7932    /**
7933     * @hide
7934     */
7935    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7936        switch (granularity) {
7937            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7938                CharSequence text = getIterableTextForAccessibility();
7939                if (text != null && text.length() > 0) {
7940                    CharacterTextSegmentIterator iterator =
7941                        CharacterTextSegmentIterator.getInstance(
7942                                mContext.getResources().getConfiguration().locale);
7943                    iterator.initialize(text.toString());
7944                    return iterator;
7945                }
7946            } break;
7947            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7948                CharSequence text = getIterableTextForAccessibility();
7949                if (text != null && text.length() > 0) {
7950                    WordTextSegmentIterator iterator =
7951                        WordTextSegmentIterator.getInstance(
7952                                mContext.getResources().getConfiguration().locale);
7953                    iterator.initialize(text.toString());
7954                    return iterator;
7955                }
7956            } break;
7957            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7958                CharSequence text = getIterableTextForAccessibility();
7959                if (text != null && text.length() > 0) {
7960                    ParagraphTextSegmentIterator iterator =
7961                        ParagraphTextSegmentIterator.getInstance();
7962                    iterator.initialize(text.toString());
7963                    return iterator;
7964                }
7965            } break;
7966        }
7967        return null;
7968    }
7969
7970    /**
7971     * @hide
7972     */
7973    public void dispatchStartTemporaryDetach() {
7974        onStartTemporaryDetach();
7975    }
7976
7977    /**
7978     * This is called when a container is going to temporarily detach a child, with
7979     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7980     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7981     * {@link #onDetachedFromWindow()} when the container is done.
7982     */
7983    public void onStartTemporaryDetach() {
7984        removeUnsetPressCallback();
7985        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7986    }
7987
7988    /**
7989     * @hide
7990     */
7991    public void dispatchFinishTemporaryDetach() {
7992        onFinishTemporaryDetach();
7993    }
7994
7995    /**
7996     * Called after {@link #onStartTemporaryDetach} when the container is done
7997     * changing the view.
7998     */
7999    public void onFinishTemporaryDetach() {
8000    }
8001
8002    /**
8003     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8004     * for this view's window.  Returns null if the view is not currently attached
8005     * to the window.  Normally you will not need to use this directly, but
8006     * just use the standard high-level event callbacks like
8007     * {@link #onKeyDown(int, KeyEvent)}.
8008     */
8009    public KeyEvent.DispatcherState getKeyDispatcherState() {
8010        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8011    }
8012
8013    /**
8014     * Dispatch a key event before it is processed by any input method
8015     * associated with the view hierarchy.  This can be used to intercept
8016     * key events in special situations before the IME consumes them; a
8017     * typical example would be handling the BACK key to update the application's
8018     * UI instead of allowing the IME to see it and close itself.
8019     *
8020     * @param event The key event to be dispatched.
8021     * @return True if the event was handled, false otherwise.
8022     */
8023    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8024        return onKeyPreIme(event.getKeyCode(), event);
8025    }
8026
8027    /**
8028     * Dispatch a key event to the next view on the focus path. This path runs
8029     * from the top of the view tree down to the currently focused view. If this
8030     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8031     * the next node down the focus path. This method also fires any key
8032     * listeners.
8033     *
8034     * @param event The key event to be dispatched.
8035     * @return True if the event was handled, false otherwise.
8036     */
8037    public boolean dispatchKeyEvent(KeyEvent event) {
8038        if (mInputEventConsistencyVerifier != null) {
8039            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8040        }
8041
8042        // Give any attached key listener a first crack at the event.
8043        //noinspection SimplifiableIfStatement
8044        ListenerInfo li = mListenerInfo;
8045        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8046                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8047            return true;
8048        }
8049
8050        if (event.dispatch(this, mAttachInfo != null
8051                ? mAttachInfo.mKeyDispatchState : null, this)) {
8052            return true;
8053        }
8054
8055        if (mInputEventConsistencyVerifier != null) {
8056            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8057        }
8058        return false;
8059    }
8060
8061    /**
8062     * Dispatches a key shortcut event.
8063     *
8064     * @param event The key event to be dispatched.
8065     * @return True if the event was handled by the view, false otherwise.
8066     */
8067    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8068        return onKeyShortcut(event.getKeyCode(), event);
8069    }
8070
8071    /**
8072     * Pass the touch screen motion event down to the target view, or this
8073     * view if it is the target.
8074     *
8075     * @param event The motion event to be dispatched.
8076     * @return True if the event was handled by the view, false otherwise.
8077     */
8078    public boolean dispatchTouchEvent(MotionEvent event) {
8079        if (mInputEventConsistencyVerifier != null) {
8080            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8081        }
8082
8083        if (onFilterTouchEventForSecurity(event)) {
8084            //noinspection SimplifiableIfStatement
8085            ListenerInfo li = mListenerInfo;
8086            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8087                    && li.mOnTouchListener.onTouch(this, event)) {
8088                return true;
8089            }
8090
8091            if (onTouchEvent(event)) {
8092                return true;
8093            }
8094        }
8095
8096        if (mInputEventConsistencyVerifier != null) {
8097            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8098        }
8099        return false;
8100    }
8101
8102    /**
8103     * Filter the touch event to apply security policies.
8104     *
8105     * @param event The motion event to be filtered.
8106     * @return True if the event should be dispatched, false if the event should be dropped.
8107     *
8108     * @see #getFilterTouchesWhenObscured
8109     */
8110    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8111        //noinspection RedundantIfStatement
8112        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8113                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8114            // Window is obscured, drop this touch.
8115            return false;
8116        }
8117        return true;
8118    }
8119
8120    /**
8121     * Pass a trackball motion event down to the focused view.
8122     *
8123     * @param event The motion event to be dispatched.
8124     * @return True if the event was handled by the view, false otherwise.
8125     */
8126    public boolean dispatchTrackballEvent(MotionEvent event) {
8127        if (mInputEventConsistencyVerifier != null) {
8128            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8129        }
8130
8131        return onTrackballEvent(event);
8132    }
8133
8134    /**
8135     * Dispatch a generic motion event.
8136     * <p>
8137     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8138     * are delivered to the view under the pointer.  All other generic motion events are
8139     * delivered to the focused view.  Hover events are handled specially and are delivered
8140     * to {@link #onHoverEvent(MotionEvent)}.
8141     * </p>
8142     *
8143     * @param event The motion event to be dispatched.
8144     * @return True if the event was handled by the view, false otherwise.
8145     */
8146    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8147        if (mInputEventConsistencyVerifier != null) {
8148            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8149        }
8150
8151        final int source = event.getSource();
8152        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8153            final int action = event.getAction();
8154            if (action == MotionEvent.ACTION_HOVER_ENTER
8155                    || action == MotionEvent.ACTION_HOVER_MOVE
8156                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8157                if (dispatchHoverEvent(event)) {
8158                    return true;
8159                }
8160            } else if (dispatchGenericPointerEvent(event)) {
8161                return true;
8162            }
8163        } else if (dispatchGenericFocusedEvent(event)) {
8164            return true;
8165        }
8166
8167        if (dispatchGenericMotionEventInternal(event)) {
8168            return true;
8169        }
8170
8171        if (mInputEventConsistencyVerifier != null) {
8172            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8173        }
8174        return false;
8175    }
8176
8177    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8178        //noinspection SimplifiableIfStatement
8179        ListenerInfo li = mListenerInfo;
8180        if (li != null && li.mOnGenericMotionListener != null
8181                && (mViewFlags & ENABLED_MASK) == ENABLED
8182                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8183            return true;
8184        }
8185
8186        if (onGenericMotionEvent(event)) {
8187            return true;
8188        }
8189
8190        if (mInputEventConsistencyVerifier != null) {
8191            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8192        }
8193        return false;
8194    }
8195
8196    /**
8197     * Dispatch a hover event.
8198     * <p>
8199     * Do not call this method directly.
8200     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8201     * </p>
8202     *
8203     * @param event The motion event to be dispatched.
8204     * @return True if the event was handled by the view, false otherwise.
8205     */
8206    protected boolean dispatchHoverEvent(MotionEvent event) {
8207        ListenerInfo li = mListenerInfo;
8208        //noinspection SimplifiableIfStatement
8209        if (li != null && li.mOnHoverListener != null
8210                && (mViewFlags & ENABLED_MASK) == ENABLED
8211                && li.mOnHoverListener.onHover(this, event)) {
8212            return true;
8213        }
8214
8215        return onHoverEvent(event);
8216    }
8217
8218    /**
8219     * Returns true if the view has a child to which it has recently sent
8220     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8221     * it does not have a hovered child, then it must be the innermost hovered view.
8222     * @hide
8223     */
8224    protected boolean hasHoveredChild() {
8225        return false;
8226    }
8227
8228    /**
8229     * Dispatch a generic motion event to the view under the first pointer.
8230     * <p>
8231     * Do not call this method directly.
8232     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8233     * </p>
8234     *
8235     * @param event The motion event to be dispatched.
8236     * @return True if the event was handled by the view, false otherwise.
8237     */
8238    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8239        return false;
8240    }
8241
8242    /**
8243     * Dispatch a generic motion event to the currently focused view.
8244     * <p>
8245     * Do not call this method directly.
8246     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8247     * </p>
8248     *
8249     * @param event The motion event to be dispatched.
8250     * @return True if the event was handled by the view, false otherwise.
8251     */
8252    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8253        return false;
8254    }
8255
8256    /**
8257     * Dispatch a pointer event.
8258     * <p>
8259     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8260     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8261     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8262     * and should not be expected to handle other pointing device features.
8263     * </p>
8264     *
8265     * @param event The motion event to be dispatched.
8266     * @return True if the event was handled by the view, false otherwise.
8267     * @hide
8268     */
8269    public final boolean dispatchPointerEvent(MotionEvent event) {
8270        if (event.isTouchEvent()) {
8271            return dispatchTouchEvent(event);
8272        } else {
8273            return dispatchGenericMotionEvent(event);
8274        }
8275    }
8276
8277    /**
8278     * Called when the window containing this view gains or loses window focus.
8279     * ViewGroups should override to route to their children.
8280     *
8281     * @param hasFocus True if the window containing this view now has focus,
8282     *        false otherwise.
8283     */
8284    public void dispatchWindowFocusChanged(boolean hasFocus) {
8285        onWindowFocusChanged(hasFocus);
8286    }
8287
8288    /**
8289     * Called when the window containing this view gains or loses focus.  Note
8290     * that this is separate from view focus: to receive key events, both
8291     * your view and its window must have focus.  If a window is displayed
8292     * on top of yours that takes input focus, then your own window will lose
8293     * focus but the view focus will remain unchanged.
8294     *
8295     * @param hasWindowFocus True if the window containing this view now has
8296     *        focus, false otherwise.
8297     */
8298    public void onWindowFocusChanged(boolean hasWindowFocus) {
8299        InputMethodManager imm = InputMethodManager.peekInstance();
8300        if (!hasWindowFocus) {
8301            if (isPressed()) {
8302                setPressed(false);
8303            }
8304            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8305                imm.focusOut(this);
8306            }
8307            removeLongPressCallback();
8308            removeTapCallback();
8309            onFocusLost();
8310        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8311            imm.focusIn(this);
8312        }
8313        refreshDrawableState();
8314    }
8315
8316    /**
8317     * Returns true if this view is in a window that currently has window focus.
8318     * Note that this is not the same as the view itself having focus.
8319     *
8320     * @return True if this view is in a window that currently has window focus.
8321     */
8322    public boolean hasWindowFocus() {
8323        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8324    }
8325
8326    /**
8327     * Dispatch a view visibility change down the view hierarchy.
8328     * ViewGroups should override to route to their children.
8329     * @param changedView The view whose visibility changed. Could be 'this' or
8330     * an ancestor view.
8331     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8332     * {@link #INVISIBLE} or {@link #GONE}.
8333     */
8334    protected void dispatchVisibilityChanged(@NonNull View changedView,
8335            @Visibility int visibility) {
8336        onVisibilityChanged(changedView, visibility);
8337    }
8338
8339    /**
8340     * Called when the visibility of the view or an ancestor of the view is changed.
8341     * @param changedView The view whose visibility changed. Could be 'this' or
8342     * an ancestor view.
8343     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8344     * {@link #INVISIBLE} or {@link #GONE}.
8345     */
8346    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8347        if (visibility == VISIBLE) {
8348            if (mAttachInfo != null) {
8349                initialAwakenScrollBars();
8350            } else {
8351                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8352            }
8353        }
8354    }
8355
8356    /**
8357     * Dispatch a hint about whether this view is displayed. For instance, when
8358     * a View moves out of the screen, it might receives a display hint indicating
8359     * the view is not displayed. Applications should not <em>rely</em> on this hint
8360     * as there is no guarantee that they will receive one.
8361     *
8362     * @param hint A hint about whether or not this view is displayed:
8363     * {@link #VISIBLE} or {@link #INVISIBLE}.
8364     */
8365    public void dispatchDisplayHint(@Visibility int hint) {
8366        onDisplayHint(hint);
8367    }
8368
8369    /**
8370     * Gives this view a hint about whether is displayed or not. For instance, when
8371     * a View moves out of the screen, it might receives a display hint indicating
8372     * the view is not displayed. Applications should not <em>rely</em> on this hint
8373     * as there is no guarantee that they will receive one.
8374     *
8375     * @param hint A hint about whether or not this view is displayed:
8376     * {@link #VISIBLE} or {@link #INVISIBLE}.
8377     */
8378    protected void onDisplayHint(@Visibility int hint) {
8379    }
8380
8381    /**
8382     * Dispatch a window visibility change down the view hierarchy.
8383     * ViewGroups should override to route to their children.
8384     *
8385     * @param visibility The new visibility of the window.
8386     *
8387     * @see #onWindowVisibilityChanged(int)
8388     */
8389    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8390        onWindowVisibilityChanged(visibility);
8391    }
8392
8393    /**
8394     * Called when the window containing has change its visibility
8395     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8396     * that this tells you whether or not your window is being made visible
8397     * to the window manager; this does <em>not</em> tell you whether or not
8398     * your window is obscured by other windows on the screen, even if it
8399     * is itself visible.
8400     *
8401     * @param visibility The new visibility of the window.
8402     */
8403    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8404        if (visibility == VISIBLE) {
8405            initialAwakenScrollBars();
8406        }
8407    }
8408
8409    /**
8410     * Returns the current visibility of the window this view is attached to
8411     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8412     *
8413     * @return Returns the current visibility of the view's window.
8414     */
8415    @Visibility
8416    public int getWindowVisibility() {
8417        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8418    }
8419
8420    /**
8421     * Retrieve the overall visible display size in which the window this view is
8422     * attached to has been positioned in.  This takes into account screen
8423     * decorations above the window, for both cases where the window itself
8424     * is being position inside of them or the window is being placed under
8425     * then and covered insets are used for the window to position its content
8426     * inside.  In effect, this tells you the available area where content can
8427     * be placed and remain visible to users.
8428     *
8429     * <p>This function requires an IPC back to the window manager to retrieve
8430     * the requested information, so should not be used in performance critical
8431     * code like drawing.
8432     *
8433     * @param outRect Filled in with the visible display frame.  If the view
8434     * is not attached to a window, this is simply the raw display size.
8435     */
8436    public void getWindowVisibleDisplayFrame(Rect outRect) {
8437        if (mAttachInfo != null) {
8438            try {
8439                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8440            } catch (RemoteException e) {
8441                return;
8442            }
8443            // XXX This is really broken, and probably all needs to be done
8444            // in the window manager, and we need to know more about whether
8445            // we want the area behind or in front of the IME.
8446            final Rect insets = mAttachInfo.mVisibleInsets;
8447            outRect.left += insets.left;
8448            outRect.top += insets.top;
8449            outRect.right -= insets.right;
8450            outRect.bottom -= insets.bottom;
8451            return;
8452        }
8453        // The view is not attached to a display so we don't have a context.
8454        // Make a best guess about the display size.
8455        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8456        d.getRectSize(outRect);
8457    }
8458
8459    /**
8460     * Dispatch a notification about a resource configuration change down
8461     * the view hierarchy.
8462     * ViewGroups should override to route to their children.
8463     *
8464     * @param newConfig The new resource configuration.
8465     *
8466     * @see #onConfigurationChanged(android.content.res.Configuration)
8467     */
8468    public void dispatchConfigurationChanged(Configuration newConfig) {
8469        onConfigurationChanged(newConfig);
8470    }
8471
8472    /**
8473     * Called when the current configuration of the resources being used
8474     * by the application have changed.  You can use this to decide when
8475     * to reload resources that can changed based on orientation and other
8476     * configuration characterstics.  You only need to use this if you are
8477     * not relying on the normal {@link android.app.Activity} mechanism of
8478     * recreating the activity instance upon a configuration change.
8479     *
8480     * @param newConfig The new resource configuration.
8481     */
8482    protected void onConfigurationChanged(Configuration newConfig) {
8483    }
8484
8485    /**
8486     * Private function to aggregate all per-view attributes in to the view
8487     * root.
8488     */
8489    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8490        performCollectViewAttributes(attachInfo, visibility);
8491    }
8492
8493    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8494        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8495            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8496                attachInfo.mKeepScreenOn = true;
8497            }
8498            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8499            ListenerInfo li = mListenerInfo;
8500            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8501                attachInfo.mHasSystemUiListeners = true;
8502            }
8503        }
8504    }
8505
8506    void needGlobalAttributesUpdate(boolean force) {
8507        final AttachInfo ai = mAttachInfo;
8508        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8509            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8510                    || ai.mHasSystemUiListeners) {
8511                ai.mRecomputeGlobalAttributes = true;
8512            }
8513        }
8514    }
8515
8516    /**
8517     * Returns whether the device is currently in touch mode.  Touch mode is entered
8518     * once the user begins interacting with the device by touch, and affects various
8519     * things like whether focus is always visible to the user.
8520     *
8521     * @return Whether the device is in touch mode.
8522     */
8523    @ViewDebug.ExportedProperty
8524    public boolean isInTouchMode() {
8525        if (mAttachInfo != null) {
8526            return mAttachInfo.mInTouchMode;
8527        } else {
8528            return ViewRootImpl.isInTouchMode();
8529        }
8530    }
8531
8532    /**
8533     * Returns the context the view is running in, through which it can
8534     * access the current theme, resources, etc.
8535     *
8536     * @return The view's Context.
8537     */
8538    @ViewDebug.CapturedViewProperty
8539    public final Context getContext() {
8540        return mContext;
8541    }
8542
8543    /**
8544     * Handle a key event before it is processed by any input method
8545     * associated with the view hierarchy.  This can be used to intercept
8546     * key events in special situations before the IME consumes them; a
8547     * typical example would be handling the BACK key to update the application's
8548     * UI instead of allowing the IME to see it and close itself.
8549     *
8550     * @param keyCode The value in event.getKeyCode().
8551     * @param event Description of the key event.
8552     * @return If you handled the event, return true. If you want to allow the
8553     *         event to be handled by the next receiver, return false.
8554     */
8555    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8556        return false;
8557    }
8558
8559    /**
8560     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8561     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8562     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8563     * is released, if the view is enabled and clickable.
8564     *
8565     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8566     * although some may elect to do so in some situations. Do not rely on this to
8567     * catch software key presses.
8568     *
8569     * @param keyCode A key code that represents the button pressed, from
8570     *                {@link android.view.KeyEvent}.
8571     * @param event   The KeyEvent object that defines the button action.
8572     */
8573    public boolean onKeyDown(int keyCode, KeyEvent event) {
8574        boolean result = false;
8575
8576        if (KeyEvent.isConfirmKey(keyCode)) {
8577            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8578                return true;
8579            }
8580            // Long clickable items don't necessarily have to be clickable
8581            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8582                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8583                    (event.getRepeatCount() == 0)) {
8584                setPressed(true);
8585                checkForLongClick(0);
8586                return true;
8587            }
8588        }
8589        return result;
8590    }
8591
8592    /**
8593     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8594     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8595     * the event).
8596     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8597     * although some may elect to do so in some situations. Do not rely on this to
8598     * catch software key presses.
8599     */
8600    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8601        return false;
8602    }
8603
8604    /**
8605     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8606     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8607     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8608     * {@link KeyEvent#KEYCODE_ENTER} is released.
8609     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8610     * although some may elect to do so in some situations. Do not rely on this to
8611     * catch software key presses.
8612     *
8613     * @param keyCode A key code that represents the button pressed, from
8614     *                {@link android.view.KeyEvent}.
8615     * @param event   The KeyEvent object that defines the button action.
8616     */
8617    public boolean onKeyUp(int keyCode, KeyEvent event) {
8618        if (KeyEvent.isConfirmKey(keyCode)) {
8619            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8620                return true;
8621            }
8622            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8623                setPressed(false);
8624
8625                if (!mHasPerformedLongPress) {
8626                    // This is a tap, so remove the longpress check
8627                    removeLongPressCallback();
8628                    return performClick();
8629                }
8630            }
8631        }
8632        return false;
8633    }
8634
8635    /**
8636     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8637     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8638     * the event).
8639     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8640     * although some may elect to do so in some situations. Do not rely on this to
8641     * catch software key presses.
8642     *
8643     * @param keyCode     A key code that represents the button pressed, from
8644     *                    {@link android.view.KeyEvent}.
8645     * @param repeatCount The number of times the action was made.
8646     * @param event       The KeyEvent object that defines the button action.
8647     */
8648    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8649        return false;
8650    }
8651
8652    /**
8653     * Called on the focused view when a key shortcut event is not handled.
8654     * Override this method to implement local key shortcuts for the View.
8655     * Key shortcuts can also be implemented by setting the
8656     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8657     *
8658     * @param keyCode The value in event.getKeyCode().
8659     * @param event Description of the key event.
8660     * @return If you handled the event, return true. If you want to allow the
8661     *         event to be handled by the next receiver, return false.
8662     */
8663    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8664        return false;
8665    }
8666
8667    /**
8668     * Check whether the called view is a text editor, in which case it
8669     * would make sense to automatically display a soft input window for
8670     * it.  Subclasses should override this if they implement
8671     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8672     * a call on that method would return a non-null InputConnection, and
8673     * they are really a first-class editor that the user would normally
8674     * start typing on when the go into a window containing your view.
8675     *
8676     * <p>The default implementation always returns false.  This does
8677     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8678     * will not be called or the user can not otherwise perform edits on your
8679     * view; it is just a hint to the system that this is not the primary
8680     * purpose of this view.
8681     *
8682     * @return Returns true if this view is a text editor, else false.
8683     */
8684    public boolean onCheckIsTextEditor() {
8685        return false;
8686    }
8687
8688    /**
8689     * Create a new InputConnection for an InputMethod to interact
8690     * with the view.  The default implementation returns null, since it doesn't
8691     * support input methods.  You can override this to implement such support.
8692     * This is only needed for views that take focus and text input.
8693     *
8694     * <p>When implementing this, you probably also want to implement
8695     * {@link #onCheckIsTextEditor()} to indicate you will return a
8696     * non-null InputConnection.</p>
8697     *
8698     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8699     * object correctly and in its entirety, so that the connected IME can rely
8700     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8701     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8702     * must be filled in with the correct cursor position for IMEs to work correctly
8703     * with your application.</p>
8704     *
8705     * @param outAttrs Fill in with attribute information about the connection.
8706     */
8707    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8708        return null;
8709    }
8710
8711    /**
8712     * Called by the {@link android.view.inputmethod.InputMethodManager}
8713     * when a view who is not the current
8714     * input connection target is trying to make a call on the manager.  The
8715     * default implementation returns false; you can override this to return
8716     * true for certain views if you are performing InputConnection proxying
8717     * to them.
8718     * @param view The View that is making the InputMethodManager call.
8719     * @return Return true to allow the call, false to reject.
8720     */
8721    public boolean checkInputConnectionProxy(View view) {
8722        return false;
8723    }
8724
8725    /**
8726     * Show the context menu for this view. It is not safe to hold on to the
8727     * menu after returning from this method.
8728     *
8729     * You should normally not overload this method. Overload
8730     * {@link #onCreateContextMenu(ContextMenu)} or define an
8731     * {@link OnCreateContextMenuListener} to add items to the context menu.
8732     *
8733     * @param menu The context menu to populate
8734     */
8735    public void createContextMenu(ContextMenu menu) {
8736        ContextMenuInfo menuInfo = getContextMenuInfo();
8737
8738        // Sets the current menu info so all items added to menu will have
8739        // my extra info set.
8740        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8741
8742        onCreateContextMenu(menu);
8743        ListenerInfo li = mListenerInfo;
8744        if (li != null && li.mOnCreateContextMenuListener != null) {
8745            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8746        }
8747
8748        // Clear the extra information so subsequent items that aren't mine don't
8749        // have my extra info.
8750        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8751
8752        if (mParent != null) {
8753            mParent.createContextMenu(menu);
8754        }
8755    }
8756
8757    /**
8758     * Views should implement this if they have extra information to associate
8759     * with the context menu. The return result is supplied as a parameter to
8760     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8761     * callback.
8762     *
8763     * @return Extra information about the item for which the context menu
8764     *         should be shown. This information will vary across different
8765     *         subclasses of View.
8766     */
8767    protected ContextMenuInfo getContextMenuInfo() {
8768        return null;
8769    }
8770
8771    /**
8772     * Views should implement this if the view itself is going to add items to
8773     * the context menu.
8774     *
8775     * @param menu the context menu to populate
8776     */
8777    protected void onCreateContextMenu(ContextMenu menu) {
8778    }
8779
8780    /**
8781     * Implement this method to handle trackball motion events.  The
8782     * <em>relative</em> movement of the trackball since the last event
8783     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8784     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8785     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8786     * they will often be fractional values, representing the more fine-grained
8787     * movement information available from a trackball).
8788     *
8789     * @param event The motion event.
8790     * @return True if the event was handled, false otherwise.
8791     */
8792    public boolean onTrackballEvent(MotionEvent event) {
8793        return false;
8794    }
8795
8796    /**
8797     * Implement this method to handle generic motion events.
8798     * <p>
8799     * Generic motion events describe joystick movements, mouse hovers, track pad
8800     * touches, scroll wheel movements and other input events.  The
8801     * {@link MotionEvent#getSource() source} of the motion event specifies
8802     * the class of input that was received.  Implementations of this method
8803     * must examine the bits in the source before processing the event.
8804     * The following code example shows how this is done.
8805     * </p><p>
8806     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8807     * are delivered to the view under the pointer.  All other generic motion events are
8808     * delivered to the focused view.
8809     * </p>
8810     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8811     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8812     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8813     *             // process the joystick movement...
8814     *             return true;
8815     *         }
8816     *     }
8817     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8818     *         switch (event.getAction()) {
8819     *             case MotionEvent.ACTION_HOVER_MOVE:
8820     *                 // process the mouse hover movement...
8821     *                 return true;
8822     *             case MotionEvent.ACTION_SCROLL:
8823     *                 // process the scroll wheel movement...
8824     *                 return true;
8825     *         }
8826     *     }
8827     *     return super.onGenericMotionEvent(event);
8828     * }</pre>
8829     *
8830     * @param event The generic motion event being processed.
8831     * @return True if the event was handled, false otherwise.
8832     */
8833    public boolean onGenericMotionEvent(MotionEvent event) {
8834        return false;
8835    }
8836
8837    /**
8838     * Implement this method to handle hover events.
8839     * <p>
8840     * This method is called whenever a pointer is hovering into, over, or out of the
8841     * bounds of a view and the view is not currently being touched.
8842     * Hover events are represented as pointer events with action
8843     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8844     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8845     * </p>
8846     * <ul>
8847     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8848     * when the pointer enters the bounds of the view.</li>
8849     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8850     * when the pointer has already entered the bounds of the view and has moved.</li>
8851     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8852     * when the pointer has exited the bounds of the view or when the pointer is
8853     * about to go down due to a button click, tap, or similar user action that
8854     * causes the view to be touched.</li>
8855     * </ul>
8856     * <p>
8857     * The view should implement this method to return true to indicate that it is
8858     * handling the hover event, such as by changing its drawable state.
8859     * </p><p>
8860     * The default implementation calls {@link #setHovered} to update the hovered state
8861     * of the view when a hover enter or hover exit event is received, if the view
8862     * is enabled and is clickable.  The default implementation also sends hover
8863     * accessibility events.
8864     * </p>
8865     *
8866     * @param event The motion event that describes the hover.
8867     * @return True if the view handled the hover event.
8868     *
8869     * @see #isHovered
8870     * @see #setHovered
8871     * @see #onHoverChanged
8872     */
8873    public boolean onHoverEvent(MotionEvent event) {
8874        // The root view may receive hover (or touch) events that are outside the bounds of
8875        // the window.  This code ensures that we only send accessibility events for
8876        // hovers that are actually within the bounds of the root view.
8877        final int action = event.getActionMasked();
8878        if (!mSendingHoverAccessibilityEvents) {
8879            if ((action == MotionEvent.ACTION_HOVER_ENTER
8880                    || action == MotionEvent.ACTION_HOVER_MOVE)
8881                    && !hasHoveredChild()
8882                    && pointInView(event.getX(), event.getY())) {
8883                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8884                mSendingHoverAccessibilityEvents = true;
8885            }
8886        } else {
8887            if (action == MotionEvent.ACTION_HOVER_EXIT
8888                    || (action == MotionEvent.ACTION_MOVE
8889                            && !pointInView(event.getX(), event.getY()))) {
8890                mSendingHoverAccessibilityEvents = false;
8891                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8892                // If the window does not have input focus we take away accessibility
8893                // focus as soon as the user stop hovering over the view.
8894                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8895                    getViewRootImpl().setAccessibilityFocus(null, null);
8896                }
8897            }
8898        }
8899
8900        if (isHoverable()) {
8901            switch (action) {
8902                case MotionEvent.ACTION_HOVER_ENTER:
8903                    setHovered(true);
8904                    break;
8905                case MotionEvent.ACTION_HOVER_EXIT:
8906                    setHovered(false);
8907                    break;
8908            }
8909
8910            // Dispatch the event to onGenericMotionEvent before returning true.
8911            // This is to provide compatibility with existing applications that
8912            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8913            // break because of the new default handling for hoverable views
8914            // in onHoverEvent.
8915            // Note that onGenericMotionEvent will be called by default when
8916            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8917            dispatchGenericMotionEventInternal(event);
8918            // The event was already handled by calling setHovered(), so always
8919            // return true.
8920            return true;
8921        }
8922
8923        return false;
8924    }
8925
8926    /**
8927     * Returns true if the view should handle {@link #onHoverEvent}
8928     * by calling {@link #setHovered} to change its hovered state.
8929     *
8930     * @return True if the view is hoverable.
8931     */
8932    private boolean isHoverable() {
8933        final int viewFlags = mViewFlags;
8934        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8935            return false;
8936        }
8937
8938        return (viewFlags & CLICKABLE) == CLICKABLE
8939                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8940    }
8941
8942    /**
8943     * Returns true if the view is currently hovered.
8944     *
8945     * @return True if the view is currently hovered.
8946     *
8947     * @see #setHovered
8948     * @see #onHoverChanged
8949     */
8950    @ViewDebug.ExportedProperty
8951    public boolean isHovered() {
8952        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8953    }
8954
8955    /**
8956     * Sets whether the view is currently hovered.
8957     * <p>
8958     * Calling this method also changes the drawable state of the view.  This
8959     * enables the view to react to hover by using different drawable resources
8960     * to change its appearance.
8961     * </p><p>
8962     * The {@link #onHoverChanged} method is called when the hovered state changes.
8963     * </p>
8964     *
8965     * @param hovered True if the view is hovered.
8966     *
8967     * @see #isHovered
8968     * @see #onHoverChanged
8969     */
8970    public void setHovered(boolean hovered) {
8971        if (hovered) {
8972            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8973                mPrivateFlags |= PFLAG_HOVERED;
8974                refreshDrawableState();
8975                onHoverChanged(true);
8976            }
8977        } else {
8978            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8979                mPrivateFlags &= ~PFLAG_HOVERED;
8980                refreshDrawableState();
8981                onHoverChanged(false);
8982            }
8983        }
8984    }
8985
8986    /**
8987     * Implement this method to handle hover state changes.
8988     * <p>
8989     * This method is called whenever the hover state changes as a result of a
8990     * call to {@link #setHovered}.
8991     * </p>
8992     *
8993     * @param hovered The current hover state, as returned by {@link #isHovered}.
8994     *
8995     * @see #isHovered
8996     * @see #setHovered
8997     */
8998    public void onHoverChanged(boolean hovered) {
8999    }
9000
9001    /**
9002     * Implement this method to handle touch screen motion events.
9003     * <p>
9004     * If this method is used to detect click actions, it is recommended that
9005     * the actions be performed by implementing and calling
9006     * {@link #performClick()}. This will ensure consistent system behavior,
9007     * including:
9008     * <ul>
9009     * <li>obeying click sound preferences
9010     * <li>dispatching OnClickListener calls
9011     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9012     * accessibility features are enabled
9013     * </ul>
9014     *
9015     * @param event The motion event.
9016     * @return True if the event was handled, false otherwise.
9017     */
9018    public boolean onTouchEvent(MotionEvent event) {
9019        final int viewFlags = mViewFlags;
9020
9021        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9022            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9023                setPressed(false);
9024            }
9025            // A disabled view that is clickable still consumes the touch
9026            // events, it just doesn't respond to them.
9027            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9028                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9029        }
9030
9031        if (mTouchDelegate != null) {
9032            if (mTouchDelegate.onTouchEvent(event)) {
9033                return true;
9034            }
9035        }
9036
9037        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9038                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9039            switch (event.getAction()) {
9040                case MotionEvent.ACTION_UP:
9041                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9042                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9043                        // take focus if we don't have it already and we should in
9044                        // touch mode.
9045                        boolean focusTaken = false;
9046                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9047                            focusTaken = requestFocus();
9048                        }
9049
9050                        if (prepressed) {
9051                            // The button is being released before we actually
9052                            // showed it as pressed.  Make it show the pressed
9053                            // state now (before scheduling the click) to ensure
9054                            // the user sees it.
9055                            setPressed(true);
9056                       }
9057
9058                        if (!mHasPerformedLongPress) {
9059                            // This is a tap, so remove the longpress check
9060                            removeLongPressCallback();
9061
9062                            // Only perform take click actions if we were in the pressed state
9063                            if (!focusTaken) {
9064                                // Use a Runnable and post this rather than calling
9065                                // performClick directly. This lets other visual state
9066                                // of the view update before click actions start.
9067                                if (mPerformClick == null) {
9068                                    mPerformClick = new PerformClick();
9069                                }
9070                                if (!post(mPerformClick)) {
9071                                    performClick();
9072                                }
9073                            }
9074                        }
9075
9076                        if (mUnsetPressedState == null) {
9077                            mUnsetPressedState = new UnsetPressedState();
9078                        }
9079
9080                        if (prepressed) {
9081                            postDelayed(mUnsetPressedState,
9082                                    ViewConfiguration.getPressedStateDuration());
9083                        } else if (!post(mUnsetPressedState)) {
9084                            // If the post failed, unpress right now
9085                            mUnsetPressedState.run();
9086                        }
9087                        removeTapCallback();
9088                    }
9089                    break;
9090
9091                case MotionEvent.ACTION_DOWN:
9092                    mHasPerformedLongPress = false;
9093
9094                    if (performButtonActionOnTouchDown(event)) {
9095                        break;
9096                    }
9097
9098                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9099                    boolean isInScrollingContainer = isInScrollingContainer();
9100
9101                    // For views inside a scrolling container, delay the pressed feedback for
9102                    // a short period in case this is a scroll.
9103                    if (isInScrollingContainer) {
9104                        mPrivateFlags |= PFLAG_PREPRESSED;
9105                        if (mPendingCheckForTap == null) {
9106                            mPendingCheckForTap = new CheckForTap();
9107                        }
9108                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9109                    } else {
9110                        // Not inside a scrolling container, so show the feedback right away
9111                        setPressed(true);
9112                        checkForLongClick(0);
9113                    }
9114                    break;
9115
9116                case MotionEvent.ACTION_CANCEL:
9117                    setPressed(false);
9118                    removeTapCallback();
9119                    removeLongPressCallback();
9120                    break;
9121
9122                case MotionEvent.ACTION_MOVE:
9123                    final int x = (int) event.getX();
9124                    final int y = (int) event.getY();
9125
9126                    // Be lenient about moving outside of buttons
9127                    if (!pointInView(x, y, mTouchSlop)) {
9128                        // Outside button
9129                        removeTapCallback();
9130                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9131                            // Remove any future long press/tap checks
9132                            removeLongPressCallback();
9133
9134                            setPressed(false);
9135                        }
9136                    }
9137                    break;
9138            }
9139
9140            if (mBackground != null && mBackground.supportsHotspots()) {
9141                manageTouchHotspot(event);
9142            }
9143
9144            return true;
9145        }
9146
9147        return false;
9148    }
9149
9150    private void manageTouchHotspot(MotionEvent event) {
9151        switch (event.getAction()) {
9152            case MotionEvent.ACTION_DOWN:
9153            case MotionEvent.ACTION_POINTER_DOWN: {
9154                final int index = event.getActionIndex();
9155                setPointerHotspot(event, index);
9156            } break;
9157            case MotionEvent.ACTION_MOVE: {
9158                final int count = event.getPointerCount();
9159                for (int index = 0; index < count; index++) {
9160                    setPointerHotspot(event, index);
9161                }
9162            } break;
9163            case MotionEvent.ACTION_POINTER_UP: {
9164                final int actionIndex = event.getActionIndex();
9165                final int pointerId = event.getPointerId(actionIndex);
9166                mBackground.removeHotspot(pointerId);
9167            } break;
9168            case MotionEvent.ACTION_UP:
9169            case MotionEvent.ACTION_CANCEL:
9170                mBackground.clearHotspots();
9171                break;
9172        }
9173    }
9174
9175    private void setPointerHotspot(MotionEvent event, int index) {
9176        final int id = event.getPointerId(index);
9177        final float x = event.getX(index);
9178        final float y = event.getY(index);
9179        mBackground.setHotspot(id, x, y);
9180    }
9181
9182    /**
9183     * @hide
9184     */
9185    public boolean isInScrollingContainer() {
9186        ViewParent p = getParent();
9187        while (p != null && p instanceof ViewGroup) {
9188            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9189                return true;
9190            }
9191            p = p.getParent();
9192        }
9193        return false;
9194    }
9195
9196    /**
9197     * Remove the longpress detection timer.
9198     */
9199    private void removeLongPressCallback() {
9200        if (mPendingCheckForLongPress != null) {
9201          removeCallbacks(mPendingCheckForLongPress);
9202        }
9203    }
9204
9205    /**
9206     * Remove the pending click action
9207     */
9208    private void removePerformClickCallback() {
9209        if (mPerformClick != null) {
9210            removeCallbacks(mPerformClick);
9211        }
9212    }
9213
9214    /**
9215     * Remove the prepress detection timer.
9216     */
9217    private void removeUnsetPressCallback() {
9218        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9219            setPressed(false);
9220            removeCallbacks(mUnsetPressedState);
9221        }
9222    }
9223
9224    /**
9225     * Remove the tap detection timer.
9226     */
9227    private void removeTapCallback() {
9228        if (mPendingCheckForTap != null) {
9229            mPrivateFlags &= ~PFLAG_PREPRESSED;
9230            removeCallbacks(mPendingCheckForTap);
9231        }
9232    }
9233
9234    /**
9235     * Cancels a pending long press.  Your subclass can use this if you
9236     * want the context menu to come up if the user presses and holds
9237     * at the same place, but you don't want it to come up if they press
9238     * and then move around enough to cause scrolling.
9239     */
9240    public void cancelLongPress() {
9241        removeLongPressCallback();
9242
9243        /*
9244         * The prepressed state handled by the tap callback is a display
9245         * construct, but the tap callback will post a long press callback
9246         * less its own timeout. Remove it here.
9247         */
9248        removeTapCallback();
9249    }
9250
9251    /**
9252     * Remove the pending callback for sending a
9253     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9254     */
9255    private void removeSendViewScrolledAccessibilityEventCallback() {
9256        if (mSendViewScrolledAccessibilityEvent != null) {
9257            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9258            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9259        }
9260    }
9261
9262    /**
9263     * Sets the TouchDelegate for this View.
9264     */
9265    public void setTouchDelegate(TouchDelegate delegate) {
9266        mTouchDelegate = delegate;
9267    }
9268
9269    /**
9270     * Gets the TouchDelegate for this View.
9271     */
9272    public TouchDelegate getTouchDelegate() {
9273        return mTouchDelegate;
9274    }
9275
9276    /**
9277     * Set flags controlling behavior of this view.
9278     *
9279     * @param flags Constant indicating the value which should be set
9280     * @param mask Constant indicating the bit range that should be changed
9281     */
9282    void setFlags(int flags, int mask) {
9283        final boolean accessibilityEnabled =
9284                AccessibilityManager.getInstance(mContext).isEnabled();
9285        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9286
9287        int old = mViewFlags;
9288        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9289
9290        int changed = mViewFlags ^ old;
9291        if (changed == 0) {
9292            return;
9293        }
9294        int privateFlags = mPrivateFlags;
9295
9296        /* Check if the FOCUSABLE bit has changed */
9297        if (((changed & FOCUSABLE_MASK) != 0) &&
9298                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9299            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9300                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9301                /* Give up focus if we are no longer focusable */
9302                clearFocus();
9303            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9304                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9305                /*
9306                 * Tell the view system that we are now available to take focus
9307                 * if no one else already has it.
9308                 */
9309                if (mParent != null) mParent.focusableViewAvailable(this);
9310            }
9311        }
9312
9313        final int newVisibility = flags & VISIBILITY_MASK;
9314        if (newVisibility == VISIBLE) {
9315            if ((changed & VISIBILITY_MASK) != 0) {
9316                /*
9317                 * If this view is becoming visible, invalidate it in case it changed while
9318                 * it was not visible. Marking it drawn ensures that the invalidation will
9319                 * go through.
9320                 */
9321                mPrivateFlags |= PFLAG_DRAWN;
9322                invalidate(true);
9323
9324                needGlobalAttributesUpdate(true);
9325
9326                // a view becoming visible is worth notifying the parent
9327                // about in case nothing has focus.  even if this specific view
9328                // isn't focusable, it may contain something that is, so let
9329                // the root view try to give this focus if nothing else does.
9330                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9331                    mParent.focusableViewAvailable(this);
9332                }
9333            }
9334        }
9335
9336        /* Check if the GONE bit has changed */
9337        if ((changed & GONE) != 0) {
9338            needGlobalAttributesUpdate(false);
9339            requestLayout();
9340
9341            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9342                if (hasFocus()) clearFocus();
9343                clearAccessibilityFocus();
9344                destroyDrawingCache();
9345                if (mParent instanceof View) {
9346                    // GONE views noop invalidation, so invalidate the parent
9347                    ((View) mParent).invalidate(true);
9348                }
9349                // Mark the view drawn to ensure that it gets invalidated properly the next
9350                // time it is visible and gets invalidated
9351                mPrivateFlags |= PFLAG_DRAWN;
9352            }
9353            if (mAttachInfo != null) {
9354                mAttachInfo.mViewVisibilityChanged = true;
9355            }
9356        }
9357
9358        /* Check if the VISIBLE bit has changed */
9359        if ((changed & INVISIBLE) != 0) {
9360            needGlobalAttributesUpdate(false);
9361            /*
9362             * If this view is becoming invisible, set the DRAWN flag so that
9363             * the next invalidate() will not be skipped.
9364             */
9365            mPrivateFlags |= PFLAG_DRAWN;
9366
9367            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9368                // root view becoming invisible shouldn't clear focus and accessibility focus
9369                if (getRootView() != this) {
9370                    if (hasFocus()) clearFocus();
9371                    clearAccessibilityFocus();
9372                }
9373            }
9374            if (mAttachInfo != null) {
9375                mAttachInfo.mViewVisibilityChanged = true;
9376            }
9377        }
9378
9379        if ((changed & VISIBILITY_MASK) != 0) {
9380            // If the view is invisible, cleanup its display list to free up resources
9381            if (newVisibility != VISIBLE && mAttachInfo != null) {
9382                cleanupDraw();
9383            }
9384
9385            if (mParent instanceof ViewGroup) {
9386                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9387                        (changed & VISIBILITY_MASK), newVisibility);
9388                ((View) mParent).invalidate(true);
9389            } else if (mParent != null) {
9390                mParent.invalidateChild(this, null);
9391            }
9392            dispatchVisibilityChanged(this, newVisibility);
9393
9394            notifySubtreeAccessibilityStateChangedIfNeeded();
9395        }
9396
9397        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9398            destroyDrawingCache();
9399        }
9400
9401        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9402            destroyDrawingCache();
9403            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9404            invalidateParentCaches();
9405        }
9406
9407        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9408            destroyDrawingCache();
9409            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9410        }
9411
9412        if ((changed & DRAW_MASK) != 0) {
9413            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9414                if (mBackground != null) {
9415                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9416                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9417                } else {
9418                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9419                }
9420            } else {
9421                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9422            }
9423            requestLayout();
9424            invalidate(true);
9425        }
9426
9427        if ((changed & KEEP_SCREEN_ON) != 0) {
9428            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9429                mParent.recomputeViewAttributes(this);
9430            }
9431        }
9432
9433        if (accessibilityEnabled) {
9434            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9435                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9436                if (oldIncludeForAccessibility != includeForAccessibility()) {
9437                    notifySubtreeAccessibilityStateChangedIfNeeded();
9438                } else {
9439                    notifyViewAccessibilityStateChangedIfNeeded(
9440                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9441                }
9442            } else if ((changed & ENABLED_MASK) != 0) {
9443                notifyViewAccessibilityStateChangedIfNeeded(
9444                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9445            }
9446        }
9447    }
9448
9449    /**
9450     * Change the view's z order in the tree, so it's on top of other sibling
9451     * views. This ordering change may affect layout, if the parent container
9452     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9453     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9454     * method should be followed by calls to {@link #requestLayout()} and
9455     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9456     * with the new child ordering.
9457     *
9458     * @see ViewGroup#bringChildToFront(View)
9459     */
9460    public void bringToFront() {
9461        if (mParent != null) {
9462            mParent.bringChildToFront(this);
9463        }
9464    }
9465
9466    /**
9467     * This is called in response to an internal scroll in this view (i.e., the
9468     * view scrolled its own contents). This is typically as a result of
9469     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9470     * called.
9471     *
9472     * @param l Current horizontal scroll origin.
9473     * @param t Current vertical scroll origin.
9474     * @param oldl Previous horizontal scroll origin.
9475     * @param oldt Previous vertical scroll origin.
9476     */
9477    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9478        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9479            postSendViewScrolledAccessibilityEventCallback();
9480        }
9481
9482        mBackgroundSizeChanged = true;
9483
9484        final AttachInfo ai = mAttachInfo;
9485        if (ai != null) {
9486            ai.mViewScrollChanged = true;
9487        }
9488    }
9489
9490    /**
9491     * Interface definition for a callback to be invoked when the layout bounds of a view
9492     * changes due to layout processing.
9493     */
9494    public interface OnLayoutChangeListener {
9495        /**
9496         * Called when the layout bounds of a view changes due to layout processing.
9497         *
9498         * @param v The view whose bounds have changed.
9499         * @param left The new value of the view's left property.
9500         * @param top The new value of the view's top property.
9501         * @param right The new value of the view's right property.
9502         * @param bottom The new value of the view's bottom property.
9503         * @param oldLeft The previous value of the view's left property.
9504         * @param oldTop The previous value of the view's top property.
9505         * @param oldRight The previous value of the view's right property.
9506         * @param oldBottom The previous value of the view's bottom property.
9507         */
9508        void onLayoutChange(View v, int left, int top, int right, int bottom,
9509            int oldLeft, int oldTop, int oldRight, int oldBottom);
9510    }
9511
9512    /**
9513     * This is called during layout when the size of this view has changed. If
9514     * you were just added to the view hierarchy, you're called with the old
9515     * values of 0.
9516     *
9517     * @param w Current width of this view.
9518     * @param h Current height of this view.
9519     * @param oldw Old width of this view.
9520     * @param oldh Old height of this view.
9521     */
9522    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9523    }
9524
9525    /**
9526     * Called by draw to draw the child views. This may be overridden
9527     * by derived classes to gain control just before its children are drawn
9528     * (but after its own view has been drawn).
9529     * @param canvas the canvas on which to draw the view
9530     */
9531    protected void dispatchDraw(Canvas canvas) {
9532
9533    }
9534
9535    /**
9536     * Gets the parent of this view. Note that the parent is a
9537     * ViewParent and not necessarily a View.
9538     *
9539     * @return Parent of this view.
9540     */
9541    public final ViewParent getParent() {
9542        return mParent;
9543    }
9544
9545    /**
9546     * Set the horizontal scrolled position of your view. This will cause a call to
9547     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9548     * invalidated.
9549     * @param value the x position to scroll to
9550     */
9551    public void setScrollX(int value) {
9552        scrollTo(value, mScrollY);
9553    }
9554
9555    /**
9556     * Set the vertical scrolled position of your view. This will cause a call to
9557     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9558     * invalidated.
9559     * @param value the y position to scroll to
9560     */
9561    public void setScrollY(int value) {
9562        scrollTo(mScrollX, value);
9563    }
9564
9565    /**
9566     * Return the scrolled left position of this view. This is the left edge of
9567     * the displayed part of your view. You do not need to draw any pixels
9568     * farther left, since those are outside of the frame of your view on
9569     * screen.
9570     *
9571     * @return The left edge of the displayed part of your view, in pixels.
9572     */
9573    public final int getScrollX() {
9574        return mScrollX;
9575    }
9576
9577    /**
9578     * Return the scrolled top position of this view. This is the top edge of
9579     * the displayed part of your view. You do not need to draw any pixels above
9580     * it, since those are outside of the frame of your view on screen.
9581     *
9582     * @return The top edge of the displayed part of your view, in pixels.
9583     */
9584    public final int getScrollY() {
9585        return mScrollY;
9586    }
9587
9588    /**
9589     * Return the width of the your view.
9590     *
9591     * @return The width of your view, in pixels.
9592     */
9593    @ViewDebug.ExportedProperty(category = "layout")
9594    public final int getWidth() {
9595        return mRight - mLeft;
9596    }
9597
9598    /**
9599     * Return the height of your view.
9600     *
9601     * @return The height of your view, in pixels.
9602     */
9603    @ViewDebug.ExportedProperty(category = "layout")
9604    public final int getHeight() {
9605        return mBottom - mTop;
9606    }
9607
9608    /**
9609     * Return the visible drawing bounds of your view. Fills in the output
9610     * rectangle with the values from getScrollX(), getScrollY(),
9611     * getWidth(), and getHeight(). These bounds do not account for any
9612     * transformation properties currently set on the view, such as
9613     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9614     *
9615     * @param outRect The (scrolled) drawing bounds of the view.
9616     */
9617    public void getDrawingRect(Rect outRect) {
9618        outRect.left = mScrollX;
9619        outRect.top = mScrollY;
9620        outRect.right = mScrollX + (mRight - mLeft);
9621        outRect.bottom = mScrollY + (mBottom - mTop);
9622    }
9623
9624    /**
9625     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9626     * raw width component (that is the result is masked by
9627     * {@link #MEASURED_SIZE_MASK}).
9628     *
9629     * @return The raw measured width of this view.
9630     */
9631    public final int getMeasuredWidth() {
9632        return mMeasuredWidth & MEASURED_SIZE_MASK;
9633    }
9634
9635    /**
9636     * Return the full width measurement information for this view as computed
9637     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9638     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9639     * This should be used during measurement and layout calculations only. Use
9640     * {@link #getWidth()} to see how wide a view is after layout.
9641     *
9642     * @return The measured width of this view as a bit mask.
9643     */
9644    public final int getMeasuredWidthAndState() {
9645        return mMeasuredWidth;
9646    }
9647
9648    /**
9649     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9650     * raw width component (that is the result is masked by
9651     * {@link #MEASURED_SIZE_MASK}).
9652     *
9653     * @return The raw measured height of this view.
9654     */
9655    public final int getMeasuredHeight() {
9656        return mMeasuredHeight & MEASURED_SIZE_MASK;
9657    }
9658
9659    /**
9660     * Return the full height measurement information for this view as computed
9661     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9662     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9663     * This should be used during measurement and layout calculations only. Use
9664     * {@link #getHeight()} to see how wide a view is after layout.
9665     *
9666     * @return The measured width of this view as a bit mask.
9667     */
9668    public final int getMeasuredHeightAndState() {
9669        return mMeasuredHeight;
9670    }
9671
9672    /**
9673     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9674     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9675     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9676     * and the height component is at the shifted bits
9677     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9678     */
9679    public final int getMeasuredState() {
9680        return (mMeasuredWidth&MEASURED_STATE_MASK)
9681                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9682                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9683    }
9684
9685    /**
9686     * The transform matrix of this view, which is calculated based on the current
9687     * roation, scale, and pivot properties.
9688     *
9689     * @see #getRotation()
9690     * @see #getScaleX()
9691     * @see #getScaleY()
9692     * @see #getPivotX()
9693     * @see #getPivotY()
9694     * @return The current transform matrix for the view
9695     */
9696    public Matrix getMatrix() {
9697        if (mTransformationInfo != null) {
9698            updateMatrix();
9699            return mTransformationInfo.mMatrix;
9700        }
9701        return Matrix.IDENTITY_MATRIX;
9702    }
9703
9704    /**
9705     * Utility function to determine if the value is far enough away from zero to be
9706     * considered non-zero.
9707     * @param value A floating point value to check for zero-ness
9708     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9709     */
9710    private static boolean nonzero(float value) {
9711        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9712    }
9713
9714    /**
9715     * Returns true if the transform matrix is the identity matrix.
9716     * Recomputes the matrix if necessary.
9717     *
9718     * @return True if the transform matrix is the identity matrix, false otherwise.
9719     */
9720    final boolean hasIdentityMatrix() {
9721        if (mTransformationInfo != null) {
9722            updateMatrix();
9723            return mTransformationInfo.mMatrixIsIdentity;
9724        }
9725        return true;
9726    }
9727
9728    void ensureTransformationInfo() {
9729        if (mTransformationInfo == null) {
9730            mTransformationInfo = new TransformationInfo();
9731        }
9732    }
9733
9734    /**
9735     * Recomputes the transform matrix if necessary.
9736     */
9737    private void updateMatrix() {
9738        final TransformationInfo info = mTransformationInfo;
9739        if (info == null) {
9740            return;
9741        }
9742        if (info.mMatrixDirty) {
9743            // transform-related properties have changed since the last time someone
9744            // asked for the matrix; recalculate it with the current values
9745
9746            // Figure out if we need to update the pivot point
9747            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9748                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9749                    info.mPrevWidth = mRight - mLeft;
9750                    info.mPrevHeight = mBottom - mTop;
9751                    info.mPivotX = info.mPrevWidth / 2f;
9752                    info.mPivotY = info.mPrevHeight / 2f;
9753                }
9754            }
9755            info.mMatrix.reset();
9756            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9757                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9758                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9759                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9760            } else {
9761                if (info.mCamera == null) {
9762                    info.mCamera = new Camera();
9763                    info.matrix3D = new Matrix();
9764                }
9765                info.mCamera.save();
9766                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9767                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9768                info.mCamera.getMatrix(info.matrix3D);
9769                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9770                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9771                        info.mPivotY + info.mTranslationY);
9772                info.mMatrix.postConcat(info.matrix3D);
9773                info.mCamera.restore();
9774            }
9775            info.mMatrixDirty = false;
9776            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9777            info.mInverseMatrixDirty = true;
9778        }
9779    }
9780
9781   /**
9782     * Utility method to retrieve the inverse of the current mMatrix property.
9783     * We cache the matrix to avoid recalculating it when transform properties
9784     * have not changed.
9785     *
9786     * @return The inverse of the current matrix of this view.
9787     */
9788    final Matrix getInverseMatrix() {
9789        final TransformationInfo info = mTransformationInfo;
9790        if (info != null) {
9791            updateMatrix();
9792            if (info.mInverseMatrixDirty) {
9793                if (info.mInverseMatrix == null) {
9794                    info.mInverseMatrix = new Matrix();
9795                }
9796                info.mMatrix.invert(info.mInverseMatrix);
9797                info.mInverseMatrixDirty = false;
9798            }
9799            return info.mInverseMatrix;
9800        }
9801        return Matrix.IDENTITY_MATRIX;
9802    }
9803
9804    /**
9805     * Gets the distance along the Z axis from the camera to this view.
9806     *
9807     * @see #setCameraDistance(float)
9808     *
9809     * @return The distance along the Z axis.
9810     */
9811    public float getCameraDistance() {
9812        ensureTransformationInfo();
9813        final float dpi = mResources.getDisplayMetrics().densityDpi;
9814        final TransformationInfo info = mTransformationInfo;
9815        if (info.mCamera == null) {
9816            info.mCamera = new Camera();
9817            info.matrix3D = new Matrix();
9818        }
9819        return -(info.mCamera.getLocationZ() * dpi);
9820    }
9821
9822    /**
9823     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9824     * views are drawn) from the camera to this view. The camera's distance
9825     * affects 3D transformations, for instance rotations around the X and Y
9826     * axis. If the rotationX or rotationY properties are changed and this view is
9827     * large (more than half the size of the screen), it is recommended to always
9828     * use a camera distance that's greater than the height (X axis rotation) or
9829     * the width (Y axis rotation) of this view.</p>
9830     *
9831     * <p>The distance of the camera from the view plane can have an affect on the
9832     * perspective distortion of the view when it is rotated around the x or y axis.
9833     * For example, a large distance will result in a large viewing angle, and there
9834     * will not be much perspective distortion of the view as it rotates. A short
9835     * distance may cause much more perspective distortion upon rotation, and can
9836     * also result in some drawing artifacts if the rotated view ends up partially
9837     * behind the camera (which is why the recommendation is to use a distance at
9838     * least as far as the size of the view, if the view is to be rotated.)</p>
9839     *
9840     * <p>The distance is expressed in "depth pixels." The default distance depends
9841     * on the screen density. For instance, on a medium density display, the
9842     * default distance is 1280. On a high density display, the default distance
9843     * is 1920.</p>
9844     *
9845     * <p>If you want to specify a distance that leads to visually consistent
9846     * results across various densities, use the following formula:</p>
9847     * <pre>
9848     * float scale = context.getResources().getDisplayMetrics().density;
9849     * view.setCameraDistance(distance * scale);
9850     * </pre>
9851     *
9852     * <p>The density scale factor of a high density display is 1.5,
9853     * and 1920 = 1280 * 1.5.</p>
9854     *
9855     * @param distance The distance in "depth pixels", if negative the opposite
9856     *        value is used
9857     *
9858     * @see #setRotationX(float)
9859     * @see #setRotationY(float)
9860     */
9861    public void setCameraDistance(float distance) {
9862        invalidateViewProperty(true, false);
9863
9864        ensureTransformationInfo();
9865        final float dpi = mResources.getDisplayMetrics().densityDpi;
9866        final TransformationInfo info = mTransformationInfo;
9867        if (info.mCamera == null) {
9868            info.mCamera = new Camera();
9869            info.matrix3D = new Matrix();
9870        }
9871
9872        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9873        info.mMatrixDirty = true;
9874
9875        invalidateViewProperty(false, false);
9876        if (mDisplayList != null) {
9877            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9878        }
9879        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9880            // View was rejected last time it was drawn by its parent; this may have changed
9881            invalidateParentIfNeeded();
9882        }
9883    }
9884
9885    /**
9886     * The degrees that the view is rotated around the pivot point.
9887     *
9888     * @see #setRotation(float)
9889     * @see #getPivotX()
9890     * @see #getPivotY()
9891     *
9892     * @return The degrees of rotation.
9893     */
9894    @ViewDebug.ExportedProperty(category = "drawing")
9895    public float getRotation() {
9896        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9897    }
9898
9899    /**
9900     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9901     * result in clockwise rotation.
9902     *
9903     * @param rotation The degrees of rotation.
9904     *
9905     * @see #getRotation()
9906     * @see #getPivotX()
9907     * @see #getPivotY()
9908     * @see #setRotationX(float)
9909     * @see #setRotationY(float)
9910     *
9911     * @attr ref android.R.styleable#View_rotation
9912     */
9913    public void setRotation(float rotation) {
9914        ensureTransformationInfo();
9915        final TransformationInfo info = mTransformationInfo;
9916        if (info.mRotation != rotation) {
9917            // Double-invalidation is necessary to capture view's old and new areas
9918            invalidateViewProperty(true, false);
9919            info.mRotation = rotation;
9920            info.mMatrixDirty = true;
9921            invalidateViewProperty(false, true);
9922            if (mDisplayList != null) {
9923                mDisplayList.setRotation(rotation);
9924            }
9925            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9926                // View was rejected last time it was drawn by its parent; this may have changed
9927                invalidateParentIfNeeded();
9928            }
9929        }
9930    }
9931
9932    /**
9933     * The degrees that the view is rotated around the vertical axis through the pivot point.
9934     *
9935     * @see #getPivotX()
9936     * @see #getPivotY()
9937     * @see #setRotationY(float)
9938     *
9939     * @return The degrees of Y rotation.
9940     */
9941    @ViewDebug.ExportedProperty(category = "drawing")
9942    public float getRotationY() {
9943        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9944    }
9945
9946    /**
9947     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9948     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9949     * down the y axis.
9950     *
9951     * When rotating large views, it is recommended to adjust the camera distance
9952     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9953     *
9954     * @param rotationY The degrees of Y rotation.
9955     *
9956     * @see #getRotationY()
9957     * @see #getPivotX()
9958     * @see #getPivotY()
9959     * @see #setRotation(float)
9960     * @see #setRotationX(float)
9961     * @see #setCameraDistance(float)
9962     *
9963     * @attr ref android.R.styleable#View_rotationY
9964     */
9965    public void setRotationY(float rotationY) {
9966        ensureTransformationInfo();
9967        final TransformationInfo info = mTransformationInfo;
9968        if (info.mRotationY != rotationY) {
9969            invalidateViewProperty(true, false);
9970            info.mRotationY = rotationY;
9971            info.mMatrixDirty = true;
9972            invalidateViewProperty(false, true);
9973            if (mDisplayList != null) {
9974                mDisplayList.setRotationY(rotationY);
9975            }
9976            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9977                // View was rejected last time it was drawn by its parent; this may have changed
9978                invalidateParentIfNeeded();
9979            }
9980        }
9981    }
9982
9983    /**
9984     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9985     *
9986     * @see #getPivotX()
9987     * @see #getPivotY()
9988     * @see #setRotationX(float)
9989     *
9990     * @return The degrees of X rotation.
9991     */
9992    @ViewDebug.ExportedProperty(category = "drawing")
9993    public float getRotationX() {
9994        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9995    }
9996
9997    /**
9998     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9999     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10000     * x axis.
10001     *
10002     * When rotating large views, it is recommended to adjust the camera distance
10003     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10004     *
10005     * @param rotationX The degrees of X rotation.
10006     *
10007     * @see #getRotationX()
10008     * @see #getPivotX()
10009     * @see #getPivotY()
10010     * @see #setRotation(float)
10011     * @see #setRotationY(float)
10012     * @see #setCameraDistance(float)
10013     *
10014     * @attr ref android.R.styleable#View_rotationX
10015     */
10016    public void setRotationX(float rotationX) {
10017        ensureTransformationInfo();
10018        final TransformationInfo info = mTransformationInfo;
10019        if (info.mRotationX != rotationX) {
10020            invalidateViewProperty(true, false);
10021            info.mRotationX = rotationX;
10022            info.mMatrixDirty = true;
10023            invalidateViewProperty(false, true);
10024            if (mDisplayList != null) {
10025                mDisplayList.setRotationX(rotationX);
10026            }
10027            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10028                // View was rejected last time it was drawn by its parent; this may have changed
10029                invalidateParentIfNeeded();
10030            }
10031        }
10032    }
10033
10034    /**
10035     * The amount that the view is scaled in x around the pivot point, as a proportion of
10036     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10037     *
10038     * <p>By default, this is 1.0f.
10039     *
10040     * @see #getPivotX()
10041     * @see #getPivotY()
10042     * @return The scaling factor.
10043     */
10044    @ViewDebug.ExportedProperty(category = "drawing")
10045    public float getScaleX() {
10046        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
10047    }
10048
10049    /**
10050     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10051     * the view's unscaled width. A value of 1 means that no scaling is applied.
10052     *
10053     * @param scaleX The scaling factor.
10054     * @see #getPivotX()
10055     * @see #getPivotY()
10056     *
10057     * @attr ref android.R.styleable#View_scaleX
10058     */
10059    public void setScaleX(float scaleX) {
10060        ensureTransformationInfo();
10061        final TransformationInfo info = mTransformationInfo;
10062        if (info.mScaleX != scaleX) {
10063            invalidateViewProperty(true, false);
10064            info.mScaleX = scaleX;
10065            info.mMatrixDirty = true;
10066            invalidateViewProperty(false, true);
10067            if (mDisplayList != null) {
10068                mDisplayList.setScaleX(scaleX);
10069            }
10070            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10071                // View was rejected last time it was drawn by its parent; this may have changed
10072                invalidateParentIfNeeded();
10073            }
10074        }
10075    }
10076
10077    /**
10078     * The amount that the view is scaled in y around the pivot point, as a proportion of
10079     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10080     *
10081     * <p>By default, this is 1.0f.
10082     *
10083     * @see #getPivotX()
10084     * @see #getPivotY()
10085     * @return The scaling factor.
10086     */
10087    @ViewDebug.ExportedProperty(category = "drawing")
10088    public float getScaleY() {
10089        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
10090    }
10091
10092    /**
10093     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10094     * the view's unscaled width. A value of 1 means that no scaling is applied.
10095     *
10096     * @param scaleY The scaling factor.
10097     * @see #getPivotX()
10098     * @see #getPivotY()
10099     *
10100     * @attr ref android.R.styleable#View_scaleY
10101     */
10102    public void setScaleY(float scaleY) {
10103        ensureTransformationInfo();
10104        final TransformationInfo info = mTransformationInfo;
10105        if (info.mScaleY != scaleY) {
10106            invalidateViewProperty(true, false);
10107            info.mScaleY = scaleY;
10108            info.mMatrixDirty = true;
10109            invalidateViewProperty(false, true);
10110            if (mDisplayList != null) {
10111                mDisplayList.setScaleY(scaleY);
10112            }
10113            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10114                // View was rejected last time it was drawn by its parent; this may have changed
10115                invalidateParentIfNeeded();
10116            }
10117        }
10118    }
10119
10120    /**
10121     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10122     * and {@link #setScaleX(float) scaled}.
10123     *
10124     * @see #getRotation()
10125     * @see #getScaleX()
10126     * @see #getScaleY()
10127     * @see #getPivotY()
10128     * @return The x location of the pivot point.
10129     *
10130     * @attr ref android.R.styleable#View_transformPivotX
10131     */
10132    @ViewDebug.ExportedProperty(category = "drawing")
10133    public float getPivotX() {
10134        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
10135    }
10136
10137    /**
10138     * Sets the x location of the point around which the view is
10139     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10140     * By default, the pivot point is centered on the object.
10141     * Setting this property disables this behavior and causes the view to use only the
10142     * explicitly set pivotX and pivotY values.
10143     *
10144     * @param pivotX The x location of the pivot point.
10145     * @see #getRotation()
10146     * @see #getScaleX()
10147     * @see #getScaleY()
10148     * @see #getPivotY()
10149     *
10150     * @attr ref android.R.styleable#View_transformPivotX
10151     */
10152    public void setPivotX(float pivotX) {
10153        ensureTransformationInfo();
10154        final TransformationInfo info = mTransformationInfo;
10155        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10156                PFLAG_PIVOT_EXPLICITLY_SET;
10157        if (info.mPivotX != pivotX || !pivotSet) {
10158            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10159            invalidateViewProperty(true, false);
10160            info.mPivotX = pivotX;
10161            info.mMatrixDirty = true;
10162            invalidateViewProperty(false, true);
10163            if (mDisplayList != null) {
10164                mDisplayList.setPivotX(pivotX);
10165            }
10166            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10167                // View was rejected last time it was drawn by its parent; this may have changed
10168                invalidateParentIfNeeded();
10169            }
10170        }
10171    }
10172
10173    /**
10174     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10175     * and {@link #setScaleY(float) scaled}.
10176     *
10177     * @see #getRotation()
10178     * @see #getScaleX()
10179     * @see #getScaleY()
10180     * @see #getPivotY()
10181     * @return The y location of the pivot point.
10182     *
10183     * @attr ref android.R.styleable#View_transformPivotY
10184     */
10185    @ViewDebug.ExportedProperty(category = "drawing")
10186    public float getPivotY() {
10187        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
10188    }
10189
10190    /**
10191     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10192     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10193     * Setting this property disables this behavior and causes the view to use only the
10194     * explicitly set pivotX and pivotY values.
10195     *
10196     * @param pivotY The y location of the pivot point.
10197     * @see #getRotation()
10198     * @see #getScaleX()
10199     * @see #getScaleY()
10200     * @see #getPivotY()
10201     *
10202     * @attr ref android.R.styleable#View_transformPivotY
10203     */
10204    public void setPivotY(float pivotY) {
10205        ensureTransformationInfo();
10206        final TransformationInfo info = mTransformationInfo;
10207        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10208                PFLAG_PIVOT_EXPLICITLY_SET;
10209        if (info.mPivotY != pivotY || !pivotSet) {
10210            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10211            invalidateViewProperty(true, false);
10212            info.mPivotY = pivotY;
10213            info.mMatrixDirty = true;
10214            invalidateViewProperty(false, true);
10215            if (mDisplayList != null) {
10216                mDisplayList.setPivotY(pivotY);
10217            }
10218            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10219                // View was rejected last time it was drawn by its parent; this may have changed
10220                invalidateParentIfNeeded();
10221            }
10222        }
10223    }
10224
10225    /**
10226     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10227     * completely transparent and 1 means the view is completely opaque.
10228     *
10229     * <p>By default this is 1.0f.
10230     * @return The opacity of the view.
10231     */
10232    @ViewDebug.ExportedProperty(category = "drawing")
10233    public float getAlpha() {
10234        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10235    }
10236
10237    /**
10238     * Returns whether this View has content which overlaps.
10239     *
10240     * <p>This function, intended to be overridden by specific View types, is an optimization when
10241     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10242     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10243     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10244     * directly. An example of overlapping rendering is a TextView with a background image, such as
10245     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10246     * ImageView with only the foreground image. The default implementation returns true; subclasses
10247     * should override if they have cases which can be optimized.</p>
10248     *
10249     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10250     * necessitates that a View return true if it uses the methods internally without passing the
10251     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10252     *
10253     * @return true if the content in this view might overlap, false otherwise.
10254     */
10255    public boolean hasOverlappingRendering() {
10256        return true;
10257    }
10258
10259    /**
10260     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10261     * completely transparent and 1 means the view is completely opaque.</p>
10262     *
10263     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10264     * performance implications, especially for large views. It is best to use the alpha property
10265     * sparingly and transiently, as in the case of fading animations.</p>
10266     *
10267     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10268     * strongly recommended for performance reasons to either override
10269     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10270     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10271     *
10272     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10273     * responsible for applying the opacity itself.</p>
10274     *
10275     * <p>Note that if the view is backed by a
10276     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10277     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10278     * 1.0 will supercede the alpha of the layer paint.</p>
10279     *
10280     * @param alpha The opacity of the view.
10281     *
10282     * @see #hasOverlappingRendering()
10283     * @see #setLayerType(int, android.graphics.Paint)
10284     *
10285     * @attr ref android.R.styleable#View_alpha
10286     */
10287    public void setAlpha(float alpha) {
10288        ensureTransformationInfo();
10289        if (mTransformationInfo.mAlpha != alpha) {
10290            mTransformationInfo.mAlpha = alpha;
10291            if (onSetAlpha((int) (alpha * 255))) {
10292                mPrivateFlags |= PFLAG_ALPHA_SET;
10293                // subclass is handling alpha - don't optimize rendering cache invalidation
10294                invalidateParentCaches();
10295                invalidate(true);
10296            } else {
10297                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10298                invalidateViewProperty(true, false);
10299                if (mDisplayList != null) {
10300                    mDisplayList.setAlpha(getFinalAlpha());
10301                }
10302            }
10303        }
10304    }
10305
10306    /**
10307     * Faster version of setAlpha() which performs the same steps except there are
10308     * no calls to invalidate(). The caller of this function should perform proper invalidation
10309     * on the parent and this object. The return value indicates whether the subclass handles
10310     * alpha (the return value for onSetAlpha()).
10311     *
10312     * @param alpha The new value for the alpha property
10313     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10314     *         the new value for the alpha property is different from the old value
10315     */
10316    boolean setAlphaNoInvalidation(float alpha) {
10317        ensureTransformationInfo();
10318        if (mTransformationInfo.mAlpha != alpha) {
10319            mTransformationInfo.mAlpha = alpha;
10320            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10321            if (subclassHandlesAlpha) {
10322                mPrivateFlags |= PFLAG_ALPHA_SET;
10323                return true;
10324            } else {
10325                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10326                if (mDisplayList != null) {
10327                    mDisplayList.setAlpha(getFinalAlpha());
10328                }
10329            }
10330        }
10331        return false;
10332    }
10333
10334    /**
10335     * This property is hidden and intended only for use by the Fade transition, which
10336     * animates it to produce a visual translucency that does not side-effect (or get
10337     * affected by) the real alpha property. This value is composited with the other
10338     * alpha value (and the AlphaAnimation value, when that is present) to produce
10339     * a final visual translucency result, which is what is passed into the DisplayList.
10340     *
10341     * @hide
10342     */
10343    public void setTransitionAlpha(float alpha) {
10344        ensureTransformationInfo();
10345        if (mTransformationInfo.mTransitionAlpha != alpha) {
10346            mTransformationInfo.mTransitionAlpha = alpha;
10347            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10348            invalidateViewProperty(true, false);
10349            if (mDisplayList != null) {
10350                mDisplayList.setAlpha(getFinalAlpha());
10351            }
10352        }
10353    }
10354
10355    /**
10356     * Calculates the visual alpha of this view, which is a combination of the actual
10357     * alpha value and the transitionAlpha value (if set).
10358     */
10359    private float getFinalAlpha() {
10360        if (mTransformationInfo != null) {
10361            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10362        }
10363        return 1;
10364    }
10365
10366    /**
10367     * This property is hidden and intended only for use by the Fade transition, which
10368     * animates it to produce a visual translucency that does not side-effect (or get
10369     * affected by) the real alpha property. This value is composited with the other
10370     * alpha value (and the AlphaAnimation value, when that is present) to produce
10371     * a final visual translucency result, which is what is passed into the DisplayList.
10372     *
10373     * @hide
10374     */
10375    public float getTransitionAlpha() {
10376        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10377    }
10378
10379    /**
10380     * Top position of this view relative to its parent.
10381     *
10382     * @return The top of this view, in pixels.
10383     */
10384    @ViewDebug.CapturedViewProperty
10385    public final int getTop() {
10386        return mTop;
10387    }
10388
10389    /**
10390     * Sets the top position of this view relative to its parent. This method is meant to be called
10391     * by the layout system and should not generally be called otherwise, because the property
10392     * may be changed at any time by the layout.
10393     *
10394     * @param top The top of this view, in pixels.
10395     */
10396    public final void setTop(int top) {
10397        if (top != mTop) {
10398            updateMatrix();
10399            final boolean matrixIsIdentity = mTransformationInfo == null
10400                    || mTransformationInfo.mMatrixIsIdentity;
10401            if (matrixIsIdentity) {
10402                if (mAttachInfo != null) {
10403                    int minTop;
10404                    int yLoc;
10405                    if (top < mTop) {
10406                        minTop = top;
10407                        yLoc = top - mTop;
10408                    } else {
10409                        minTop = mTop;
10410                        yLoc = 0;
10411                    }
10412                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10413                }
10414            } else {
10415                // Double-invalidation is necessary to capture view's old and new areas
10416                invalidate(true);
10417            }
10418
10419            int width = mRight - mLeft;
10420            int oldHeight = mBottom - mTop;
10421
10422            mTop = top;
10423            if (mDisplayList != null) {
10424                mDisplayList.setTop(mTop);
10425            }
10426
10427            sizeChange(width, mBottom - mTop, width, oldHeight);
10428
10429            if (!matrixIsIdentity) {
10430                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10431                    // A change in dimension means an auto-centered pivot point changes, too
10432                    mTransformationInfo.mMatrixDirty = true;
10433                }
10434                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10435                invalidate(true);
10436            }
10437            mBackgroundSizeChanged = true;
10438            invalidateParentIfNeeded();
10439            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10440                // View was rejected last time it was drawn by its parent; this may have changed
10441                invalidateParentIfNeeded();
10442            }
10443        }
10444    }
10445
10446    /**
10447     * Bottom position of this view relative to its parent.
10448     *
10449     * @return The bottom of this view, in pixels.
10450     */
10451    @ViewDebug.CapturedViewProperty
10452    public final int getBottom() {
10453        return mBottom;
10454    }
10455
10456    /**
10457     * True if this view has changed since the last time being drawn.
10458     *
10459     * @return The dirty state of this view.
10460     */
10461    public boolean isDirty() {
10462        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10463    }
10464
10465    /**
10466     * Sets the bottom position of this view relative to its parent. This method is meant to be
10467     * called by the layout system and should not generally be called otherwise, because the
10468     * property may be changed at any time by the layout.
10469     *
10470     * @param bottom The bottom of this view, in pixels.
10471     */
10472    public final void setBottom(int bottom) {
10473        if (bottom != mBottom) {
10474            updateMatrix();
10475            final boolean matrixIsIdentity = mTransformationInfo == null
10476                    || mTransformationInfo.mMatrixIsIdentity;
10477            if (matrixIsIdentity) {
10478                if (mAttachInfo != null) {
10479                    int maxBottom;
10480                    if (bottom < mBottom) {
10481                        maxBottom = mBottom;
10482                    } else {
10483                        maxBottom = bottom;
10484                    }
10485                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10486                }
10487            } else {
10488                // Double-invalidation is necessary to capture view's old and new areas
10489                invalidate(true);
10490            }
10491
10492            int width = mRight - mLeft;
10493            int oldHeight = mBottom - mTop;
10494
10495            mBottom = bottom;
10496            if (mDisplayList != null) {
10497                mDisplayList.setBottom(mBottom);
10498            }
10499
10500            sizeChange(width, mBottom - mTop, width, oldHeight);
10501
10502            if (!matrixIsIdentity) {
10503                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10504                    // A change in dimension means an auto-centered pivot point changes, too
10505                    mTransformationInfo.mMatrixDirty = true;
10506                }
10507                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10508                invalidate(true);
10509            }
10510            mBackgroundSizeChanged = true;
10511            invalidateParentIfNeeded();
10512            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10513                // View was rejected last time it was drawn by its parent; this may have changed
10514                invalidateParentIfNeeded();
10515            }
10516        }
10517    }
10518
10519    /**
10520     * Left position of this view relative to its parent.
10521     *
10522     * @return The left edge of this view, in pixels.
10523     */
10524    @ViewDebug.CapturedViewProperty
10525    public final int getLeft() {
10526        return mLeft;
10527    }
10528
10529    /**
10530     * Sets the left position of this view relative to its parent. This method is meant to be called
10531     * by the layout system and should not generally be called otherwise, because the property
10532     * may be changed at any time by the layout.
10533     *
10534     * @param left The left of this view, in pixels.
10535     */
10536    public final void setLeft(int left) {
10537        if (left != mLeft) {
10538            updateMatrix();
10539            final boolean matrixIsIdentity = mTransformationInfo == null
10540                    || mTransformationInfo.mMatrixIsIdentity;
10541            if (matrixIsIdentity) {
10542                if (mAttachInfo != null) {
10543                    int minLeft;
10544                    int xLoc;
10545                    if (left < mLeft) {
10546                        minLeft = left;
10547                        xLoc = left - mLeft;
10548                    } else {
10549                        minLeft = mLeft;
10550                        xLoc = 0;
10551                    }
10552                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10553                }
10554            } else {
10555                // Double-invalidation is necessary to capture view's old and new areas
10556                invalidate(true);
10557            }
10558
10559            int oldWidth = mRight - mLeft;
10560            int height = mBottom - mTop;
10561
10562            mLeft = left;
10563            if (mDisplayList != null) {
10564                mDisplayList.setLeft(left);
10565            }
10566
10567            sizeChange(mRight - mLeft, height, oldWidth, height);
10568
10569            if (!matrixIsIdentity) {
10570                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10571                    // A change in dimension means an auto-centered pivot point changes, too
10572                    mTransformationInfo.mMatrixDirty = true;
10573                }
10574                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10575                invalidate(true);
10576            }
10577            mBackgroundSizeChanged = true;
10578            invalidateParentIfNeeded();
10579            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10580                // View was rejected last time it was drawn by its parent; this may have changed
10581                invalidateParentIfNeeded();
10582            }
10583        }
10584    }
10585
10586    /**
10587     * Right position of this view relative to its parent.
10588     *
10589     * @return The right edge of this view, in pixels.
10590     */
10591    @ViewDebug.CapturedViewProperty
10592    public final int getRight() {
10593        return mRight;
10594    }
10595
10596    /**
10597     * Sets the right position of this view relative to its parent. This method is meant to be called
10598     * by the layout system and should not generally be called otherwise, because the property
10599     * may be changed at any time by the layout.
10600     *
10601     * @param right The right of this view, in pixels.
10602     */
10603    public final void setRight(int right) {
10604        if (right != mRight) {
10605            updateMatrix();
10606            final boolean matrixIsIdentity = mTransformationInfo == null
10607                    || mTransformationInfo.mMatrixIsIdentity;
10608            if (matrixIsIdentity) {
10609                if (mAttachInfo != null) {
10610                    int maxRight;
10611                    if (right < mRight) {
10612                        maxRight = mRight;
10613                    } else {
10614                        maxRight = right;
10615                    }
10616                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10617                }
10618            } else {
10619                // Double-invalidation is necessary to capture view's old and new areas
10620                invalidate(true);
10621            }
10622
10623            int oldWidth = mRight - mLeft;
10624            int height = mBottom - mTop;
10625
10626            mRight = right;
10627            if (mDisplayList != null) {
10628                mDisplayList.setRight(mRight);
10629            }
10630
10631            sizeChange(mRight - mLeft, height, oldWidth, height);
10632
10633            if (!matrixIsIdentity) {
10634                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10635                    // A change in dimension means an auto-centered pivot point changes, too
10636                    mTransformationInfo.mMatrixDirty = true;
10637                }
10638                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10639                invalidate(true);
10640            }
10641            mBackgroundSizeChanged = true;
10642            invalidateParentIfNeeded();
10643            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10644                // View was rejected last time it was drawn by its parent; this may have changed
10645                invalidateParentIfNeeded();
10646            }
10647        }
10648    }
10649
10650    /**
10651     * The visual x position of this view, in pixels. This is equivalent to the
10652     * {@link #setTranslationX(float) translationX} property plus the current
10653     * {@link #getLeft() left} property.
10654     *
10655     * @return The visual x position of this view, in pixels.
10656     */
10657    @ViewDebug.ExportedProperty(category = "drawing")
10658    public float getX() {
10659        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10660    }
10661
10662    /**
10663     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10664     * {@link #setTranslationX(float) translationX} property to be the difference between
10665     * the x value passed in and the current {@link #getLeft() left} property.
10666     *
10667     * @param x The visual x position of this view, in pixels.
10668     */
10669    public void setX(float x) {
10670        setTranslationX(x - mLeft);
10671    }
10672
10673    /**
10674     * The visual y position of this view, in pixels. This is equivalent to the
10675     * {@link #setTranslationY(float) translationY} property plus the current
10676     * {@link #getTop() top} property.
10677     *
10678     * @return The visual y position of this view, in pixels.
10679     */
10680    @ViewDebug.ExportedProperty(category = "drawing")
10681    public float getY() {
10682        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10683    }
10684
10685    /**
10686     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10687     * {@link #setTranslationY(float) translationY} property to be the difference between
10688     * the y value passed in and the current {@link #getTop() top} property.
10689     *
10690     * @param y The visual y position of this view, in pixels.
10691     */
10692    public void setY(float y) {
10693        setTranslationY(y - mTop);
10694    }
10695
10696
10697    /**
10698     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10699     * This position is post-layout, in addition to wherever the object's
10700     * layout placed it.
10701     *
10702     * @return The horizontal position of this view relative to its left position, in pixels.
10703     */
10704    @ViewDebug.ExportedProperty(category = "drawing")
10705    public float getTranslationX() {
10706        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10707    }
10708
10709    /**
10710     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10711     * This effectively positions the object post-layout, in addition to wherever the object's
10712     * layout placed it.
10713     *
10714     * @param translationX The horizontal position of this view relative to its left position,
10715     * in pixels.
10716     *
10717     * @attr ref android.R.styleable#View_translationX
10718     */
10719    public void setTranslationX(float translationX) {
10720        ensureTransformationInfo();
10721        final TransformationInfo info = mTransformationInfo;
10722        if (info.mTranslationX != translationX) {
10723            // Double-invalidation is necessary to capture view's old and new areas
10724            invalidateViewProperty(true, false);
10725            info.mTranslationX = translationX;
10726            info.mMatrixDirty = true;
10727            invalidateViewProperty(false, true);
10728            if (mDisplayList != null) {
10729                mDisplayList.setTranslationX(translationX);
10730            }
10731            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10732                // View was rejected last time it was drawn by its parent; this may have changed
10733                invalidateParentIfNeeded();
10734            }
10735        }
10736    }
10737
10738    /**
10739     * The vertical location of this view relative to its {@link #getTop() top} position.
10740     * This position is post-layout, in addition to wherever the object's
10741     * layout placed it.
10742     *
10743     * @return The vertical position of this view relative to its top position,
10744     * in pixels.
10745     */
10746    @ViewDebug.ExportedProperty(category = "drawing")
10747    public float getTranslationY() {
10748        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10749    }
10750
10751    /**
10752     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10753     * This effectively positions the object post-layout, in addition to wherever the object's
10754     * layout placed it.
10755     *
10756     * @param translationY The vertical position of this view relative to its top position,
10757     * in pixels.
10758     *
10759     * @attr ref android.R.styleable#View_translationY
10760     */
10761    public void setTranslationY(float translationY) {
10762        ensureTransformationInfo();
10763        final TransformationInfo info = mTransformationInfo;
10764        if (info.mTranslationY != translationY) {
10765            invalidateViewProperty(true, false);
10766            info.mTranslationY = translationY;
10767            info.mMatrixDirty = true;
10768            invalidateViewProperty(false, true);
10769            if (mDisplayList != null) {
10770                mDisplayList.setTranslationY(translationY);
10771            }
10772            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10773                // View was rejected last time it was drawn by its parent; this may have changed
10774                invalidateParentIfNeeded();
10775            }
10776        }
10777    }
10778
10779    /**
10780     * The depth location of this view relative to its parent.
10781     *
10782     * @return The depth of this view relative to its parent.
10783     */
10784    @ViewDebug.ExportedProperty(category = "drawing")
10785    public float getTranslationZ() {
10786        return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0;
10787    }
10788
10789    /**
10790     * Sets the depth location of this view relative to its parent.
10791     *
10792     * @attr ref android.R.styleable#View_translationZ
10793     */
10794    public void setTranslationZ(float translationZ) {
10795        ensureTransformationInfo();
10796        final TransformationInfo info = mTransformationInfo;
10797        if (info.mTranslationZ != translationZ) {
10798            invalidateViewProperty(true, false);
10799            info.mTranslationZ = translationZ;
10800            info.mMatrixDirty = true;
10801            invalidateViewProperty(false, true);
10802            if (mDisplayList != null) {
10803                mDisplayList.setTranslationZ(translationZ);
10804            }
10805            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10806                // View was rejected last time it was drawn by its parent; this may have changed
10807                invalidateParentIfNeeded();
10808            }
10809        }
10810    }
10811
10812    /**
10813     * Sets the outline of the view, which defines the shape of the shadow it
10814     * casts, and can used for clipping.
10815     * <p>
10816     * If the outline is not set or is null, shadows will be cast from the
10817     * bounds of the View, and clipToOutline will be ignored.
10818     *
10819     * @param outline The new outline of the view.
10820     *         Must be {@link android.view.Outline#isValid() valid.}
10821     *
10822     * @see #getClipToOutline()
10823     * @see #setClipToOutline(boolean)
10824     */
10825    public void setOutline(@Nullable Outline outline) {
10826        if (outline != null && !outline.isValid()) {
10827            throw new IllegalArgumentException("Outline must not be invalid");
10828        }
10829
10830        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10831
10832        if (outline == null) {
10833            mOutline = null;
10834        } else {
10835            // always copy the path since caller may reuse
10836            if (mOutline == null) {
10837                mOutline = new Outline();
10838            }
10839            mOutline.set(outline);
10840        }
10841
10842        if (mDisplayList != null) {
10843            mDisplayList.setOutline(mOutline);
10844        }
10845    }
10846
10847    /**
10848     * Returns whether the outline of the View will be used for clipping.
10849     *
10850     * @see #setOutline(Outline)
10851     */
10852    public final boolean getClipToOutline() {
10853        return ((mPrivateFlags3 & PFLAG3_CLIP_TO_OUTLINE) != 0);
10854    }
10855
10856    /**
10857     * Sets whether the outline of the View will be used for clipping.
10858     * <p>
10859     * The current implementation of outline clipping uses Canvas#clipPath(),
10860     * and thus does not support anti-aliasing, and is expensive in terms of
10861     * graphics performance. Therefore, it is strongly recommended that this
10862     * property only be set temporarily, as in an animation. For the same
10863     * reasons, there is no parallel XML attribute for this property.
10864     * <p>
10865     * If the outline of the view is not set or is empty, no clipping will be
10866     * performed.
10867     *
10868     * @see #setOutline(Outline)
10869     */
10870    public void setClipToOutline(boolean clipToOutline) {
10871        // TODO : Add a fast invalidation here.
10872        if (getClipToOutline() != clipToOutline) {
10873            if (clipToOutline) {
10874                mPrivateFlags3 |= PFLAG3_CLIP_TO_OUTLINE;
10875            } else {
10876                mPrivateFlags3 &= ~PFLAG3_CLIP_TO_OUTLINE;
10877            }
10878            if (mDisplayList != null) {
10879                mDisplayList.setClipToOutline(clipToOutline);
10880            }
10881        }
10882    }
10883
10884    /**
10885     * Hit rectangle in parent's coordinates
10886     *
10887     * @param outRect The hit rectangle of the view.
10888     */
10889    public void getHitRect(Rect outRect) {
10890        updateMatrix();
10891        final TransformationInfo info = mTransformationInfo;
10892        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10893            outRect.set(mLeft, mTop, mRight, mBottom);
10894        } else {
10895            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10896            tmpRect.set(0, 0, getWidth(), getHeight());
10897            info.mMatrix.mapRect(tmpRect);
10898            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10899                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10900        }
10901    }
10902
10903    /**
10904     * Determines whether the given point, in local coordinates is inside the view.
10905     */
10906    /*package*/ final boolean pointInView(float localX, float localY) {
10907        return localX >= 0 && localX < (mRight - mLeft)
10908                && localY >= 0 && localY < (mBottom - mTop);
10909    }
10910
10911    /**
10912     * Utility method to determine whether the given point, in local coordinates,
10913     * is inside the view, where the area of the view is expanded by the slop factor.
10914     * This method is called while processing touch-move events to determine if the event
10915     * is still within the view.
10916     *
10917     * @hide
10918     */
10919    public boolean pointInView(float localX, float localY, float slop) {
10920        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10921                localY < ((mBottom - mTop) + slop);
10922    }
10923
10924    /**
10925     * When a view has focus and the user navigates away from it, the next view is searched for
10926     * starting from the rectangle filled in by this method.
10927     *
10928     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10929     * of the view.  However, if your view maintains some idea of internal selection,
10930     * such as a cursor, or a selected row or column, you should override this method and
10931     * fill in a more specific rectangle.
10932     *
10933     * @param r The rectangle to fill in, in this view's coordinates.
10934     */
10935    public void getFocusedRect(Rect r) {
10936        getDrawingRect(r);
10937    }
10938
10939    /**
10940     * If some part of this view is not clipped by any of its parents, then
10941     * return that area in r in global (root) coordinates. To convert r to local
10942     * coordinates (without taking possible View rotations into account), offset
10943     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10944     * If the view is completely clipped or translated out, return false.
10945     *
10946     * @param r If true is returned, r holds the global coordinates of the
10947     *        visible portion of this view.
10948     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10949     *        between this view and its root. globalOffet may be null.
10950     * @return true if r is non-empty (i.e. part of the view is visible at the
10951     *         root level.
10952     */
10953    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10954        int width = mRight - mLeft;
10955        int height = mBottom - mTop;
10956        if (width > 0 && height > 0) {
10957            r.set(0, 0, width, height);
10958            if (globalOffset != null) {
10959                globalOffset.set(-mScrollX, -mScrollY);
10960            }
10961            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10962        }
10963        return false;
10964    }
10965
10966    public final boolean getGlobalVisibleRect(Rect r) {
10967        return getGlobalVisibleRect(r, null);
10968    }
10969
10970    public final boolean getLocalVisibleRect(Rect r) {
10971        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10972        if (getGlobalVisibleRect(r, offset)) {
10973            r.offset(-offset.x, -offset.y); // make r local
10974            return true;
10975        }
10976        return false;
10977    }
10978
10979    /**
10980     * Offset this view's vertical location by the specified number of pixels.
10981     *
10982     * @param offset the number of pixels to offset the view by
10983     */
10984    public void offsetTopAndBottom(int offset) {
10985        if (offset != 0) {
10986            updateMatrix();
10987            final boolean matrixIsIdentity = mTransformationInfo == null
10988                    || mTransformationInfo.mMatrixIsIdentity;
10989            if (matrixIsIdentity) {
10990                if (mDisplayList != null) {
10991                    invalidateViewProperty(false, false);
10992                } else {
10993                    final ViewParent p = mParent;
10994                    if (p != null && mAttachInfo != null) {
10995                        final Rect r = mAttachInfo.mTmpInvalRect;
10996                        int minTop;
10997                        int maxBottom;
10998                        int yLoc;
10999                        if (offset < 0) {
11000                            minTop = mTop + offset;
11001                            maxBottom = mBottom;
11002                            yLoc = offset;
11003                        } else {
11004                            minTop = mTop;
11005                            maxBottom = mBottom + offset;
11006                            yLoc = 0;
11007                        }
11008                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11009                        p.invalidateChild(this, r);
11010                    }
11011                }
11012            } else {
11013                invalidateViewProperty(false, false);
11014            }
11015
11016            mTop += offset;
11017            mBottom += offset;
11018            if (mDisplayList != null) {
11019                mDisplayList.offsetTopAndBottom(offset);
11020                invalidateViewProperty(false, false);
11021            } else {
11022                if (!matrixIsIdentity) {
11023                    invalidateViewProperty(false, true);
11024                }
11025                invalidateParentIfNeeded();
11026            }
11027        }
11028    }
11029
11030    /**
11031     * Offset this view's horizontal location by the specified amount of pixels.
11032     *
11033     * @param offset the number of pixels to offset the view by
11034     */
11035    public void offsetLeftAndRight(int offset) {
11036        if (offset != 0) {
11037            updateMatrix();
11038            final boolean matrixIsIdentity = mTransformationInfo == null
11039                    || mTransformationInfo.mMatrixIsIdentity;
11040            if (matrixIsIdentity) {
11041                if (mDisplayList != null) {
11042                    invalidateViewProperty(false, false);
11043                } else {
11044                    final ViewParent p = mParent;
11045                    if (p != null && mAttachInfo != null) {
11046                        final Rect r = mAttachInfo.mTmpInvalRect;
11047                        int minLeft;
11048                        int maxRight;
11049                        if (offset < 0) {
11050                            minLeft = mLeft + offset;
11051                            maxRight = mRight;
11052                        } else {
11053                            minLeft = mLeft;
11054                            maxRight = mRight + offset;
11055                        }
11056                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11057                        p.invalidateChild(this, r);
11058                    }
11059                }
11060            } else {
11061                invalidateViewProperty(false, false);
11062            }
11063
11064            mLeft += offset;
11065            mRight += offset;
11066            if (mDisplayList != null) {
11067                mDisplayList.offsetLeftAndRight(offset);
11068                invalidateViewProperty(false, false);
11069            } else {
11070                if (!matrixIsIdentity) {
11071                    invalidateViewProperty(false, true);
11072                }
11073                invalidateParentIfNeeded();
11074            }
11075        }
11076    }
11077
11078    /**
11079     * Get the LayoutParams associated with this view. All views should have
11080     * layout parameters. These supply parameters to the <i>parent</i> of this
11081     * view specifying how it should be arranged. There are many subclasses of
11082     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11083     * of ViewGroup that are responsible for arranging their children.
11084     *
11085     * This method may return null if this View is not attached to a parent
11086     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11087     * was not invoked successfully. When a View is attached to a parent
11088     * ViewGroup, this method must not return null.
11089     *
11090     * @return The LayoutParams associated with this view, or null if no
11091     *         parameters have been set yet
11092     */
11093    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11094    public ViewGroup.LayoutParams getLayoutParams() {
11095        return mLayoutParams;
11096    }
11097
11098    /**
11099     * Set the layout parameters associated with this view. These supply
11100     * parameters to the <i>parent</i> of this view specifying how it should be
11101     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11102     * correspond to the different subclasses of ViewGroup that are responsible
11103     * for arranging their children.
11104     *
11105     * @param params The layout parameters for this view, cannot be null
11106     */
11107    public void setLayoutParams(ViewGroup.LayoutParams params) {
11108        if (params == null) {
11109            throw new NullPointerException("Layout parameters cannot be null");
11110        }
11111        mLayoutParams = params;
11112        resolveLayoutParams();
11113        if (mParent instanceof ViewGroup) {
11114            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11115        }
11116        requestLayout();
11117    }
11118
11119    /**
11120     * Resolve the layout parameters depending on the resolved layout direction
11121     *
11122     * @hide
11123     */
11124    public void resolveLayoutParams() {
11125        if (mLayoutParams != null) {
11126            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11127        }
11128    }
11129
11130    /**
11131     * Set the scrolled position of your view. This will cause a call to
11132     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11133     * invalidated.
11134     * @param x the x position to scroll to
11135     * @param y the y position to scroll to
11136     */
11137    public void scrollTo(int x, int y) {
11138        if (mScrollX != x || mScrollY != y) {
11139            int oldX = mScrollX;
11140            int oldY = mScrollY;
11141            mScrollX = x;
11142            mScrollY = y;
11143            invalidateParentCaches();
11144            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11145            if (!awakenScrollBars()) {
11146                postInvalidateOnAnimation();
11147            }
11148        }
11149    }
11150
11151    /**
11152     * Move the scrolled position of your view. This will cause a call to
11153     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11154     * invalidated.
11155     * @param x the amount of pixels to scroll by horizontally
11156     * @param y the amount of pixels to scroll by vertically
11157     */
11158    public void scrollBy(int x, int y) {
11159        scrollTo(mScrollX + x, mScrollY + y);
11160    }
11161
11162    /**
11163     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11164     * animation to fade the scrollbars out after a default delay. If a subclass
11165     * provides animated scrolling, the start delay should equal the duration
11166     * of the scrolling animation.</p>
11167     *
11168     * <p>The animation starts only if at least one of the scrollbars is
11169     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11170     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11171     * this method returns true, and false otherwise. If the animation is
11172     * started, this method calls {@link #invalidate()}; in that case the
11173     * caller should not call {@link #invalidate()}.</p>
11174     *
11175     * <p>This method should be invoked every time a subclass directly updates
11176     * the scroll parameters.</p>
11177     *
11178     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11179     * and {@link #scrollTo(int, int)}.</p>
11180     *
11181     * @return true if the animation is played, false otherwise
11182     *
11183     * @see #awakenScrollBars(int)
11184     * @see #scrollBy(int, int)
11185     * @see #scrollTo(int, int)
11186     * @see #isHorizontalScrollBarEnabled()
11187     * @see #isVerticalScrollBarEnabled()
11188     * @see #setHorizontalScrollBarEnabled(boolean)
11189     * @see #setVerticalScrollBarEnabled(boolean)
11190     */
11191    protected boolean awakenScrollBars() {
11192        return mScrollCache != null &&
11193                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11194    }
11195
11196    /**
11197     * Trigger the scrollbars to draw.
11198     * This method differs from awakenScrollBars() only in its default duration.
11199     * initialAwakenScrollBars() will show the scroll bars for longer than
11200     * usual to give the user more of a chance to notice them.
11201     *
11202     * @return true if the animation is played, false otherwise.
11203     */
11204    private boolean initialAwakenScrollBars() {
11205        return mScrollCache != null &&
11206                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11207    }
11208
11209    /**
11210     * <p>
11211     * Trigger the scrollbars to draw. When invoked this method starts an
11212     * animation to fade the scrollbars out after a fixed delay. If a subclass
11213     * provides animated scrolling, the start delay should equal the duration of
11214     * the scrolling animation.
11215     * </p>
11216     *
11217     * <p>
11218     * The animation starts only if at least one of the scrollbars is enabled,
11219     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11220     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11221     * this method returns true, and false otherwise. If the animation is
11222     * started, this method calls {@link #invalidate()}; in that case the caller
11223     * should not call {@link #invalidate()}.
11224     * </p>
11225     *
11226     * <p>
11227     * This method should be invoked everytime a subclass directly updates the
11228     * scroll parameters.
11229     * </p>
11230     *
11231     * @param startDelay the delay, in milliseconds, after which the animation
11232     *        should start; when the delay is 0, the animation starts
11233     *        immediately
11234     * @return true if the animation is played, false otherwise
11235     *
11236     * @see #scrollBy(int, int)
11237     * @see #scrollTo(int, int)
11238     * @see #isHorizontalScrollBarEnabled()
11239     * @see #isVerticalScrollBarEnabled()
11240     * @see #setHorizontalScrollBarEnabled(boolean)
11241     * @see #setVerticalScrollBarEnabled(boolean)
11242     */
11243    protected boolean awakenScrollBars(int startDelay) {
11244        return awakenScrollBars(startDelay, true);
11245    }
11246
11247    /**
11248     * <p>
11249     * Trigger the scrollbars to draw. When invoked this method starts an
11250     * animation to fade the scrollbars out after a fixed delay. If a subclass
11251     * provides animated scrolling, the start delay should equal the duration of
11252     * the scrolling animation.
11253     * </p>
11254     *
11255     * <p>
11256     * The animation starts only if at least one of the scrollbars is enabled,
11257     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11258     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11259     * this method returns true, and false otherwise. If the animation is
11260     * started, this method calls {@link #invalidate()} if the invalidate parameter
11261     * is set to true; in that case the caller
11262     * should not call {@link #invalidate()}.
11263     * </p>
11264     *
11265     * <p>
11266     * This method should be invoked everytime a subclass directly updates the
11267     * scroll parameters.
11268     * </p>
11269     *
11270     * @param startDelay the delay, in milliseconds, after which the animation
11271     *        should start; when the delay is 0, the animation starts
11272     *        immediately
11273     *
11274     * @param invalidate Wheter this method should call invalidate
11275     *
11276     * @return true if the animation is played, false otherwise
11277     *
11278     * @see #scrollBy(int, int)
11279     * @see #scrollTo(int, int)
11280     * @see #isHorizontalScrollBarEnabled()
11281     * @see #isVerticalScrollBarEnabled()
11282     * @see #setHorizontalScrollBarEnabled(boolean)
11283     * @see #setVerticalScrollBarEnabled(boolean)
11284     */
11285    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11286        final ScrollabilityCache scrollCache = mScrollCache;
11287
11288        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11289            return false;
11290        }
11291
11292        if (scrollCache.scrollBar == null) {
11293            scrollCache.scrollBar = new ScrollBarDrawable();
11294        }
11295
11296        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11297
11298            if (invalidate) {
11299                // Invalidate to show the scrollbars
11300                postInvalidateOnAnimation();
11301            }
11302
11303            if (scrollCache.state == ScrollabilityCache.OFF) {
11304                // FIXME: this is copied from WindowManagerService.
11305                // We should get this value from the system when it
11306                // is possible to do so.
11307                final int KEY_REPEAT_FIRST_DELAY = 750;
11308                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11309            }
11310
11311            // Tell mScrollCache when we should start fading. This may
11312            // extend the fade start time if one was already scheduled
11313            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11314            scrollCache.fadeStartTime = fadeStartTime;
11315            scrollCache.state = ScrollabilityCache.ON;
11316
11317            // Schedule our fader to run, unscheduling any old ones first
11318            if (mAttachInfo != null) {
11319                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11320                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11321            }
11322
11323            return true;
11324        }
11325
11326        return false;
11327    }
11328
11329    /**
11330     * Do not invalidate views which are not visible and which are not running an animation. They
11331     * will not get drawn and they should not set dirty flags as if they will be drawn
11332     */
11333    private boolean skipInvalidate() {
11334        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11335                (!(mParent instanceof ViewGroup) ||
11336                        !((ViewGroup) mParent).isViewTransitioning(this));
11337    }
11338
11339    /**
11340     * Mark the area defined by dirty as needing to be drawn. If the view is
11341     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11342     * point in the future.
11343     * <p>
11344     * This must be called from a UI thread. To call from a non-UI thread, call
11345     * {@link #postInvalidate()}.
11346     * <p>
11347     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11348     * {@code dirty}.
11349     *
11350     * @param dirty the rectangle representing the bounds of the dirty region
11351     */
11352    public void invalidate(Rect dirty) {
11353        final int scrollX = mScrollX;
11354        final int scrollY = mScrollY;
11355        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11356                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11357    }
11358
11359    /**
11360     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11361     * coordinates of the dirty rect are relative to the view. If the view is
11362     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11363     * point in the future.
11364     * <p>
11365     * This must be called from a UI thread. To call from a non-UI thread, call
11366     * {@link #postInvalidate()}.
11367     *
11368     * @param l the left position of the dirty region
11369     * @param t the top position of the dirty region
11370     * @param r the right position of the dirty region
11371     * @param b the bottom position of the dirty region
11372     */
11373    public void invalidate(int l, int t, int r, int b) {
11374        final int scrollX = mScrollX;
11375        final int scrollY = mScrollY;
11376        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11377    }
11378
11379    /**
11380     * Invalidate the whole view. If the view is visible,
11381     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11382     * the future.
11383     * <p>
11384     * This must be called from a UI thread. To call from a non-UI thread, call
11385     * {@link #postInvalidate()}.
11386     */
11387    public void invalidate() {
11388        invalidate(true);
11389    }
11390
11391    /**
11392     * This is where the invalidate() work actually happens. A full invalidate()
11393     * causes the drawing cache to be invalidated, but this function can be
11394     * called with invalidateCache set to false to skip that invalidation step
11395     * for cases that do not need it (for example, a component that remains at
11396     * the same dimensions with the same content).
11397     *
11398     * @param invalidateCache Whether the drawing cache for this view should be
11399     *            invalidated as well. This is usually true for a full
11400     *            invalidate, but may be set to false if the View's contents or
11401     *            dimensions have not changed.
11402     */
11403    void invalidate(boolean invalidateCache) {
11404        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11405    }
11406
11407    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11408            boolean fullInvalidate) {
11409        if (skipInvalidate()) {
11410            return;
11411        }
11412
11413        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11414                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11415                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11416                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11417            if (fullInvalidate) {
11418                mLastIsOpaque = isOpaque();
11419                mPrivateFlags &= ~PFLAG_DRAWN;
11420            }
11421
11422            mPrivateFlags |= PFLAG_DIRTY;
11423
11424            if (invalidateCache) {
11425                mPrivateFlags |= PFLAG_INVALIDATED;
11426                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11427            }
11428
11429            // Propagate the damage rectangle to the parent view.
11430            final AttachInfo ai = mAttachInfo;
11431            final ViewParent p = mParent;
11432            if (p != null && ai != null && l < r && t < b) {
11433                final Rect damage = ai.mTmpInvalRect;
11434                damage.set(l, t, r, b);
11435                p.invalidateChild(this, damage);
11436            }
11437
11438            // Damage the entire projection receiver, if necessary.
11439            if (mBackground != null && mBackground.isProjected()) {
11440                final View receiver = getProjectionReceiver();
11441                if (receiver != null) {
11442                    receiver.damageInParent();
11443                }
11444            }
11445
11446            // Damage the entire IsolatedZVolume recieving this view's shadow.
11447            if (getTranslationZ() != 0) {
11448                damageShadowReceiver();
11449            }
11450        }
11451    }
11452
11453    /**
11454     * @return this view's projection receiver, or {@code null} if none exists
11455     */
11456    private View getProjectionReceiver() {
11457        ViewParent p = getParent();
11458        while (p != null && p instanceof View) {
11459            final View v = (View) p;
11460            if (v.isProjectionReceiver()) {
11461                return v;
11462            }
11463            p = p.getParent();
11464        }
11465
11466        return null;
11467    }
11468
11469    /**
11470     * @return whether the view is a projection receiver
11471     */
11472    private boolean isProjectionReceiver() {
11473        return mBackground != null;
11474    }
11475
11476    /**
11477     * Damage area of the screen that can be covered by this View's shadow.
11478     *
11479     * This method will guarantee that any changes to shadows cast by a View
11480     * are damaged on the screen for future redraw.
11481     */
11482    private void damageShadowReceiver() {
11483        final AttachInfo ai = mAttachInfo;
11484        if (ai != null) {
11485            ViewParent p = getParent();
11486            if (p != null && p instanceof ViewGroup) {
11487                final ViewGroup vg = (ViewGroup) p;
11488                vg.damageInParent();
11489            }
11490        }
11491    }
11492
11493    /**
11494     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11495     * set any flags or handle all of the cases handled by the default invalidation methods.
11496     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11497     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11498     * walk up the hierarchy, transforming the dirty rect as necessary.
11499     *
11500     * The method also handles normal invalidation logic if display list properties are not
11501     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11502     * backup approach, to handle these cases used in the various property-setting methods.
11503     *
11504     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11505     * are not being used in this view
11506     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11507     * list properties are not being used in this view
11508     */
11509    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11510        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11511            if (invalidateParent) {
11512                invalidateParentCaches();
11513            }
11514            if (forceRedraw) {
11515                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11516            }
11517            invalidate(false);
11518        } else {
11519            damageInParent();
11520        }
11521        if (invalidateParent && getTranslationZ() != 0) {
11522            damageShadowReceiver();
11523        }
11524    }
11525
11526    /**
11527     * Tells the parent view to damage this view's bounds.
11528     *
11529     * @hide
11530     */
11531    protected void damageInParent() {
11532        final AttachInfo ai = mAttachInfo;
11533        final ViewParent p = mParent;
11534        if (p != null && ai != null) {
11535            final Rect r = ai.mTmpInvalRect;
11536            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11537            if (mParent instanceof ViewGroup) {
11538                ((ViewGroup) mParent).invalidateChildFast(this, r);
11539            } else {
11540                mParent.invalidateChild(this, r);
11541            }
11542        }
11543    }
11544
11545    /**
11546     * Utility method to transform a given Rect by the current matrix of this view.
11547     */
11548    void transformRect(final Rect rect) {
11549        if (!getMatrix().isIdentity()) {
11550            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11551            boundingRect.set(rect);
11552            getMatrix().mapRect(boundingRect);
11553            rect.set((int) Math.floor(boundingRect.left),
11554                    (int) Math.floor(boundingRect.top),
11555                    (int) Math.ceil(boundingRect.right),
11556                    (int) Math.ceil(boundingRect.bottom));
11557        }
11558    }
11559
11560    /**
11561     * Used to indicate that the parent of this view should clear its caches. This functionality
11562     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11563     * which is necessary when various parent-managed properties of the view change, such as
11564     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11565     * clears the parent caches and does not causes an invalidate event.
11566     *
11567     * @hide
11568     */
11569    protected void invalidateParentCaches() {
11570        if (mParent instanceof View) {
11571            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11572        }
11573    }
11574
11575    /**
11576     * Used to indicate that the parent of this view should be invalidated. This functionality
11577     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11578     * which is necessary when various parent-managed properties of the view change, such as
11579     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11580     * an invalidation event to the parent.
11581     *
11582     * @hide
11583     */
11584    protected void invalidateParentIfNeeded() {
11585        if (isHardwareAccelerated() && mParent instanceof View) {
11586            ((View) mParent).invalidate(true);
11587        }
11588    }
11589
11590    /**
11591     * Indicates whether this View is opaque. An opaque View guarantees that it will
11592     * draw all the pixels overlapping its bounds using a fully opaque color.
11593     *
11594     * Subclasses of View should override this method whenever possible to indicate
11595     * whether an instance is opaque. Opaque Views are treated in a special way by
11596     * the View hierarchy, possibly allowing it to perform optimizations during
11597     * invalidate/draw passes.
11598     *
11599     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11600     */
11601    @ViewDebug.ExportedProperty(category = "drawing")
11602    public boolean isOpaque() {
11603        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11604                getFinalAlpha() >= 1.0f;
11605    }
11606
11607    /**
11608     * @hide
11609     */
11610    protected void computeOpaqueFlags() {
11611        // Opaque if:
11612        //   - Has a background
11613        //   - Background is opaque
11614        //   - Doesn't have scrollbars or scrollbars overlay
11615
11616        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11617            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11618        } else {
11619            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11620        }
11621
11622        final int flags = mViewFlags;
11623        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11624                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11625                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11626            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11627        } else {
11628            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11629        }
11630    }
11631
11632    /**
11633     * @hide
11634     */
11635    protected boolean hasOpaqueScrollbars() {
11636        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11637    }
11638
11639    /**
11640     * @return A handler associated with the thread running the View. This
11641     * handler can be used to pump events in the UI events queue.
11642     */
11643    public Handler getHandler() {
11644        final AttachInfo attachInfo = mAttachInfo;
11645        if (attachInfo != null) {
11646            return attachInfo.mHandler;
11647        }
11648        return null;
11649    }
11650
11651    /**
11652     * Gets the view root associated with the View.
11653     * @return The view root, or null if none.
11654     * @hide
11655     */
11656    public ViewRootImpl getViewRootImpl() {
11657        if (mAttachInfo != null) {
11658            return mAttachInfo.mViewRootImpl;
11659        }
11660        return null;
11661    }
11662
11663    /**
11664     * @hide
11665     */
11666    public HardwareRenderer getHardwareRenderer() {
11667        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11668    }
11669
11670    /**
11671     * <p>Causes the Runnable to be added to the message queue.
11672     * The runnable will be run on the user interface thread.</p>
11673     *
11674     * @param action The Runnable that will be executed.
11675     *
11676     * @return Returns true if the Runnable was successfully placed in to the
11677     *         message queue.  Returns false on failure, usually because the
11678     *         looper processing the message queue is exiting.
11679     *
11680     * @see #postDelayed
11681     * @see #removeCallbacks
11682     */
11683    public boolean post(Runnable action) {
11684        final AttachInfo attachInfo = mAttachInfo;
11685        if (attachInfo != null) {
11686            return attachInfo.mHandler.post(action);
11687        }
11688        // Assume that post will succeed later
11689        ViewRootImpl.getRunQueue().post(action);
11690        return true;
11691    }
11692
11693    /**
11694     * <p>Causes the Runnable to be added to the message queue, to be run
11695     * after the specified amount of time elapses.
11696     * The runnable will be run on the user interface thread.</p>
11697     *
11698     * @param action The Runnable that will be executed.
11699     * @param delayMillis The delay (in milliseconds) until the Runnable
11700     *        will be executed.
11701     *
11702     * @return true if the Runnable was successfully placed in to the
11703     *         message queue.  Returns false on failure, usually because the
11704     *         looper processing the message queue is exiting.  Note that a
11705     *         result of true does not mean the Runnable will be processed --
11706     *         if the looper is quit before the delivery time of the message
11707     *         occurs then the message will be dropped.
11708     *
11709     * @see #post
11710     * @see #removeCallbacks
11711     */
11712    public boolean postDelayed(Runnable action, long delayMillis) {
11713        final AttachInfo attachInfo = mAttachInfo;
11714        if (attachInfo != null) {
11715            return attachInfo.mHandler.postDelayed(action, delayMillis);
11716        }
11717        // Assume that post will succeed later
11718        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11719        return true;
11720    }
11721
11722    /**
11723     * <p>Causes the Runnable to execute on the next animation time step.
11724     * The runnable will be run on the user interface thread.</p>
11725     *
11726     * @param action The Runnable that will be executed.
11727     *
11728     * @see #postOnAnimationDelayed
11729     * @see #removeCallbacks
11730     */
11731    public void postOnAnimation(Runnable action) {
11732        final AttachInfo attachInfo = mAttachInfo;
11733        if (attachInfo != null) {
11734            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11735                    Choreographer.CALLBACK_ANIMATION, action, null);
11736        } else {
11737            // Assume that post will succeed later
11738            ViewRootImpl.getRunQueue().post(action);
11739        }
11740    }
11741
11742    /**
11743     * <p>Causes the Runnable to execute on the next animation time step,
11744     * after the specified amount of time elapses.
11745     * The runnable will be run on the user interface thread.</p>
11746     *
11747     * @param action The Runnable that will be executed.
11748     * @param delayMillis The delay (in milliseconds) until the Runnable
11749     *        will be executed.
11750     *
11751     * @see #postOnAnimation
11752     * @see #removeCallbacks
11753     */
11754    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11755        final AttachInfo attachInfo = mAttachInfo;
11756        if (attachInfo != null) {
11757            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11758                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11759        } else {
11760            // Assume that post will succeed later
11761            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11762        }
11763    }
11764
11765    /**
11766     * <p>Removes the specified Runnable from the message queue.</p>
11767     *
11768     * @param action The Runnable to remove from the message handling queue
11769     *
11770     * @return true if this view could ask the Handler to remove the Runnable,
11771     *         false otherwise. When the returned value is true, the Runnable
11772     *         may or may not have been actually removed from the message queue
11773     *         (for instance, if the Runnable was not in the queue already.)
11774     *
11775     * @see #post
11776     * @see #postDelayed
11777     * @see #postOnAnimation
11778     * @see #postOnAnimationDelayed
11779     */
11780    public boolean removeCallbacks(Runnable action) {
11781        if (action != null) {
11782            final AttachInfo attachInfo = mAttachInfo;
11783            if (attachInfo != null) {
11784                attachInfo.mHandler.removeCallbacks(action);
11785                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11786                        Choreographer.CALLBACK_ANIMATION, action, null);
11787            }
11788            // Assume that post will succeed later
11789            ViewRootImpl.getRunQueue().removeCallbacks(action);
11790        }
11791        return true;
11792    }
11793
11794    /**
11795     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11796     * Use this to invalidate the View from a non-UI thread.</p>
11797     *
11798     * <p>This method can be invoked from outside of the UI thread
11799     * only when this View is attached to a window.</p>
11800     *
11801     * @see #invalidate()
11802     * @see #postInvalidateDelayed(long)
11803     */
11804    public void postInvalidate() {
11805        postInvalidateDelayed(0);
11806    }
11807
11808    /**
11809     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11810     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11811     *
11812     * <p>This method can be invoked from outside of the UI thread
11813     * only when this View is attached to a window.</p>
11814     *
11815     * @param left The left coordinate of the rectangle to invalidate.
11816     * @param top The top coordinate of the rectangle to invalidate.
11817     * @param right The right coordinate of the rectangle to invalidate.
11818     * @param bottom The bottom coordinate of the rectangle to invalidate.
11819     *
11820     * @see #invalidate(int, int, int, int)
11821     * @see #invalidate(Rect)
11822     * @see #postInvalidateDelayed(long, int, int, int, int)
11823     */
11824    public void postInvalidate(int left, int top, int right, int bottom) {
11825        postInvalidateDelayed(0, left, top, right, bottom);
11826    }
11827
11828    /**
11829     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11830     * loop. Waits for the specified amount of time.</p>
11831     *
11832     * <p>This method can be invoked from outside of the UI thread
11833     * only when this View is attached to a window.</p>
11834     *
11835     * @param delayMilliseconds the duration in milliseconds to delay the
11836     *         invalidation by
11837     *
11838     * @see #invalidate()
11839     * @see #postInvalidate()
11840     */
11841    public void postInvalidateDelayed(long delayMilliseconds) {
11842        // We try only with the AttachInfo because there's no point in invalidating
11843        // if we are not attached to our window
11844        final AttachInfo attachInfo = mAttachInfo;
11845        if (attachInfo != null) {
11846            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11847        }
11848    }
11849
11850    /**
11851     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11852     * through the event loop. Waits for the specified amount of time.</p>
11853     *
11854     * <p>This method can be invoked from outside of the UI thread
11855     * only when this View is attached to a window.</p>
11856     *
11857     * @param delayMilliseconds the duration in milliseconds to delay the
11858     *         invalidation by
11859     * @param left The left coordinate of the rectangle to invalidate.
11860     * @param top The top coordinate of the rectangle to invalidate.
11861     * @param right The right coordinate of the rectangle to invalidate.
11862     * @param bottom The bottom coordinate of the rectangle to invalidate.
11863     *
11864     * @see #invalidate(int, int, int, int)
11865     * @see #invalidate(Rect)
11866     * @see #postInvalidate(int, int, int, int)
11867     */
11868    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11869            int right, int bottom) {
11870
11871        // We try only with the AttachInfo because there's no point in invalidating
11872        // if we are not attached to our window
11873        final AttachInfo attachInfo = mAttachInfo;
11874        if (attachInfo != null) {
11875            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11876            info.target = this;
11877            info.left = left;
11878            info.top = top;
11879            info.right = right;
11880            info.bottom = bottom;
11881
11882            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11883        }
11884    }
11885
11886    /**
11887     * <p>Cause an invalidate to happen on the next animation time step, typically the
11888     * next display frame.</p>
11889     *
11890     * <p>This method can be invoked from outside of the UI thread
11891     * only when this View is attached to a window.</p>
11892     *
11893     * @see #invalidate()
11894     */
11895    public void postInvalidateOnAnimation() {
11896        // We try only with the AttachInfo because there's no point in invalidating
11897        // if we are not attached to our window
11898        final AttachInfo attachInfo = mAttachInfo;
11899        if (attachInfo != null) {
11900            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11901        }
11902    }
11903
11904    /**
11905     * <p>Cause an invalidate of the specified area to happen on the next animation
11906     * time step, typically the next display frame.</p>
11907     *
11908     * <p>This method can be invoked from outside of the UI thread
11909     * only when this View is attached to a window.</p>
11910     *
11911     * @param left The left coordinate of the rectangle to invalidate.
11912     * @param top The top coordinate of the rectangle to invalidate.
11913     * @param right The right coordinate of the rectangle to invalidate.
11914     * @param bottom The bottom coordinate of the rectangle to invalidate.
11915     *
11916     * @see #invalidate(int, int, int, int)
11917     * @see #invalidate(Rect)
11918     */
11919    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11920        // We try only with the AttachInfo because there's no point in invalidating
11921        // if we are not attached to our window
11922        final AttachInfo attachInfo = mAttachInfo;
11923        if (attachInfo != null) {
11924            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11925            info.target = this;
11926            info.left = left;
11927            info.top = top;
11928            info.right = right;
11929            info.bottom = bottom;
11930
11931            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11932        }
11933    }
11934
11935    /**
11936     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11937     * This event is sent at most once every
11938     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11939     */
11940    private void postSendViewScrolledAccessibilityEventCallback() {
11941        if (mSendViewScrolledAccessibilityEvent == null) {
11942            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11943        }
11944        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11945            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11946            postDelayed(mSendViewScrolledAccessibilityEvent,
11947                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11948        }
11949    }
11950
11951    /**
11952     * Called by a parent to request that a child update its values for mScrollX
11953     * and mScrollY if necessary. This will typically be done if the child is
11954     * animating a scroll using a {@link android.widget.Scroller Scroller}
11955     * object.
11956     */
11957    public void computeScroll() {
11958    }
11959
11960    /**
11961     * <p>Indicate whether the horizontal edges are faded when the view is
11962     * scrolled horizontally.</p>
11963     *
11964     * @return true if the horizontal edges should are faded on scroll, false
11965     *         otherwise
11966     *
11967     * @see #setHorizontalFadingEdgeEnabled(boolean)
11968     *
11969     * @attr ref android.R.styleable#View_requiresFadingEdge
11970     */
11971    public boolean isHorizontalFadingEdgeEnabled() {
11972        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11973    }
11974
11975    /**
11976     * <p>Define whether the horizontal edges should be faded when this view
11977     * is scrolled horizontally.</p>
11978     *
11979     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11980     *                                    be faded when the view is scrolled
11981     *                                    horizontally
11982     *
11983     * @see #isHorizontalFadingEdgeEnabled()
11984     *
11985     * @attr ref android.R.styleable#View_requiresFadingEdge
11986     */
11987    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11988        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11989            if (horizontalFadingEdgeEnabled) {
11990                initScrollCache();
11991            }
11992
11993            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11994        }
11995    }
11996
11997    /**
11998     * <p>Indicate whether the vertical edges are faded when the view is
11999     * scrolled horizontally.</p>
12000     *
12001     * @return true if the vertical edges should are faded on scroll, false
12002     *         otherwise
12003     *
12004     * @see #setVerticalFadingEdgeEnabled(boolean)
12005     *
12006     * @attr ref android.R.styleable#View_requiresFadingEdge
12007     */
12008    public boolean isVerticalFadingEdgeEnabled() {
12009        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12010    }
12011
12012    /**
12013     * <p>Define whether the vertical edges should be faded when this view
12014     * is scrolled vertically.</p>
12015     *
12016     * @param verticalFadingEdgeEnabled true if the vertical edges should
12017     *                                  be faded when the view is scrolled
12018     *                                  vertically
12019     *
12020     * @see #isVerticalFadingEdgeEnabled()
12021     *
12022     * @attr ref android.R.styleable#View_requiresFadingEdge
12023     */
12024    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12025        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12026            if (verticalFadingEdgeEnabled) {
12027                initScrollCache();
12028            }
12029
12030            mViewFlags ^= FADING_EDGE_VERTICAL;
12031        }
12032    }
12033
12034    /**
12035     * Returns the strength, or intensity, of the top faded edge. The strength is
12036     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12037     * returns 0.0 or 1.0 but no value in between.
12038     *
12039     * Subclasses should override this method to provide a smoother fade transition
12040     * when scrolling occurs.
12041     *
12042     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12043     */
12044    protected float getTopFadingEdgeStrength() {
12045        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12046    }
12047
12048    /**
12049     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12050     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12051     * returns 0.0 or 1.0 but no value in between.
12052     *
12053     * Subclasses should override this method to provide a smoother fade transition
12054     * when scrolling occurs.
12055     *
12056     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12057     */
12058    protected float getBottomFadingEdgeStrength() {
12059        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12060                computeVerticalScrollRange() ? 1.0f : 0.0f;
12061    }
12062
12063    /**
12064     * Returns the strength, or intensity, of the left faded edge. The strength is
12065     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12066     * returns 0.0 or 1.0 but no value in between.
12067     *
12068     * Subclasses should override this method to provide a smoother fade transition
12069     * when scrolling occurs.
12070     *
12071     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12072     */
12073    protected float getLeftFadingEdgeStrength() {
12074        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12075    }
12076
12077    /**
12078     * Returns the strength, or intensity, of the right faded edge. The strength is
12079     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12080     * returns 0.0 or 1.0 but no value in between.
12081     *
12082     * Subclasses should override this method to provide a smoother fade transition
12083     * when scrolling occurs.
12084     *
12085     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12086     */
12087    protected float getRightFadingEdgeStrength() {
12088        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12089                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12090    }
12091
12092    /**
12093     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12094     * scrollbar is not drawn by default.</p>
12095     *
12096     * @return true if the horizontal scrollbar should be painted, false
12097     *         otherwise
12098     *
12099     * @see #setHorizontalScrollBarEnabled(boolean)
12100     */
12101    public boolean isHorizontalScrollBarEnabled() {
12102        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12103    }
12104
12105    /**
12106     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12107     * scrollbar is not drawn by default.</p>
12108     *
12109     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12110     *                                   be painted
12111     *
12112     * @see #isHorizontalScrollBarEnabled()
12113     */
12114    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12115        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12116            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12117            computeOpaqueFlags();
12118            resolvePadding();
12119        }
12120    }
12121
12122    /**
12123     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12124     * scrollbar is not drawn by default.</p>
12125     *
12126     * @return true if the vertical scrollbar should be painted, false
12127     *         otherwise
12128     *
12129     * @see #setVerticalScrollBarEnabled(boolean)
12130     */
12131    public boolean isVerticalScrollBarEnabled() {
12132        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12133    }
12134
12135    /**
12136     * <p>Define whether the vertical scrollbar should be drawn or not. The
12137     * scrollbar is not drawn by default.</p>
12138     *
12139     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12140     *                                 be painted
12141     *
12142     * @see #isVerticalScrollBarEnabled()
12143     */
12144    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12145        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12146            mViewFlags ^= SCROLLBARS_VERTICAL;
12147            computeOpaqueFlags();
12148            resolvePadding();
12149        }
12150    }
12151
12152    /**
12153     * @hide
12154     */
12155    protected void recomputePadding() {
12156        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12157    }
12158
12159    /**
12160     * Define whether scrollbars will fade when the view is not scrolling.
12161     *
12162     * @param fadeScrollbars wheter to enable fading
12163     *
12164     * @attr ref android.R.styleable#View_fadeScrollbars
12165     */
12166    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12167        initScrollCache();
12168        final ScrollabilityCache scrollabilityCache = mScrollCache;
12169        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12170        if (fadeScrollbars) {
12171            scrollabilityCache.state = ScrollabilityCache.OFF;
12172        } else {
12173            scrollabilityCache.state = ScrollabilityCache.ON;
12174        }
12175    }
12176
12177    /**
12178     *
12179     * Returns true if scrollbars will fade when this view is not scrolling
12180     *
12181     * @return true if scrollbar fading is enabled
12182     *
12183     * @attr ref android.R.styleable#View_fadeScrollbars
12184     */
12185    public boolean isScrollbarFadingEnabled() {
12186        return mScrollCache != null && mScrollCache.fadeScrollBars;
12187    }
12188
12189    /**
12190     *
12191     * Returns the delay before scrollbars fade.
12192     *
12193     * @return the delay before scrollbars fade
12194     *
12195     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12196     */
12197    public int getScrollBarDefaultDelayBeforeFade() {
12198        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12199                mScrollCache.scrollBarDefaultDelayBeforeFade;
12200    }
12201
12202    /**
12203     * Define the delay before scrollbars fade.
12204     *
12205     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12206     *
12207     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12208     */
12209    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12210        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12211    }
12212
12213    /**
12214     *
12215     * Returns the scrollbar fade duration.
12216     *
12217     * @return the scrollbar fade duration
12218     *
12219     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12220     */
12221    public int getScrollBarFadeDuration() {
12222        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12223                mScrollCache.scrollBarFadeDuration;
12224    }
12225
12226    /**
12227     * Define the scrollbar fade duration.
12228     *
12229     * @param scrollBarFadeDuration - the scrollbar fade duration
12230     *
12231     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12232     */
12233    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12234        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12235    }
12236
12237    /**
12238     *
12239     * Returns the scrollbar size.
12240     *
12241     * @return the scrollbar size
12242     *
12243     * @attr ref android.R.styleable#View_scrollbarSize
12244     */
12245    public int getScrollBarSize() {
12246        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12247                mScrollCache.scrollBarSize;
12248    }
12249
12250    /**
12251     * Define the scrollbar size.
12252     *
12253     * @param scrollBarSize - the scrollbar size
12254     *
12255     * @attr ref android.R.styleable#View_scrollbarSize
12256     */
12257    public void setScrollBarSize(int scrollBarSize) {
12258        getScrollCache().scrollBarSize = scrollBarSize;
12259    }
12260
12261    /**
12262     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12263     * inset. When inset, they add to the padding of the view. And the scrollbars
12264     * can be drawn inside the padding area or on the edge of the view. For example,
12265     * if a view has a background drawable and you want to draw the scrollbars
12266     * inside the padding specified by the drawable, you can use
12267     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12268     * appear at the edge of the view, ignoring the padding, then you can use
12269     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12270     * @param style the style of the scrollbars. Should be one of
12271     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12272     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12273     * @see #SCROLLBARS_INSIDE_OVERLAY
12274     * @see #SCROLLBARS_INSIDE_INSET
12275     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12276     * @see #SCROLLBARS_OUTSIDE_INSET
12277     *
12278     * @attr ref android.R.styleable#View_scrollbarStyle
12279     */
12280    public void setScrollBarStyle(@ScrollBarStyle int style) {
12281        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12282            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12283            computeOpaqueFlags();
12284            resolvePadding();
12285        }
12286    }
12287
12288    /**
12289     * <p>Returns the current scrollbar style.</p>
12290     * @return the current scrollbar style
12291     * @see #SCROLLBARS_INSIDE_OVERLAY
12292     * @see #SCROLLBARS_INSIDE_INSET
12293     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12294     * @see #SCROLLBARS_OUTSIDE_INSET
12295     *
12296     * @attr ref android.R.styleable#View_scrollbarStyle
12297     */
12298    @ViewDebug.ExportedProperty(mapping = {
12299            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12300            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12301            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12302            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12303    })
12304    @ScrollBarStyle
12305    public int getScrollBarStyle() {
12306        return mViewFlags & SCROLLBARS_STYLE_MASK;
12307    }
12308
12309    /**
12310     * <p>Compute the horizontal range that the horizontal scrollbar
12311     * represents.</p>
12312     *
12313     * <p>The range is expressed in arbitrary units that must be the same as the
12314     * units used by {@link #computeHorizontalScrollExtent()} and
12315     * {@link #computeHorizontalScrollOffset()}.</p>
12316     *
12317     * <p>The default range is the drawing width of this view.</p>
12318     *
12319     * @return the total horizontal range represented by the horizontal
12320     *         scrollbar
12321     *
12322     * @see #computeHorizontalScrollExtent()
12323     * @see #computeHorizontalScrollOffset()
12324     * @see android.widget.ScrollBarDrawable
12325     */
12326    protected int computeHorizontalScrollRange() {
12327        return getWidth();
12328    }
12329
12330    /**
12331     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12332     * within the horizontal range. This value is used to compute the position
12333     * of the thumb within the scrollbar's track.</p>
12334     *
12335     * <p>The range is expressed in arbitrary units that must be the same as the
12336     * units used by {@link #computeHorizontalScrollRange()} and
12337     * {@link #computeHorizontalScrollExtent()}.</p>
12338     *
12339     * <p>The default offset is the scroll offset of this view.</p>
12340     *
12341     * @return the horizontal offset of the scrollbar's thumb
12342     *
12343     * @see #computeHorizontalScrollRange()
12344     * @see #computeHorizontalScrollExtent()
12345     * @see android.widget.ScrollBarDrawable
12346     */
12347    protected int computeHorizontalScrollOffset() {
12348        return mScrollX;
12349    }
12350
12351    /**
12352     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12353     * within the horizontal range. This value is used to compute the length
12354     * of the thumb within the scrollbar's track.</p>
12355     *
12356     * <p>The range is expressed in arbitrary units that must be the same as the
12357     * units used by {@link #computeHorizontalScrollRange()} and
12358     * {@link #computeHorizontalScrollOffset()}.</p>
12359     *
12360     * <p>The default extent is the drawing width of this view.</p>
12361     *
12362     * @return the horizontal extent of the scrollbar's thumb
12363     *
12364     * @see #computeHorizontalScrollRange()
12365     * @see #computeHorizontalScrollOffset()
12366     * @see android.widget.ScrollBarDrawable
12367     */
12368    protected int computeHorizontalScrollExtent() {
12369        return getWidth();
12370    }
12371
12372    /**
12373     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12374     *
12375     * <p>The range is expressed in arbitrary units that must be the same as the
12376     * units used by {@link #computeVerticalScrollExtent()} and
12377     * {@link #computeVerticalScrollOffset()}.</p>
12378     *
12379     * @return the total vertical range represented by the vertical scrollbar
12380     *
12381     * <p>The default range is the drawing height of this view.</p>
12382     *
12383     * @see #computeVerticalScrollExtent()
12384     * @see #computeVerticalScrollOffset()
12385     * @see android.widget.ScrollBarDrawable
12386     */
12387    protected int computeVerticalScrollRange() {
12388        return getHeight();
12389    }
12390
12391    /**
12392     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12393     * within the horizontal range. This value is used to compute the position
12394     * of the thumb within the scrollbar's track.</p>
12395     *
12396     * <p>The range is expressed in arbitrary units that must be the same as the
12397     * units used by {@link #computeVerticalScrollRange()} and
12398     * {@link #computeVerticalScrollExtent()}.</p>
12399     *
12400     * <p>The default offset is the scroll offset of this view.</p>
12401     *
12402     * @return the vertical offset of the scrollbar's thumb
12403     *
12404     * @see #computeVerticalScrollRange()
12405     * @see #computeVerticalScrollExtent()
12406     * @see android.widget.ScrollBarDrawable
12407     */
12408    protected int computeVerticalScrollOffset() {
12409        return mScrollY;
12410    }
12411
12412    /**
12413     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12414     * within the vertical range. This value is used to compute the length
12415     * of the thumb within the scrollbar's track.</p>
12416     *
12417     * <p>The range is expressed in arbitrary units that must be the same as the
12418     * units used by {@link #computeVerticalScrollRange()} and
12419     * {@link #computeVerticalScrollOffset()}.</p>
12420     *
12421     * <p>The default extent is the drawing height of this view.</p>
12422     *
12423     * @return the vertical extent of the scrollbar's thumb
12424     *
12425     * @see #computeVerticalScrollRange()
12426     * @see #computeVerticalScrollOffset()
12427     * @see android.widget.ScrollBarDrawable
12428     */
12429    protected int computeVerticalScrollExtent() {
12430        return getHeight();
12431    }
12432
12433    /**
12434     * Check if this view can be scrolled horizontally in a certain direction.
12435     *
12436     * @param direction Negative to check scrolling left, positive to check scrolling right.
12437     * @return true if this view can be scrolled in the specified direction, false otherwise.
12438     */
12439    public boolean canScrollHorizontally(int direction) {
12440        final int offset = computeHorizontalScrollOffset();
12441        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12442        if (range == 0) return false;
12443        if (direction < 0) {
12444            return offset > 0;
12445        } else {
12446            return offset < range - 1;
12447        }
12448    }
12449
12450    /**
12451     * Check if this view can be scrolled vertically in a certain direction.
12452     *
12453     * @param direction Negative to check scrolling up, positive to check scrolling down.
12454     * @return true if this view can be scrolled in the specified direction, false otherwise.
12455     */
12456    public boolean canScrollVertically(int direction) {
12457        final int offset = computeVerticalScrollOffset();
12458        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12459        if (range == 0) return false;
12460        if (direction < 0) {
12461            return offset > 0;
12462        } else {
12463            return offset < range - 1;
12464        }
12465    }
12466
12467    /**
12468     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12469     * scrollbars are painted only if they have been awakened first.</p>
12470     *
12471     * @param canvas the canvas on which to draw the scrollbars
12472     *
12473     * @see #awakenScrollBars(int)
12474     */
12475    protected final void onDrawScrollBars(Canvas canvas) {
12476        // scrollbars are drawn only when the animation is running
12477        final ScrollabilityCache cache = mScrollCache;
12478        if (cache != null) {
12479
12480            int state = cache.state;
12481
12482            if (state == ScrollabilityCache.OFF) {
12483                return;
12484            }
12485
12486            boolean invalidate = false;
12487
12488            if (state == ScrollabilityCache.FADING) {
12489                // We're fading -- get our fade interpolation
12490                if (cache.interpolatorValues == null) {
12491                    cache.interpolatorValues = new float[1];
12492                }
12493
12494                float[] values = cache.interpolatorValues;
12495
12496                // Stops the animation if we're done
12497                if (cache.scrollBarInterpolator.timeToValues(values) ==
12498                        Interpolator.Result.FREEZE_END) {
12499                    cache.state = ScrollabilityCache.OFF;
12500                } else {
12501                    cache.scrollBar.setAlpha(Math.round(values[0]));
12502                }
12503
12504                // This will make the scroll bars inval themselves after
12505                // drawing. We only want this when we're fading so that
12506                // we prevent excessive redraws
12507                invalidate = true;
12508            } else {
12509                // We're just on -- but we may have been fading before so
12510                // reset alpha
12511                cache.scrollBar.setAlpha(255);
12512            }
12513
12514
12515            final int viewFlags = mViewFlags;
12516
12517            final boolean drawHorizontalScrollBar =
12518                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12519            final boolean drawVerticalScrollBar =
12520                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12521                && !isVerticalScrollBarHidden();
12522
12523            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12524                final int width = mRight - mLeft;
12525                final int height = mBottom - mTop;
12526
12527                final ScrollBarDrawable scrollBar = cache.scrollBar;
12528
12529                final int scrollX = mScrollX;
12530                final int scrollY = mScrollY;
12531                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12532
12533                int left;
12534                int top;
12535                int right;
12536                int bottom;
12537
12538                if (drawHorizontalScrollBar) {
12539                    int size = scrollBar.getSize(false);
12540                    if (size <= 0) {
12541                        size = cache.scrollBarSize;
12542                    }
12543
12544                    scrollBar.setParameters(computeHorizontalScrollRange(),
12545                                            computeHorizontalScrollOffset(),
12546                                            computeHorizontalScrollExtent(), false);
12547                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12548                            getVerticalScrollbarWidth() : 0;
12549                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12550                    left = scrollX + (mPaddingLeft & inside);
12551                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12552                    bottom = top + size;
12553                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12554                    if (invalidate) {
12555                        invalidate(left, top, right, bottom);
12556                    }
12557                }
12558
12559                if (drawVerticalScrollBar) {
12560                    int size = scrollBar.getSize(true);
12561                    if (size <= 0) {
12562                        size = cache.scrollBarSize;
12563                    }
12564
12565                    scrollBar.setParameters(computeVerticalScrollRange(),
12566                                            computeVerticalScrollOffset(),
12567                                            computeVerticalScrollExtent(), true);
12568                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12569                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12570                        verticalScrollbarPosition = isLayoutRtl() ?
12571                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12572                    }
12573                    switch (verticalScrollbarPosition) {
12574                        default:
12575                        case SCROLLBAR_POSITION_RIGHT:
12576                            left = scrollX + width - size - (mUserPaddingRight & inside);
12577                            break;
12578                        case SCROLLBAR_POSITION_LEFT:
12579                            left = scrollX + (mUserPaddingLeft & inside);
12580                            break;
12581                    }
12582                    top = scrollY + (mPaddingTop & inside);
12583                    right = left + size;
12584                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12585                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12586                    if (invalidate) {
12587                        invalidate(left, top, right, bottom);
12588                    }
12589                }
12590            }
12591        }
12592    }
12593
12594    /**
12595     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12596     * FastScroller is visible.
12597     * @return whether to temporarily hide the vertical scrollbar
12598     * @hide
12599     */
12600    protected boolean isVerticalScrollBarHidden() {
12601        return false;
12602    }
12603
12604    /**
12605     * <p>Draw the horizontal scrollbar if
12606     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12607     *
12608     * @param canvas the canvas on which to draw the scrollbar
12609     * @param scrollBar the scrollbar's drawable
12610     *
12611     * @see #isHorizontalScrollBarEnabled()
12612     * @see #computeHorizontalScrollRange()
12613     * @see #computeHorizontalScrollExtent()
12614     * @see #computeHorizontalScrollOffset()
12615     * @see android.widget.ScrollBarDrawable
12616     * @hide
12617     */
12618    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12619            int l, int t, int r, int b) {
12620        scrollBar.setBounds(l, t, r, b);
12621        scrollBar.draw(canvas);
12622    }
12623
12624    /**
12625     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12626     * returns true.</p>
12627     *
12628     * @param canvas the canvas on which to draw the scrollbar
12629     * @param scrollBar the scrollbar's drawable
12630     *
12631     * @see #isVerticalScrollBarEnabled()
12632     * @see #computeVerticalScrollRange()
12633     * @see #computeVerticalScrollExtent()
12634     * @see #computeVerticalScrollOffset()
12635     * @see android.widget.ScrollBarDrawable
12636     * @hide
12637     */
12638    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12639            int l, int t, int r, int b) {
12640        scrollBar.setBounds(l, t, r, b);
12641        scrollBar.draw(canvas);
12642    }
12643
12644    /**
12645     * Implement this to do your drawing.
12646     *
12647     * @param canvas the canvas on which the background will be drawn
12648     */
12649    protected void onDraw(Canvas canvas) {
12650    }
12651
12652    /*
12653     * Caller is responsible for calling requestLayout if necessary.
12654     * (This allows addViewInLayout to not request a new layout.)
12655     */
12656    void assignParent(ViewParent parent) {
12657        if (mParent == null) {
12658            mParent = parent;
12659        } else if (parent == null) {
12660            mParent = null;
12661        } else {
12662            throw new RuntimeException("view " + this + " being added, but"
12663                    + " it already has a parent");
12664        }
12665    }
12666
12667    /**
12668     * This is called when the view is attached to a window.  At this point it
12669     * has a Surface and will start drawing.  Note that this function is
12670     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12671     * however it may be called any time before the first onDraw -- including
12672     * before or after {@link #onMeasure(int, int)}.
12673     *
12674     * @see #onDetachedFromWindow()
12675     */
12676    protected void onAttachedToWindow() {
12677        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12678            mParent.requestTransparentRegion(this);
12679        }
12680
12681        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12682            initialAwakenScrollBars();
12683            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12684        }
12685
12686        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12687
12688        jumpDrawablesToCurrentState();
12689
12690        resetSubtreeAccessibilityStateChanged();
12691
12692        if (isFocused()) {
12693            InputMethodManager imm = InputMethodManager.peekInstance();
12694            imm.focusIn(this);
12695        }
12696    }
12697
12698    /**
12699     * Resolve all RTL related properties.
12700     *
12701     * @return true if resolution of RTL properties has been done
12702     *
12703     * @hide
12704     */
12705    public boolean resolveRtlPropertiesIfNeeded() {
12706        if (!needRtlPropertiesResolution()) return false;
12707
12708        // Order is important here: LayoutDirection MUST be resolved first
12709        if (!isLayoutDirectionResolved()) {
12710            resolveLayoutDirection();
12711            resolveLayoutParams();
12712        }
12713        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12714        if (!isTextDirectionResolved()) {
12715            resolveTextDirection();
12716        }
12717        if (!isTextAlignmentResolved()) {
12718            resolveTextAlignment();
12719        }
12720        // Should resolve Drawables before Padding because we need the layout direction of the
12721        // Drawable to correctly resolve Padding.
12722        if (!isDrawablesResolved()) {
12723            resolveDrawables();
12724        }
12725        if (!isPaddingResolved()) {
12726            resolvePadding();
12727        }
12728        onRtlPropertiesChanged(getLayoutDirection());
12729        return true;
12730    }
12731
12732    /**
12733     * Reset resolution of all RTL related properties.
12734     *
12735     * @hide
12736     */
12737    public void resetRtlProperties() {
12738        resetResolvedLayoutDirection();
12739        resetResolvedTextDirection();
12740        resetResolvedTextAlignment();
12741        resetResolvedPadding();
12742        resetResolvedDrawables();
12743    }
12744
12745    /**
12746     * @see #onScreenStateChanged(int)
12747     */
12748    void dispatchScreenStateChanged(int screenState) {
12749        onScreenStateChanged(screenState);
12750    }
12751
12752    /**
12753     * This method is called whenever the state of the screen this view is
12754     * attached to changes. A state change will usually occurs when the screen
12755     * turns on or off (whether it happens automatically or the user does it
12756     * manually.)
12757     *
12758     * @param screenState The new state of the screen. Can be either
12759     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12760     */
12761    public void onScreenStateChanged(int screenState) {
12762    }
12763
12764    /**
12765     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12766     */
12767    private boolean hasRtlSupport() {
12768        return mContext.getApplicationInfo().hasRtlSupport();
12769    }
12770
12771    /**
12772     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12773     * RTL not supported)
12774     */
12775    private boolean isRtlCompatibilityMode() {
12776        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12777        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12778    }
12779
12780    /**
12781     * @return true if RTL properties need resolution.
12782     *
12783     */
12784    private boolean needRtlPropertiesResolution() {
12785        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12786    }
12787
12788    /**
12789     * Called when any RTL property (layout direction or text direction or text alignment) has
12790     * been changed.
12791     *
12792     * Subclasses need to override this method to take care of cached information that depends on the
12793     * resolved layout direction, or to inform child views that inherit their layout direction.
12794     *
12795     * The default implementation does nothing.
12796     *
12797     * @param layoutDirection the direction of the layout
12798     *
12799     * @see #LAYOUT_DIRECTION_LTR
12800     * @see #LAYOUT_DIRECTION_RTL
12801     */
12802    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12803    }
12804
12805    /**
12806     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12807     * that the parent directionality can and will be resolved before its children.
12808     *
12809     * @return true if resolution has been done, false otherwise.
12810     *
12811     * @hide
12812     */
12813    public boolean resolveLayoutDirection() {
12814        // Clear any previous layout direction resolution
12815        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12816
12817        if (hasRtlSupport()) {
12818            // Set resolved depending on layout direction
12819            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12820                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12821                case LAYOUT_DIRECTION_INHERIT:
12822                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12823                    // later to get the correct resolved value
12824                    if (!canResolveLayoutDirection()) return false;
12825
12826                    // Parent has not yet resolved, LTR is still the default
12827                    try {
12828                        if (!mParent.isLayoutDirectionResolved()) return false;
12829
12830                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12831                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12832                        }
12833                    } catch (AbstractMethodError e) {
12834                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12835                                " does not fully implement ViewParent", e);
12836                    }
12837                    break;
12838                case LAYOUT_DIRECTION_RTL:
12839                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12840                    break;
12841                case LAYOUT_DIRECTION_LOCALE:
12842                    if((LAYOUT_DIRECTION_RTL ==
12843                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12844                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12845                    }
12846                    break;
12847                default:
12848                    // Nothing to do, LTR by default
12849            }
12850        }
12851
12852        // Set to resolved
12853        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12854        return true;
12855    }
12856
12857    /**
12858     * Check if layout direction resolution can be done.
12859     *
12860     * @return true if layout direction resolution can be done otherwise return false.
12861     */
12862    public boolean canResolveLayoutDirection() {
12863        switch (getRawLayoutDirection()) {
12864            case LAYOUT_DIRECTION_INHERIT:
12865                if (mParent != null) {
12866                    try {
12867                        return mParent.canResolveLayoutDirection();
12868                    } catch (AbstractMethodError e) {
12869                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12870                                " does not fully implement ViewParent", e);
12871                    }
12872                }
12873                return false;
12874
12875            default:
12876                return true;
12877        }
12878    }
12879
12880    /**
12881     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12882     * {@link #onMeasure(int, int)}.
12883     *
12884     * @hide
12885     */
12886    public void resetResolvedLayoutDirection() {
12887        // Reset the current resolved bits
12888        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12889    }
12890
12891    /**
12892     * @return true if the layout direction is inherited.
12893     *
12894     * @hide
12895     */
12896    public boolean isLayoutDirectionInherited() {
12897        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12898    }
12899
12900    /**
12901     * @return true if layout direction has been resolved.
12902     */
12903    public boolean isLayoutDirectionResolved() {
12904        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12905    }
12906
12907    /**
12908     * Return if padding has been resolved
12909     *
12910     * @hide
12911     */
12912    boolean isPaddingResolved() {
12913        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12914    }
12915
12916    /**
12917     * Resolves padding depending on layout direction, if applicable, and
12918     * recomputes internal padding values to adjust for scroll bars.
12919     *
12920     * @hide
12921     */
12922    public void resolvePadding() {
12923        final int resolvedLayoutDirection = getLayoutDirection();
12924
12925        if (!isRtlCompatibilityMode()) {
12926            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12927            // If start / end padding are defined, they will be resolved (hence overriding) to
12928            // left / right or right / left depending on the resolved layout direction.
12929            // If start / end padding are not defined, use the left / right ones.
12930            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12931                Rect padding = sThreadLocal.get();
12932                if (padding == null) {
12933                    padding = new Rect();
12934                    sThreadLocal.set(padding);
12935                }
12936                mBackground.getPadding(padding);
12937                if (!mLeftPaddingDefined) {
12938                    mUserPaddingLeftInitial = padding.left;
12939                }
12940                if (!mRightPaddingDefined) {
12941                    mUserPaddingRightInitial = padding.right;
12942                }
12943            }
12944            switch (resolvedLayoutDirection) {
12945                case LAYOUT_DIRECTION_RTL:
12946                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12947                        mUserPaddingRight = mUserPaddingStart;
12948                    } else {
12949                        mUserPaddingRight = mUserPaddingRightInitial;
12950                    }
12951                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12952                        mUserPaddingLeft = mUserPaddingEnd;
12953                    } else {
12954                        mUserPaddingLeft = mUserPaddingLeftInitial;
12955                    }
12956                    break;
12957                case LAYOUT_DIRECTION_LTR:
12958                default:
12959                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12960                        mUserPaddingLeft = mUserPaddingStart;
12961                    } else {
12962                        mUserPaddingLeft = mUserPaddingLeftInitial;
12963                    }
12964                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12965                        mUserPaddingRight = mUserPaddingEnd;
12966                    } else {
12967                        mUserPaddingRight = mUserPaddingRightInitial;
12968                    }
12969            }
12970
12971            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12972        }
12973
12974        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12975        onRtlPropertiesChanged(resolvedLayoutDirection);
12976
12977        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12978    }
12979
12980    /**
12981     * Reset the resolved layout direction.
12982     *
12983     * @hide
12984     */
12985    public void resetResolvedPadding() {
12986        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12987    }
12988
12989    /**
12990     * This is called when the view is detached from a window.  At this point it
12991     * no longer has a surface for drawing.
12992     *
12993     * @see #onAttachedToWindow()
12994     */
12995    protected void onDetachedFromWindow() {
12996    }
12997
12998    /**
12999     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13000     * after onDetachedFromWindow().
13001     *
13002     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13003     * The super method should be called at the end of the overriden method to ensure
13004     * subclasses are destroyed first
13005     *
13006     * @hide
13007     */
13008    protected void onDetachedFromWindowInternal() {
13009        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13010        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13011
13012        removeUnsetPressCallback();
13013        removeLongPressCallback();
13014        removePerformClickCallback();
13015        removeSendViewScrolledAccessibilityEventCallback();
13016
13017        destroyDrawingCache();
13018        destroyLayer(false);
13019
13020        cleanupDraw();
13021
13022        mCurrentAnimation = null;
13023    }
13024
13025    private void cleanupDraw() {
13026        resetDisplayList();
13027        if (mAttachInfo != null) {
13028            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13029        }
13030    }
13031
13032    /**
13033     * This method ensures the hardware renderer is in a valid state
13034     * before executing the specified action.
13035     *
13036     * This method will attempt to set a valid state even if the window
13037     * the renderer is attached to was destroyed.
13038     *
13039     * This method is not guaranteed to work. If the hardware renderer
13040     * does not exist or cannot be put in a valid state, this method
13041     * will not executed the specified action.
13042     *
13043     * The specified action is executed synchronously.
13044     *
13045     * @param action The action to execute after the renderer is in a valid state
13046     *
13047     * @return True if the specified Runnable was executed, false otherwise
13048     *
13049     * @hide
13050     */
13051    public boolean executeHardwareAction(Runnable action) {
13052        //noinspection SimplifiableIfStatement
13053        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
13054            return mAttachInfo.mHardwareRenderer.safelyRun(action);
13055        }
13056        return false;
13057    }
13058
13059    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13060    }
13061
13062    /**
13063     * @return The number of times this view has been attached to a window
13064     */
13065    protected int getWindowAttachCount() {
13066        return mWindowAttachCount;
13067    }
13068
13069    /**
13070     * Retrieve a unique token identifying the window this view is attached to.
13071     * @return Return the window's token for use in
13072     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13073     */
13074    public IBinder getWindowToken() {
13075        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13076    }
13077
13078    /**
13079     * Retrieve the {@link WindowId} for the window this view is
13080     * currently attached to.
13081     */
13082    public WindowId getWindowId() {
13083        if (mAttachInfo == null) {
13084            return null;
13085        }
13086        if (mAttachInfo.mWindowId == null) {
13087            try {
13088                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13089                        mAttachInfo.mWindowToken);
13090                mAttachInfo.mWindowId = new WindowId(
13091                        mAttachInfo.mIWindowId);
13092            } catch (RemoteException e) {
13093            }
13094        }
13095        return mAttachInfo.mWindowId;
13096    }
13097
13098    /**
13099     * Retrieve a unique token identifying the top-level "real" window of
13100     * the window that this view is attached to.  That is, this is like
13101     * {@link #getWindowToken}, except if the window this view in is a panel
13102     * window (attached to another containing window), then the token of
13103     * the containing window is returned instead.
13104     *
13105     * @return Returns the associated window token, either
13106     * {@link #getWindowToken()} or the containing window's token.
13107     */
13108    public IBinder getApplicationWindowToken() {
13109        AttachInfo ai = mAttachInfo;
13110        if (ai != null) {
13111            IBinder appWindowToken = ai.mPanelParentWindowToken;
13112            if (appWindowToken == null) {
13113                appWindowToken = ai.mWindowToken;
13114            }
13115            return appWindowToken;
13116        }
13117        return null;
13118    }
13119
13120    /**
13121     * Gets the logical display to which the view's window has been attached.
13122     *
13123     * @return The logical display, or null if the view is not currently attached to a window.
13124     */
13125    public Display getDisplay() {
13126        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13127    }
13128
13129    /**
13130     * Retrieve private session object this view hierarchy is using to
13131     * communicate with the window manager.
13132     * @return the session object to communicate with the window manager
13133     */
13134    /*package*/ IWindowSession getWindowSession() {
13135        return mAttachInfo != null ? mAttachInfo.mSession : null;
13136    }
13137
13138    /**
13139     * @param info the {@link android.view.View.AttachInfo} to associated with
13140     *        this view
13141     */
13142    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13143        //System.out.println("Attached! " + this);
13144        mAttachInfo = info;
13145        if (mOverlay != null) {
13146            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13147        }
13148        mWindowAttachCount++;
13149        // We will need to evaluate the drawable state at least once.
13150        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13151        if (mFloatingTreeObserver != null) {
13152            info.mTreeObserver.merge(mFloatingTreeObserver);
13153            mFloatingTreeObserver = null;
13154        }
13155        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13156            mAttachInfo.mScrollContainers.add(this);
13157            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13158        }
13159        performCollectViewAttributes(mAttachInfo, visibility);
13160        onAttachedToWindow();
13161
13162        ListenerInfo li = mListenerInfo;
13163        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13164                li != null ? li.mOnAttachStateChangeListeners : null;
13165        if (listeners != null && listeners.size() > 0) {
13166            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13167            // perform the dispatching. The iterator is a safe guard against listeners that
13168            // could mutate the list by calling the various add/remove methods. This prevents
13169            // the array from being modified while we iterate it.
13170            for (OnAttachStateChangeListener listener : listeners) {
13171                listener.onViewAttachedToWindow(this);
13172            }
13173        }
13174
13175        int vis = info.mWindowVisibility;
13176        if (vis != GONE) {
13177            onWindowVisibilityChanged(vis);
13178        }
13179        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13180            // If nobody has evaluated the drawable state yet, then do it now.
13181            refreshDrawableState();
13182        }
13183        needGlobalAttributesUpdate(false);
13184    }
13185
13186    void dispatchDetachedFromWindow() {
13187        AttachInfo info = mAttachInfo;
13188        if (info != null) {
13189            int vis = info.mWindowVisibility;
13190            if (vis != GONE) {
13191                onWindowVisibilityChanged(GONE);
13192            }
13193        }
13194
13195        onDetachedFromWindow();
13196        onDetachedFromWindowInternal();
13197
13198        ListenerInfo li = mListenerInfo;
13199        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13200                li != null ? li.mOnAttachStateChangeListeners : null;
13201        if (listeners != null && listeners.size() > 0) {
13202            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13203            // perform the dispatching. The iterator is a safe guard against listeners that
13204            // could mutate the list by calling the various add/remove methods. This prevents
13205            // the array from being modified while we iterate it.
13206            for (OnAttachStateChangeListener listener : listeners) {
13207                listener.onViewDetachedFromWindow(this);
13208            }
13209        }
13210
13211        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13212            mAttachInfo.mScrollContainers.remove(this);
13213            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13214        }
13215
13216        mAttachInfo = null;
13217        if (mOverlay != null) {
13218            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13219        }
13220    }
13221
13222    /**
13223     * Cancel any deferred high-level input events that were previously posted to the event queue.
13224     *
13225     * <p>Many views post high-level events such as click handlers to the event queue
13226     * to run deferred in order to preserve a desired user experience - clearing visible
13227     * pressed states before executing, etc. This method will abort any events of this nature
13228     * that are currently in flight.</p>
13229     *
13230     * <p>Custom views that generate their own high-level deferred input events should override
13231     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13232     *
13233     * <p>This will also cancel pending input events for any child views.</p>
13234     *
13235     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13236     * This will not impact newer events posted after this call that may occur as a result of
13237     * lower-level input events still waiting in the queue. If you are trying to prevent
13238     * double-submitted  events for the duration of some sort of asynchronous transaction
13239     * you should also take other steps to protect against unexpected double inputs e.g. calling
13240     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13241     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13242     */
13243    public final void cancelPendingInputEvents() {
13244        dispatchCancelPendingInputEvents();
13245    }
13246
13247    /**
13248     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13249     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13250     */
13251    void dispatchCancelPendingInputEvents() {
13252        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13253        onCancelPendingInputEvents();
13254        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13255            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13256                    " did not call through to super.onCancelPendingInputEvents()");
13257        }
13258    }
13259
13260    /**
13261     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13262     * a parent view.
13263     *
13264     * <p>This method is responsible for removing any pending high-level input events that were
13265     * posted to the event queue to run later. Custom view classes that post their own deferred
13266     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13267     * {@link android.os.Handler} should override this method, call
13268     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13269     * </p>
13270     */
13271    public void onCancelPendingInputEvents() {
13272        removePerformClickCallback();
13273        cancelLongPress();
13274        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13275    }
13276
13277    /**
13278     * Store this view hierarchy's frozen state into the given container.
13279     *
13280     * @param container The SparseArray in which to save the view's state.
13281     *
13282     * @see #restoreHierarchyState(android.util.SparseArray)
13283     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13284     * @see #onSaveInstanceState()
13285     */
13286    public void saveHierarchyState(SparseArray<Parcelable> container) {
13287        dispatchSaveInstanceState(container);
13288    }
13289
13290    /**
13291     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13292     * this view and its children. May be overridden to modify how freezing happens to a
13293     * view's children; for example, some views may want to not store state for their children.
13294     *
13295     * @param container The SparseArray in which to save the view's state.
13296     *
13297     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13298     * @see #saveHierarchyState(android.util.SparseArray)
13299     * @see #onSaveInstanceState()
13300     */
13301    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13302        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13303            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13304            Parcelable state = onSaveInstanceState();
13305            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13306                throw new IllegalStateException(
13307                        "Derived class did not call super.onSaveInstanceState()");
13308            }
13309            if (state != null) {
13310                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13311                // + ": " + state);
13312                container.put(mID, state);
13313            }
13314        }
13315    }
13316
13317    /**
13318     * Hook allowing a view to generate a representation of its internal state
13319     * that can later be used to create a new instance with that same state.
13320     * This state should only contain information that is not persistent or can
13321     * not be reconstructed later. For example, you will never store your
13322     * current position on screen because that will be computed again when a
13323     * new instance of the view is placed in its view hierarchy.
13324     * <p>
13325     * Some examples of things you may store here: the current cursor position
13326     * in a text view (but usually not the text itself since that is stored in a
13327     * content provider or other persistent storage), the currently selected
13328     * item in a list view.
13329     *
13330     * @return Returns a Parcelable object containing the view's current dynamic
13331     *         state, or null if there is nothing interesting to save. The
13332     *         default implementation returns null.
13333     * @see #onRestoreInstanceState(android.os.Parcelable)
13334     * @see #saveHierarchyState(android.util.SparseArray)
13335     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13336     * @see #setSaveEnabled(boolean)
13337     */
13338    protected Parcelable onSaveInstanceState() {
13339        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13340        return BaseSavedState.EMPTY_STATE;
13341    }
13342
13343    /**
13344     * Restore this view hierarchy's frozen state from the given container.
13345     *
13346     * @param container The SparseArray which holds previously frozen states.
13347     *
13348     * @see #saveHierarchyState(android.util.SparseArray)
13349     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13350     * @see #onRestoreInstanceState(android.os.Parcelable)
13351     */
13352    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13353        dispatchRestoreInstanceState(container);
13354    }
13355
13356    /**
13357     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13358     * state for this view and its children. May be overridden to modify how restoring
13359     * happens to a view's children; for example, some views may want to not store state
13360     * for their children.
13361     *
13362     * @param container The SparseArray which holds previously saved state.
13363     *
13364     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13365     * @see #restoreHierarchyState(android.util.SparseArray)
13366     * @see #onRestoreInstanceState(android.os.Parcelable)
13367     */
13368    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13369        if (mID != NO_ID) {
13370            Parcelable state = container.get(mID);
13371            if (state != null) {
13372                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13373                // + ": " + state);
13374                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13375                onRestoreInstanceState(state);
13376                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13377                    throw new IllegalStateException(
13378                            "Derived class did not call super.onRestoreInstanceState()");
13379                }
13380            }
13381        }
13382    }
13383
13384    /**
13385     * Hook allowing a view to re-apply a representation of its internal state that had previously
13386     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13387     * null state.
13388     *
13389     * @param state The frozen state that had previously been returned by
13390     *        {@link #onSaveInstanceState}.
13391     *
13392     * @see #onSaveInstanceState()
13393     * @see #restoreHierarchyState(android.util.SparseArray)
13394     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13395     */
13396    protected void onRestoreInstanceState(Parcelable state) {
13397        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13398        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13399            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13400                    + "received " + state.getClass().toString() + " instead. This usually happens "
13401                    + "when two views of different type have the same id in the same hierarchy. "
13402                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13403                    + "other views do not use the same id.");
13404        }
13405    }
13406
13407    /**
13408     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13409     *
13410     * @return the drawing start time in milliseconds
13411     */
13412    public long getDrawingTime() {
13413        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13414    }
13415
13416    /**
13417     * <p>Enables or disables the duplication of the parent's state into this view. When
13418     * duplication is enabled, this view gets its drawable state from its parent rather
13419     * than from its own internal properties.</p>
13420     *
13421     * <p>Note: in the current implementation, setting this property to true after the
13422     * view was added to a ViewGroup might have no effect at all. This property should
13423     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13424     *
13425     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13426     * property is enabled, an exception will be thrown.</p>
13427     *
13428     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13429     * parent, these states should not be affected by this method.</p>
13430     *
13431     * @param enabled True to enable duplication of the parent's drawable state, false
13432     *                to disable it.
13433     *
13434     * @see #getDrawableState()
13435     * @see #isDuplicateParentStateEnabled()
13436     */
13437    public void setDuplicateParentStateEnabled(boolean enabled) {
13438        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13439    }
13440
13441    /**
13442     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13443     *
13444     * @return True if this view's drawable state is duplicated from the parent,
13445     *         false otherwise
13446     *
13447     * @see #getDrawableState()
13448     * @see #setDuplicateParentStateEnabled(boolean)
13449     */
13450    public boolean isDuplicateParentStateEnabled() {
13451        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13452    }
13453
13454    /**
13455     * <p>Specifies the type of layer backing this view. The layer can be
13456     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13457     * {@link #LAYER_TYPE_HARDWARE}.</p>
13458     *
13459     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13460     * instance that controls how the layer is composed on screen. The following
13461     * properties of the paint are taken into account when composing the layer:</p>
13462     * <ul>
13463     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13464     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13465     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13466     * </ul>
13467     *
13468     * <p>If this view has an alpha value set to < 1.0 by calling
13469     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13470     * by this view's alpha value.</p>
13471     *
13472     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13473     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13474     * for more information on when and how to use layers.</p>
13475     *
13476     * @param layerType The type of layer to use with this view, must be one of
13477     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13478     *        {@link #LAYER_TYPE_HARDWARE}
13479     * @param paint The paint used to compose the layer. This argument is optional
13480     *        and can be null. It is ignored when the layer type is
13481     *        {@link #LAYER_TYPE_NONE}
13482     *
13483     * @see #getLayerType()
13484     * @see #LAYER_TYPE_NONE
13485     * @see #LAYER_TYPE_SOFTWARE
13486     * @see #LAYER_TYPE_HARDWARE
13487     * @see #setAlpha(float)
13488     *
13489     * @attr ref android.R.styleable#View_layerType
13490     */
13491    public void setLayerType(int layerType, Paint paint) {
13492        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13493            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13494                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13495        }
13496
13497        if (layerType == mLayerType) {
13498            setLayerPaint(paint);
13499            return;
13500        }
13501
13502        // Destroy any previous software drawing cache if needed
13503        switch (mLayerType) {
13504            case LAYER_TYPE_HARDWARE:
13505                destroyLayer(false);
13506                // fall through - non-accelerated views may use software layer mechanism instead
13507            case LAYER_TYPE_SOFTWARE:
13508                destroyDrawingCache();
13509                break;
13510            default:
13511                break;
13512        }
13513
13514        mLayerType = layerType;
13515        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13516        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13517        mLocalDirtyRect = layerDisabled ? null : new Rect();
13518
13519        invalidateParentCaches();
13520        invalidate(true);
13521    }
13522
13523    /**
13524     * Updates the {@link Paint} object used with the current layer (used only if the current
13525     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13526     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13527     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13528     * ensure that the view gets redrawn immediately.
13529     *
13530     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13531     * instance that controls how the layer is composed on screen. The following
13532     * properties of the paint are taken into account when composing the layer:</p>
13533     * <ul>
13534     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13535     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13536     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13537     * </ul>
13538     *
13539     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13540     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13541     *
13542     * @param paint The paint used to compose the layer. This argument is optional
13543     *        and can be null. It is ignored when the layer type is
13544     *        {@link #LAYER_TYPE_NONE}
13545     *
13546     * @see #setLayerType(int, android.graphics.Paint)
13547     */
13548    public void setLayerPaint(Paint paint) {
13549        int layerType = getLayerType();
13550        if (layerType != LAYER_TYPE_NONE) {
13551            mLayerPaint = paint == null ? new Paint() : paint;
13552            if (layerType == LAYER_TYPE_HARDWARE) {
13553                HardwareLayer layer = getHardwareLayer();
13554                if (layer != null) {
13555                    layer.setLayerPaint(mLayerPaint);
13556                }
13557                invalidateViewProperty(false, false);
13558            } else {
13559                invalidate();
13560            }
13561        }
13562    }
13563
13564    /**
13565     * Indicates whether this view has a static layer. A view with layer type
13566     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13567     * dynamic.
13568     */
13569    boolean hasStaticLayer() {
13570        return true;
13571    }
13572
13573    /**
13574     * Indicates what type of layer is currently associated with this view. By default
13575     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13576     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13577     * for more information on the different types of layers.
13578     *
13579     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13580     *         {@link #LAYER_TYPE_HARDWARE}
13581     *
13582     * @see #setLayerType(int, android.graphics.Paint)
13583     * @see #buildLayer()
13584     * @see #LAYER_TYPE_NONE
13585     * @see #LAYER_TYPE_SOFTWARE
13586     * @see #LAYER_TYPE_HARDWARE
13587     */
13588    public int getLayerType() {
13589        return mLayerType;
13590    }
13591
13592    /**
13593     * Forces this view's layer to be created and this view to be rendered
13594     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13595     * invoking this method will have no effect.
13596     *
13597     * This method can for instance be used to render a view into its layer before
13598     * starting an animation. If this view is complex, rendering into the layer
13599     * before starting the animation will avoid skipping frames.
13600     *
13601     * @throws IllegalStateException If this view is not attached to a window
13602     *
13603     * @see #setLayerType(int, android.graphics.Paint)
13604     */
13605    public void buildLayer() {
13606        if (mLayerType == LAYER_TYPE_NONE) return;
13607
13608        final AttachInfo attachInfo = mAttachInfo;
13609        if (attachInfo == null) {
13610            throw new IllegalStateException("This view must be attached to a window first");
13611        }
13612
13613        switch (mLayerType) {
13614            case LAYER_TYPE_HARDWARE:
13615                getHardwareLayer();
13616                // TODO: We need a better way to handle this case
13617                // If views have registered pre-draw listeners they need
13618                // to be notified before we build the layer. Those listeners
13619                // may however rely on other events to happen first so we
13620                // cannot just invoke them here until they don't cancel the
13621                // current frame
13622                if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13623                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13624                }
13625                break;
13626            case LAYER_TYPE_SOFTWARE:
13627                buildDrawingCache(true);
13628                break;
13629        }
13630    }
13631
13632    /**
13633     * <p>Returns a hardware layer that can be used to draw this view again
13634     * without executing its draw method.</p>
13635     *
13636     * @return A HardwareLayer ready to render, or null if an error occurred.
13637     */
13638    HardwareLayer getHardwareLayer() {
13639        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13640                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13641            return null;
13642        }
13643
13644        final int width = mRight - mLeft;
13645        final int height = mBottom - mTop;
13646
13647        if (width == 0 || height == 0) {
13648            return null;
13649        }
13650
13651        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13652            if (mHardwareLayer == null) {
13653                mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
13654                        width, height);
13655                mLocalDirtyRect.set(0, 0, width, height);
13656            } else if (mHardwareLayer.isValid()) {
13657                // This should not be necessary but applications that change
13658                // the parameters of their background drawable without calling
13659                // this.setBackground(Drawable) can leave the view in a bad state
13660                // (for instance isOpaque() returns true, but the background is
13661                // not opaque.)
13662                computeOpaqueFlags();
13663
13664                if (mHardwareLayer.prepare(width, height, isOpaque())) {
13665                    mLocalDirtyRect.set(0, 0, width, height);
13666                }
13667            }
13668
13669            // The layer is not valid if the underlying GPU resources cannot be allocated
13670            mHardwareLayer.flushChanges();
13671            if (!mHardwareLayer.isValid()) {
13672                return null;
13673            }
13674
13675            mHardwareLayer.setLayerPaint(mLayerPaint);
13676            RenderNode displayList = mHardwareLayer.startRecording();
13677            if (getDisplayList(displayList, true) != displayList) {
13678                throw new IllegalStateException("getDisplayList() didn't return"
13679                        + " the input displaylist for a hardware layer!");
13680            }
13681            mHardwareLayer.endRecording(mLocalDirtyRect);
13682            mLocalDirtyRect.setEmpty();
13683        }
13684
13685        return mHardwareLayer;
13686    }
13687
13688    /**
13689     * Destroys this View's hardware layer if possible.
13690     *
13691     * @return True if the layer was destroyed, false otherwise.
13692     *
13693     * @see #setLayerType(int, android.graphics.Paint)
13694     * @see #LAYER_TYPE_HARDWARE
13695     */
13696    boolean destroyLayer(boolean valid) {
13697        if (mHardwareLayer != null) {
13698            mHardwareLayer.destroy();
13699            mHardwareLayer = null;
13700
13701            invalidate(true);
13702            invalidateParentCaches();
13703            return true;
13704        }
13705        return false;
13706    }
13707
13708    /**
13709     * Destroys all hardware rendering resources. This method is invoked
13710     * when the system needs to reclaim resources. Upon execution of this
13711     * method, you should free any OpenGL resources created by the view.
13712     *
13713     * Note: you <strong>must</strong> call
13714     * <code>super.destroyHardwareResources()</code> when overriding
13715     * this method.
13716     *
13717     * @hide
13718     */
13719    protected void destroyHardwareResources() {
13720        resetDisplayList();
13721        destroyLayer(true);
13722    }
13723
13724    /**
13725     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13726     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13727     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13728     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13729     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13730     * null.</p>
13731     *
13732     * <p>Enabling the drawing cache is similar to
13733     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13734     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13735     * drawing cache has no effect on rendering because the system uses a different mechanism
13736     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13737     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13738     * for information on how to enable software and hardware layers.</p>
13739     *
13740     * <p>This API can be used to manually generate
13741     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13742     * {@link #getDrawingCache()}.</p>
13743     *
13744     * @param enabled true to enable the drawing cache, false otherwise
13745     *
13746     * @see #isDrawingCacheEnabled()
13747     * @see #getDrawingCache()
13748     * @see #buildDrawingCache()
13749     * @see #setLayerType(int, android.graphics.Paint)
13750     */
13751    public void setDrawingCacheEnabled(boolean enabled) {
13752        mCachingFailed = false;
13753        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13754    }
13755
13756    /**
13757     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13758     *
13759     * @return true if the drawing cache is enabled
13760     *
13761     * @see #setDrawingCacheEnabled(boolean)
13762     * @see #getDrawingCache()
13763     */
13764    @ViewDebug.ExportedProperty(category = "drawing")
13765    public boolean isDrawingCacheEnabled() {
13766        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13767    }
13768
13769    /**
13770     * Debugging utility which recursively outputs the dirty state of a view and its
13771     * descendants.
13772     *
13773     * @hide
13774     */
13775    @SuppressWarnings({"UnusedDeclaration"})
13776    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13777        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13778                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13779                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13780                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13781        if (clear) {
13782            mPrivateFlags &= clearMask;
13783        }
13784        if (this instanceof ViewGroup) {
13785            ViewGroup parent = (ViewGroup) this;
13786            final int count = parent.getChildCount();
13787            for (int i = 0; i < count; i++) {
13788                final View child = parent.getChildAt(i);
13789                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13790            }
13791        }
13792    }
13793
13794    /**
13795     * This method is used by ViewGroup to cause its children to restore or recreate their
13796     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13797     * to recreate its own display list, which would happen if it went through the normal
13798     * draw/dispatchDraw mechanisms.
13799     *
13800     * @hide
13801     */
13802    protected void dispatchGetDisplayList() {}
13803
13804    /**
13805     * A view that is not attached or hardware accelerated cannot create a display list.
13806     * This method checks these conditions and returns the appropriate result.
13807     *
13808     * @return true if view has the ability to create a display list, false otherwise.
13809     *
13810     * @hide
13811     */
13812    public boolean canHaveDisplayList() {
13813        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13814    }
13815
13816    /**
13817     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13818     * Otherwise, the same display list will be returned (after having been rendered into
13819     * along the way, depending on the invalidation state of the view).
13820     *
13821     * @param displayList The previous version of this displayList, could be null.
13822     * @param isLayer Whether the requester of the display list is a layer. If so,
13823     * the view will avoid creating a layer inside the resulting display list.
13824     * @return A new or reused DisplayList object.
13825     */
13826    private RenderNode getDisplayList(RenderNode displayList, boolean isLayer) {
13827        final HardwareRenderer renderer = getHardwareRenderer();
13828        if (renderer == null || !canHaveDisplayList()) {
13829            return null;
13830        }
13831
13832        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13833                displayList == null || !displayList.isValid() ||
13834                (!isLayer && mRecreateDisplayList))) {
13835            // Don't need to recreate the display list, just need to tell our
13836            // children to restore/recreate theirs
13837            if (displayList != null && displayList.isValid() &&
13838                    !isLayer && !mRecreateDisplayList) {
13839                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13840                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13841                dispatchGetDisplayList();
13842
13843                return displayList;
13844            }
13845
13846            if (!isLayer) {
13847                // If we got here, we're recreating it. Mark it as such to ensure that
13848                // we copy in child display lists into ours in drawChild()
13849                mRecreateDisplayList = true;
13850            }
13851            if (displayList == null) {
13852                displayList = RenderNode.create(getClass().getName());
13853                // If we're creating a new display list, make sure our parent gets invalidated
13854                // since they will need to recreate their display list to account for this
13855                // new child display list.
13856                invalidateParentCaches();
13857            }
13858
13859            boolean caching = false;
13860            int width = mRight - mLeft;
13861            int height = mBottom - mTop;
13862            int layerType = getLayerType();
13863
13864            final HardwareCanvas canvas = displayList.start(width, height);
13865
13866            try {
13867                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13868                    if (layerType == LAYER_TYPE_HARDWARE) {
13869                        final HardwareLayer layer = getHardwareLayer();
13870                        if (layer != null && layer.isValid()) {
13871                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13872                        } else {
13873                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13874                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13875                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13876                        }
13877                        caching = true;
13878                    } else {
13879                        buildDrawingCache(true);
13880                        Bitmap cache = getDrawingCache(true);
13881                        if (cache != null) {
13882                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13883                            caching = true;
13884                        }
13885                    }
13886                } else {
13887
13888                    computeScroll();
13889
13890                    canvas.translate(-mScrollX, -mScrollY);
13891                    if (!isLayer) {
13892                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13893                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13894                    }
13895
13896                    // Fast path for layouts with no backgrounds
13897                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13898                        dispatchDraw(canvas);
13899                        if (mOverlay != null && !mOverlay.isEmpty()) {
13900                            mOverlay.getOverlayView().draw(canvas);
13901                        }
13902                    } else {
13903                        draw(canvas);
13904                    }
13905                }
13906            } finally {
13907                displayList.end(renderer, canvas);
13908                displayList.setCaching(caching);
13909                if (isLayer) {
13910                    displayList.setLeftTopRightBottom(0, 0, width, height);
13911                } else {
13912                    setDisplayListProperties(displayList);
13913                }
13914
13915                if (renderer != getHardwareRenderer()) {
13916                    Log.w(VIEW_LOG_TAG, "View was detached during a draw() call!");
13917                    // TODO: Should this be elevated to a crash?
13918                    // For now have it behaves the same as it previously did, it
13919                    // will result in the DisplayListData being destroyed later
13920                    // than it could be but oh well...
13921                }
13922            }
13923        } else if (!isLayer) {
13924            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13925            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13926        }
13927
13928        return displayList;
13929    }
13930
13931    /**
13932     * <p>Returns a display list that can be used to draw this view again
13933     * without executing its draw method.</p>
13934     *
13935     * @return A DisplayList ready to replay, or null if caching is not enabled.
13936     *
13937     * @hide
13938     */
13939    public RenderNode getDisplayList() {
13940        mDisplayList = getDisplayList(mDisplayList, false);
13941        return mDisplayList;
13942    }
13943
13944    private void resetDisplayList() {
13945        if (mDisplayList != null && mDisplayList.isValid()) {
13946            mDisplayList.destroyDisplayListData();
13947        }
13948
13949        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
13950            mBackgroundDisplayList.destroyDisplayListData();
13951        }
13952    }
13953
13954    /**
13955     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13956     *
13957     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13958     *
13959     * @see #getDrawingCache(boolean)
13960     */
13961    public Bitmap getDrawingCache() {
13962        return getDrawingCache(false);
13963    }
13964
13965    /**
13966     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13967     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13968     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13969     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13970     * request the drawing cache by calling this method and draw it on screen if the
13971     * returned bitmap is not null.</p>
13972     *
13973     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13974     * this method will create a bitmap of the same size as this view. Because this bitmap
13975     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13976     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13977     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13978     * size than the view. This implies that your application must be able to handle this
13979     * size.</p>
13980     *
13981     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13982     *        the current density of the screen when the application is in compatibility
13983     *        mode.
13984     *
13985     * @return A bitmap representing this view or null if cache is disabled.
13986     *
13987     * @see #setDrawingCacheEnabled(boolean)
13988     * @see #isDrawingCacheEnabled()
13989     * @see #buildDrawingCache(boolean)
13990     * @see #destroyDrawingCache()
13991     */
13992    public Bitmap getDrawingCache(boolean autoScale) {
13993        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13994            return null;
13995        }
13996        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13997            buildDrawingCache(autoScale);
13998        }
13999        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14000    }
14001
14002    /**
14003     * <p>Frees the resources used by the drawing cache. If you call
14004     * {@link #buildDrawingCache()} manually without calling
14005     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14006     * should cleanup the cache with this method afterwards.</p>
14007     *
14008     * @see #setDrawingCacheEnabled(boolean)
14009     * @see #buildDrawingCache()
14010     * @see #getDrawingCache()
14011     */
14012    public void destroyDrawingCache() {
14013        if (mDrawingCache != null) {
14014            mDrawingCache.recycle();
14015            mDrawingCache = null;
14016        }
14017        if (mUnscaledDrawingCache != null) {
14018            mUnscaledDrawingCache.recycle();
14019            mUnscaledDrawingCache = null;
14020        }
14021    }
14022
14023    /**
14024     * Setting a solid background color for the drawing cache's bitmaps will improve
14025     * performance and memory usage. Note, though that this should only be used if this
14026     * view will always be drawn on top of a solid color.
14027     *
14028     * @param color The background color to use for the drawing cache's bitmap
14029     *
14030     * @see #setDrawingCacheEnabled(boolean)
14031     * @see #buildDrawingCache()
14032     * @see #getDrawingCache()
14033     */
14034    public void setDrawingCacheBackgroundColor(int color) {
14035        if (color != mDrawingCacheBackgroundColor) {
14036            mDrawingCacheBackgroundColor = color;
14037            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14038        }
14039    }
14040
14041    /**
14042     * @see #setDrawingCacheBackgroundColor(int)
14043     *
14044     * @return The background color to used for the drawing cache's bitmap
14045     */
14046    public int getDrawingCacheBackgroundColor() {
14047        return mDrawingCacheBackgroundColor;
14048    }
14049
14050    /**
14051     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14052     *
14053     * @see #buildDrawingCache(boolean)
14054     */
14055    public void buildDrawingCache() {
14056        buildDrawingCache(false);
14057    }
14058
14059    /**
14060     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14061     *
14062     * <p>If you call {@link #buildDrawingCache()} manually without calling
14063     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14064     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14065     *
14066     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14067     * this method will create a bitmap of the same size as this view. Because this bitmap
14068     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14069     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14070     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14071     * size than the view. This implies that your application must be able to handle this
14072     * size.</p>
14073     *
14074     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14075     * you do not need the drawing cache bitmap, calling this method will increase memory
14076     * usage and cause the view to be rendered in software once, thus negatively impacting
14077     * performance.</p>
14078     *
14079     * @see #getDrawingCache()
14080     * @see #destroyDrawingCache()
14081     */
14082    public void buildDrawingCache(boolean autoScale) {
14083        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14084                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14085            mCachingFailed = false;
14086
14087            int width = mRight - mLeft;
14088            int height = mBottom - mTop;
14089
14090            final AttachInfo attachInfo = mAttachInfo;
14091            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14092
14093            if (autoScale && scalingRequired) {
14094                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14095                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14096            }
14097
14098            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14099            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14100            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14101
14102            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14103            final long drawingCacheSize =
14104                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14105            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14106                if (width > 0 && height > 0) {
14107                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14108                            + projectedBitmapSize + " bytes, only "
14109                            + drawingCacheSize + " available");
14110                }
14111                destroyDrawingCache();
14112                mCachingFailed = true;
14113                return;
14114            }
14115
14116            boolean clear = true;
14117            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14118
14119            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14120                Bitmap.Config quality;
14121                if (!opaque) {
14122                    // Never pick ARGB_4444 because it looks awful
14123                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14124                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14125                        case DRAWING_CACHE_QUALITY_AUTO:
14126                        case DRAWING_CACHE_QUALITY_LOW:
14127                        case DRAWING_CACHE_QUALITY_HIGH:
14128                        default:
14129                            quality = Bitmap.Config.ARGB_8888;
14130                            break;
14131                    }
14132                } else {
14133                    // Optimization for translucent windows
14134                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14135                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14136                }
14137
14138                // Try to cleanup memory
14139                if (bitmap != null) bitmap.recycle();
14140
14141                try {
14142                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14143                            width, height, quality);
14144                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14145                    if (autoScale) {
14146                        mDrawingCache = bitmap;
14147                    } else {
14148                        mUnscaledDrawingCache = bitmap;
14149                    }
14150                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14151                } catch (OutOfMemoryError e) {
14152                    // If there is not enough memory to create the bitmap cache, just
14153                    // ignore the issue as bitmap caches are not required to draw the
14154                    // view hierarchy
14155                    if (autoScale) {
14156                        mDrawingCache = null;
14157                    } else {
14158                        mUnscaledDrawingCache = null;
14159                    }
14160                    mCachingFailed = true;
14161                    return;
14162                }
14163
14164                clear = drawingCacheBackgroundColor != 0;
14165            }
14166
14167            Canvas canvas;
14168            if (attachInfo != null) {
14169                canvas = attachInfo.mCanvas;
14170                if (canvas == null) {
14171                    canvas = new Canvas();
14172                }
14173                canvas.setBitmap(bitmap);
14174                // Temporarily clobber the cached Canvas in case one of our children
14175                // is also using a drawing cache. Without this, the children would
14176                // steal the canvas by attaching their own bitmap to it and bad, bad
14177                // thing would happen (invisible views, corrupted drawings, etc.)
14178                attachInfo.mCanvas = null;
14179            } else {
14180                // This case should hopefully never or seldom happen
14181                canvas = new Canvas(bitmap);
14182            }
14183
14184            if (clear) {
14185                bitmap.eraseColor(drawingCacheBackgroundColor);
14186            }
14187
14188            computeScroll();
14189            final int restoreCount = canvas.save();
14190
14191            if (autoScale && scalingRequired) {
14192                final float scale = attachInfo.mApplicationScale;
14193                canvas.scale(scale, scale);
14194            }
14195
14196            canvas.translate(-mScrollX, -mScrollY);
14197
14198            mPrivateFlags |= PFLAG_DRAWN;
14199            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14200                    mLayerType != LAYER_TYPE_NONE) {
14201                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14202            }
14203
14204            // Fast path for layouts with no backgrounds
14205            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14206                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14207                dispatchDraw(canvas);
14208                if (mOverlay != null && !mOverlay.isEmpty()) {
14209                    mOverlay.getOverlayView().draw(canvas);
14210                }
14211            } else {
14212                draw(canvas);
14213            }
14214
14215            canvas.restoreToCount(restoreCount);
14216            canvas.setBitmap(null);
14217
14218            if (attachInfo != null) {
14219                // Restore the cached Canvas for our siblings
14220                attachInfo.mCanvas = canvas;
14221            }
14222        }
14223    }
14224
14225    /**
14226     * Create a snapshot of the view into a bitmap.  We should probably make
14227     * some form of this public, but should think about the API.
14228     */
14229    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14230        int width = mRight - mLeft;
14231        int height = mBottom - mTop;
14232
14233        final AttachInfo attachInfo = mAttachInfo;
14234        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14235        width = (int) ((width * scale) + 0.5f);
14236        height = (int) ((height * scale) + 0.5f);
14237
14238        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14239                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14240        if (bitmap == null) {
14241            throw new OutOfMemoryError();
14242        }
14243
14244        Resources resources = getResources();
14245        if (resources != null) {
14246            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14247        }
14248
14249        Canvas canvas;
14250        if (attachInfo != null) {
14251            canvas = attachInfo.mCanvas;
14252            if (canvas == null) {
14253                canvas = new Canvas();
14254            }
14255            canvas.setBitmap(bitmap);
14256            // Temporarily clobber the cached Canvas in case one of our children
14257            // is also using a drawing cache. Without this, the children would
14258            // steal the canvas by attaching their own bitmap to it and bad, bad
14259            // things would happen (invisible views, corrupted drawings, etc.)
14260            attachInfo.mCanvas = null;
14261        } else {
14262            // This case should hopefully never or seldom happen
14263            canvas = new Canvas(bitmap);
14264        }
14265
14266        if ((backgroundColor & 0xff000000) != 0) {
14267            bitmap.eraseColor(backgroundColor);
14268        }
14269
14270        computeScroll();
14271        final int restoreCount = canvas.save();
14272        canvas.scale(scale, scale);
14273        canvas.translate(-mScrollX, -mScrollY);
14274
14275        // Temporarily remove the dirty mask
14276        int flags = mPrivateFlags;
14277        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14278
14279        // Fast path for layouts with no backgrounds
14280        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14281            dispatchDraw(canvas);
14282            if (mOverlay != null && !mOverlay.isEmpty()) {
14283                mOverlay.getOverlayView().draw(canvas);
14284            }
14285        } else {
14286            draw(canvas);
14287        }
14288
14289        mPrivateFlags = flags;
14290
14291        canvas.restoreToCount(restoreCount);
14292        canvas.setBitmap(null);
14293
14294        if (attachInfo != null) {
14295            // Restore the cached Canvas for our siblings
14296            attachInfo.mCanvas = canvas;
14297        }
14298
14299        return bitmap;
14300    }
14301
14302    /**
14303     * Indicates whether this View is currently in edit mode. A View is usually
14304     * in edit mode when displayed within a developer tool. For instance, if
14305     * this View is being drawn by a visual user interface builder, this method
14306     * should return true.
14307     *
14308     * Subclasses should check the return value of this method to provide
14309     * different behaviors if their normal behavior might interfere with the
14310     * host environment. For instance: the class spawns a thread in its
14311     * constructor, the drawing code relies on device-specific features, etc.
14312     *
14313     * This method is usually checked in the drawing code of custom widgets.
14314     *
14315     * @return True if this View is in edit mode, false otherwise.
14316     */
14317    public boolean isInEditMode() {
14318        return false;
14319    }
14320
14321    /**
14322     * If the View draws content inside its padding and enables fading edges,
14323     * it needs to support padding offsets. Padding offsets are added to the
14324     * fading edges to extend the length of the fade so that it covers pixels
14325     * drawn inside the padding.
14326     *
14327     * Subclasses of this class should override this method if they need
14328     * to draw content inside the padding.
14329     *
14330     * @return True if padding offset must be applied, false otherwise.
14331     *
14332     * @see #getLeftPaddingOffset()
14333     * @see #getRightPaddingOffset()
14334     * @see #getTopPaddingOffset()
14335     * @see #getBottomPaddingOffset()
14336     *
14337     * @since CURRENT
14338     */
14339    protected boolean isPaddingOffsetRequired() {
14340        return false;
14341    }
14342
14343    /**
14344     * Amount by which to extend the left fading region. Called only when
14345     * {@link #isPaddingOffsetRequired()} returns true.
14346     *
14347     * @return The left padding offset in pixels.
14348     *
14349     * @see #isPaddingOffsetRequired()
14350     *
14351     * @since CURRENT
14352     */
14353    protected int getLeftPaddingOffset() {
14354        return 0;
14355    }
14356
14357    /**
14358     * Amount by which to extend the right fading region. Called only when
14359     * {@link #isPaddingOffsetRequired()} returns true.
14360     *
14361     * @return The right padding offset in pixels.
14362     *
14363     * @see #isPaddingOffsetRequired()
14364     *
14365     * @since CURRENT
14366     */
14367    protected int getRightPaddingOffset() {
14368        return 0;
14369    }
14370
14371    /**
14372     * Amount by which to extend the top fading region. Called only when
14373     * {@link #isPaddingOffsetRequired()} returns true.
14374     *
14375     * @return The top padding offset in pixels.
14376     *
14377     * @see #isPaddingOffsetRequired()
14378     *
14379     * @since CURRENT
14380     */
14381    protected int getTopPaddingOffset() {
14382        return 0;
14383    }
14384
14385    /**
14386     * Amount by which to extend the bottom fading region. Called only when
14387     * {@link #isPaddingOffsetRequired()} returns true.
14388     *
14389     * @return The bottom padding offset in pixels.
14390     *
14391     * @see #isPaddingOffsetRequired()
14392     *
14393     * @since CURRENT
14394     */
14395    protected int getBottomPaddingOffset() {
14396        return 0;
14397    }
14398
14399    /**
14400     * @hide
14401     * @param offsetRequired
14402     */
14403    protected int getFadeTop(boolean offsetRequired) {
14404        int top = mPaddingTop;
14405        if (offsetRequired) top += getTopPaddingOffset();
14406        return top;
14407    }
14408
14409    /**
14410     * @hide
14411     * @param offsetRequired
14412     */
14413    protected int getFadeHeight(boolean offsetRequired) {
14414        int padding = mPaddingTop;
14415        if (offsetRequired) padding += getTopPaddingOffset();
14416        return mBottom - mTop - mPaddingBottom - padding;
14417    }
14418
14419    /**
14420     * <p>Indicates whether this view is attached to a hardware accelerated
14421     * window or not.</p>
14422     *
14423     * <p>Even if this method returns true, it does not mean that every call
14424     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14425     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14426     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14427     * window is hardware accelerated,
14428     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14429     * return false, and this method will return true.</p>
14430     *
14431     * @return True if the view is attached to a window and the window is
14432     *         hardware accelerated; false in any other case.
14433     */
14434    public boolean isHardwareAccelerated() {
14435        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14436    }
14437
14438    /**
14439     * Sets a rectangular area on this view to which the view will be clipped
14440     * when it is drawn. Setting the value to null will remove the clip bounds
14441     * and the view will draw normally, using its full bounds.
14442     *
14443     * @param clipBounds The rectangular area, in the local coordinates of
14444     * this view, to which future drawing operations will be clipped.
14445     */
14446    public void setClipBounds(Rect clipBounds) {
14447        if (clipBounds != null) {
14448            if (clipBounds.equals(mClipBounds)) {
14449                return;
14450            }
14451            if (mClipBounds == null) {
14452                invalidate();
14453                mClipBounds = new Rect(clipBounds);
14454            } else {
14455                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14456                        Math.min(mClipBounds.top, clipBounds.top),
14457                        Math.max(mClipBounds.right, clipBounds.right),
14458                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14459                mClipBounds.set(clipBounds);
14460            }
14461        } else {
14462            if (mClipBounds != null) {
14463                invalidate();
14464                mClipBounds = null;
14465            }
14466        }
14467    }
14468
14469    /**
14470     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14471     *
14472     * @return A copy of the current clip bounds if clip bounds are set,
14473     * otherwise null.
14474     */
14475    public Rect getClipBounds() {
14476        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14477    }
14478
14479    /**
14480     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14481     * case of an active Animation being run on the view.
14482     */
14483    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14484            Animation a, boolean scalingRequired) {
14485        Transformation invalidationTransform;
14486        final int flags = parent.mGroupFlags;
14487        final boolean initialized = a.isInitialized();
14488        if (!initialized) {
14489            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14490            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14491            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14492            onAnimationStart();
14493        }
14494
14495        final Transformation t = parent.getChildTransformation();
14496        boolean more = a.getTransformation(drawingTime, t, 1f);
14497        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14498            if (parent.mInvalidationTransformation == null) {
14499                parent.mInvalidationTransformation = new Transformation();
14500            }
14501            invalidationTransform = parent.mInvalidationTransformation;
14502            a.getTransformation(drawingTime, invalidationTransform, 1f);
14503        } else {
14504            invalidationTransform = t;
14505        }
14506
14507        if (more) {
14508            if (!a.willChangeBounds()) {
14509                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14510                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14511                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14512                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14513                    // The child need to draw an animation, potentially offscreen, so
14514                    // make sure we do not cancel invalidate requests
14515                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14516                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14517                }
14518            } else {
14519                if (parent.mInvalidateRegion == null) {
14520                    parent.mInvalidateRegion = new RectF();
14521                }
14522                final RectF region = parent.mInvalidateRegion;
14523                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14524                        invalidationTransform);
14525
14526                // The child need to draw an animation, potentially offscreen, so
14527                // make sure we do not cancel invalidate requests
14528                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14529
14530                final int left = mLeft + (int) region.left;
14531                final int top = mTop + (int) region.top;
14532                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14533                        top + (int) (region.height() + .5f));
14534            }
14535        }
14536        return more;
14537    }
14538
14539    /**
14540     * This method is called by getDisplayList() when a display list is created or re-rendered.
14541     * It sets or resets the current value of all properties on that display list (resetting is
14542     * necessary when a display list is being re-created, because we need to make sure that
14543     * previously-set transform values
14544     */
14545    void setDisplayListProperties(RenderNode displayList) {
14546        if (displayList != null) {
14547            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14548            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14549            if (mParent instanceof ViewGroup) {
14550                displayList.setClipToBounds(
14551                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14552            }
14553            displayList.setOutline(mOutline);
14554            displayList.setClipToOutline(getClipToOutline());
14555            float alpha = 1;
14556            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14557                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14558                ViewGroup parentVG = (ViewGroup) mParent;
14559                final Transformation t = parentVG.getChildTransformation();
14560                if (parentVG.getChildStaticTransformation(this, t)) {
14561                    final int transformType = t.getTransformationType();
14562                    if (transformType != Transformation.TYPE_IDENTITY) {
14563                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14564                            alpha = t.getAlpha();
14565                        }
14566                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14567                            displayList.setStaticMatrix(t.getMatrix());
14568                        }
14569                    }
14570                }
14571            }
14572            if (mTransformationInfo != null) {
14573                alpha *= getFinalAlpha();
14574                if (alpha < 1) {
14575                    final int multipliedAlpha = (int) (255 * alpha);
14576                    if (onSetAlpha(multipliedAlpha)) {
14577                        alpha = 1;
14578                    }
14579                }
14580                displayList.setTransformationInfo(alpha,
14581                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14582                        mTransformationInfo.mTranslationZ,
14583                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14584                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14585                        mTransformationInfo.mScaleY);
14586                if (mTransformationInfo.mCamera == null) {
14587                    mTransformationInfo.mCamera = new Camera();
14588                    mTransformationInfo.matrix3D = new Matrix();
14589                }
14590                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14591                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14592                    displayList.setPivotX(getPivotX());
14593                    displayList.setPivotY(getPivotY());
14594                }
14595            } else if (alpha < 1) {
14596                displayList.setAlpha(alpha);
14597            }
14598        }
14599    }
14600
14601    /**
14602     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14603     * This draw() method is an implementation detail and is not intended to be overridden or
14604     * to be called from anywhere else other than ViewGroup.drawChild().
14605     */
14606    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14607        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14608        boolean more = false;
14609        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14610        final int flags = parent.mGroupFlags;
14611
14612        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14613            parent.getChildTransformation().clear();
14614            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14615        }
14616
14617        Transformation transformToApply = null;
14618        boolean concatMatrix = false;
14619
14620        boolean scalingRequired = false;
14621        boolean caching;
14622        int layerType = getLayerType();
14623
14624        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14625        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14626                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14627            caching = true;
14628            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14629            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14630        } else {
14631            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14632        }
14633
14634        final Animation a = getAnimation();
14635        if (a != null) {
14636            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14637            concatMatrix = a.willChangeTransformationMatrix();
14638            if (concatMatrix) {
14639                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14640            }
14641            transformToApply = parent.getChildTransformation();
14642        } else {
14643            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14644                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14645                // No longer animating: clear out old animation matrix
14646                mDisplayList.setAnimationMatrix(null);
14647                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14648            }
14649            if (!useDisplayListProperties &&
14650                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14651                final Transformation t = parent.getChildTransformation();
14652                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14653                if (hasTransform) {
14654                    final int transformType = t.getTransformationType();
14655                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14656                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14657                }
14658            }
14659        }
14660
14661        concatMatrix |= !childHasIdentityMatrix;
14662
14663        // Sets the flag as early as possible to allow draw() implementations
14664        // to call invalidate() successfully when doing animations
14665        mPrivateFlags |= PFLAG_DRAWN;
14666
14667        if (!concatMatrix &&
14668                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14669                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14670                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14671                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14672            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14673            return more;
14674        }
14675        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14676
14677        if (hardwareAccelerated) {
14678            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14679            // retain the flag's value temporarily in the mRecreateDisplayList flag
14680            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14681            mPrivateFlags &= ~PFLAG_INVALIDATED;
14682        }
14683
14684        RenderNode displayList = null;
14685        Bitmap cache = null;
14686        boolean hasDisplayList = false;
14687        if (caching) {
14688            if (!hardwareAccelerated) {
14689                if (layerType != LAYER_TYPE_NONE) {
14690                    layerType = LAYER_TYPE_SOFTWARE;
14691                    buildDrawingCache(true);
14692                }
14693                cache = getDrawingCache(true);
14694            } else {
14695                switch (layerType) {
14696                    case LAYER_TYPE_SOFTWARE:
14697                        if (useDisplayListProperties) {
14698                            hasDisplayList = canHaveDisplayList();
14699                        } else {
14700                            buildDrawingCache(true);
14701                            cache = getDrawingCache(true);
14702                        }
14703                        break;
14704                    case LAYER_TYPE_HARDWARE:
14705                        if (useDisplayListProperties) {
14706                            hasDisplayList = canHaveDisplayList();
14707                        }
14708                        break;
14709                    case LAYER_TYPE_NONE:
14710                        // Delay getting the display list until animation-driven alpha values are
14711                        // set up and possibly passed on to the view
14712                        hasDisplayList = canHaveDisplayList();
14713                        break;
14714                }
14715            }
14716        }
14717        useDisplayListProperties &= hasDisplayList;
14718        if (useDisplayListProperties) {
14719            displayList = getDisplayList();
14720            if (!displayList.isValid()) {
14721                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14722                // to getDisplayList(), the display list will be marked invalid and we should not
14723                // try to use it again.
14724                displayList = null;
14725                hasDisplayList = false;
14726                useDisplayListProperties = false;
14727            }
14728        }
14729
14730        int sx = 0;
14731        int sy = 0;
14732        if (!hasDisplayList) {
14733            computeScroll();
14734            sx = mScrollX;
14735            sy = mScrollY;
14736        }
14737
14738        final boolean hasNoCache = cache == null || hasDisplayList;
14739        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14740                layerType != LAYER_TYPE_HARDWARE;
14741
14742        int restoreTo = -1;
14743        if (!useDisplayListProperties || transformToApply != null) {
14744            restoreTo = canvas.save();
14745        }
14746        if (offsetForScroll) {
14747            canvas.translate(mLeft - sx, mTop - sy);
14748        } else {
14749            if (!useDisplayListProperties) {
14750                canvas.translate(mLeft, mTop);
14751            }
14752            if (scalingRequired) {
14753                if (useDisplayListProperties) {
14754                    // TODO: Might not need this if we put everything inside the DL
14755                    restoreTo = canvas.save();
14756                }
14757                // mAttachInfo cannot be null, otherwise scalingRequired == false
14758                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14759                canvas.scale(scale, scale);
14760            }
14761        }
14762
14763        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14764        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14765                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14766            if (transformToApply != null || !childHasIdentityMatrix) {
14767                int transX = 0;
14768                int transY = 0;
14769
14770                if (offsetForScroll) {
14771                    transX = -sx;
14772                    transY = -sy;
14773                }
14774
14775                if (transformToApply != null) {
14776                    if (concatMatrix) {
14777                        if (useDisplayListProperties) {
14778                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14779                        } else {
14780                            // Undo the scroll translation, apply the transformation matrix,
14781                            // then redo the scroll translate to get the correct result.
14782                            canvas.translate(-transX, -transY);
14783                            canvas.concat(transformToApply.getMatrix());
14784                            canvas.translate(transX, transY);
14785                        }
14786                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14787                    }
14788
14789                    float transformAlpha = transformToApply.getAlpha();
14790                    if (transformAlpha < 1) {
14791                        alpha *= transformAlpha;
14792                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14793                    }
14794                }
14795
14796                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14797                    canvas.translate(-transX, -transY);
14798                    canvas.concat(getMatrix());
14799                    canvas.translate(transX, transY);
14800                }
14801            }
14802
14803            // Deal with alpha if it is or used to be <1
14804            if (alpha < 1 ||
14805                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14806                if (alpha < 1) {
14807                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14808                } else {
14809                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14810                }
14811                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14812                if (hasNoCache) {
14813                    final int multipliedAlpha = (int) (255 * alpha);
14814                    if (!onSetAlpha(multipliedAlpha)) {
14815                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14816                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14817                                layerType != LAYER_TYPE_NONE) {
14818                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14819                        }
14820                        if (useDisplayListProperties) {
14821                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14822                        } else  if (layerType == LAYER_TYPE_NONE) {
14823                            final int scrollX = hasDisplayList ? 0 : sx;
14824                            final int scrollY = hasDisplayList ? 0 : sy;
14825                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14826                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14827                        }
14828                    } else {
14829                        // Alpha is handled by the child directly, clobber the layer's alpha
14830                        mPrivateFlags |= PFLAG_ALPHA_SET;
14831                    }
14832                }
14833            }
14834        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14835            onSetAlpha(255);
14836            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14837        }
14838
14839        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14840                !useDisplayListProperties && cache == null) {
14841            if (offsetForScroll) {
14842                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14843            } else {
14844                if (!scalingRequired || cache == null) {
14845                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14846                } else {
14847                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14848                }
14849            }
14850        }
14851
14852        if (!useDisplayListProperties && hasDisplayList) {
14853            displayList = getDisplayList();
14854            if (!displayList.isValid()) {
14855                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14856                // to getDisplayList(), the display list will be marked invalid and we should not
14857                // try to use it again.
14858                displayList = null;
14859                hasDisplayList = false;
14860            }
14861        }
14862
14863        if (hasNoCache) {
14864            boolean layerRendered = false;
14865            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14866                final HardwareLayer layer = getHardwareLayer();
14867                if (layer != null && layer.isValid()) {
14868                    mLayerPaint.setAlpha((int) (alpha * 255));
14869                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14870                    layerRendered = true;
14871                } else {
14872                    final int scrollX = hasDisplayList ? 0 : sx;
14873                    final int scrollY = hasDisplayList ? 0 : sy;
14874                    canvas.saveLayer(scrollX, scrollY,
14875                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14876                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14877                }
14878            }
14879
14880            if (!layerRendered) {
14881                if (!hasDisplayList) {
14882                    // Fast path for layouts with no backgrounds
14883                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14884                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14885                        dispatchDraw(canvas);
14886                    } else {
14887                        draw(canvas);
14888                    }
14889                } else {
14890                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14891                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14892                }
14893            }
14894        } else if (cache != null) {
14895            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14896            Paint cachePaint;
14897
14898            if (layerType == LAYER_TYPE_NONE) {
14899                cachePaint = parent.mCachePaint;
14900                if (cachePaint == null) {
14901                    cachePaint = new Paint();
14902                    cachePaint.setDither(false);
14903                    parent.mCachePaint = cachePaint;
14904                }
14905                if (alpha < 1) {
14906                    cachePaint.setAlpha((int) (alpha * 255));
14907                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14908                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14909                    cachePaint.setAlpha(255);
14910                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14911                }
14912            } else {
14913                cachePaint = mLayerPaint;
14914                cachePaint.setAlpha((int) (alpha * 255));
14915            }
14916            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14917        }
14918
14919        if (restoreTo >= 0) {
14920            canvas.restoreToCount(restoreTo);
14921        }
14922
14923        if (a != null && !more) {
14924            if (!hardwareAccelerated && !a.getFillAfter()) {
14925                onSetAlpha(255);
14926            }
14927            parent.finishAnimatingView(this, a);
14928        }
14929
14930        if (more && hardwareAccelerated) {
14931            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14932                // alpha animations should cause the child to recreate its display list
14933                invalidate(true);
14934            }
14935        }
14936
14937        mRecreateDisplayList = false;
14938
14939        return more;
14940    }
14941
14942    /**
14943     * Manually render this view (and all of its children) to the given Canvas.
14944     * The view must have already done a full layout before this function is
14945     * called.  When implementing a view, implement
14946     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14947     * If you do need to override this method, call the superclass version.
14948     *
14949     * @param canvas The Canvas to which the View is rendered.
14950     */
14951    public void draw(Canvas canvas) {
14952        if (mClipBounds != null) {
14953            canvas.clipRect(mClipBounds);
14954        }
14955        final int privateFlags = mPrivateFlags;
14956        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14957                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14958        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14959
14960        /*
14961         * Draw traversal performs several drawing steps which must be executed
14962         * in the appropriate order:
14963         *
14964         *      1. Draw the background
14965         *      2. If necessary, save the canvas' layers to prepare for fading
14966         *      3. Draw view's content
14967         *      4. Draw children
14968         *      5. If necessary, draw the fading edges and restore layers
14969         *      6. Draw decorations (scrollbars for instance)
14970         */
14971
14972        // Step 1, draw the background, if needed
14973        int saveCount;
14974
14975        if (!dirtyOpaque) {
14976            drawBackground(canvas);
14977        }
14978
14979        // skip step 2 & 5 if possible (common case)
14980        final int viewFlags = mViewFlags;
14981        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14982        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14983        if (!verticalEdges && !horizontalEdges) {
14984            // Step 3, draw the content
14985            if (!dirtyOpaque) onDraw(canvas);
14986
14987            // Step 4, draw the children
14988            dispatchDraw(canvas);
14989
14990            // Step 6, draw decorations (scrollbars)
14991            onDrawScrollBars(canvas);
14992
14993            if (mOverlay != null && !mOverlay.isEmpty()) {
14994                mOverlay.getOverlayView().dispatchDraw(canvas);
14995            }
14996
14997            // we're done...
14998            return;
14999        }
15000
15001        /*
15002         * Here we do the full fledged routine...
15003         * (this is an uncommon case where speed matters less,
15004         * this is why we repeat some of the tests that have been
15005         * done above)
15006         */
15007
15008        boolean drawTop = false;
15009        boolean drawBottom = false;
15010        boolean drawLeft = false;
15011        boolean drawRight = false;
15012
15013        float topFadeStrength = 0.0f;
15014        float bottomFadeStrength = 0.0f;
15015        float leftFadeStrength = 0.0f;
15016        float rightFadeStrength = 0.0f;
15017
15018        // Step 2, save the canvas' layers
15019        int paddingLeft = mPaddingLeft;
15020
15021        final boolean offsetRequired = isPaddingOffsetRequired();
15022        if (offsetRequired) {
15023            paddingLeft += getLeftPaddingOffset();
15024        }
15025
15026        int left = mScrollX + paddingLeft;
15027        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15028        int top = mScrollY + getFadeTop(offsetRequired);
15029        int bottom = top + getFadeHeight(offsetRequired);
15030
15031        if (offsetRequired) {
15032            right += getRightPaddingOffset();
15033            bottom += getBottomPaddingOffset();
15034        }
15035
15036        final ScrollabilityCache scrollabilityCache = mScrollCache;
15037        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15038        int length = (int) fadeHeight;
15039
15040        // clip the fade length if top and bottom fades overlap
15041        // overlapping fades produce odd-looking artifacts
15042        if (verticalEdges && (top + length > bottom - length)) {
15043            length = (bottom - top) / 2;
15044        }
15045
15046        // also clip horizontal fades if necessary
15047        if (horizontalEdges && (left + length > right - length)) {
15048            length = (right - left) / 2;
15049        }
15050
15051        if (verticalEdges) {
15052            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15053            drawTop = topFadeStrength * fadeHeight > 1.0f;
15054            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15055            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15056        }
15057
15058        if (horizontalEdges) {
15059            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15060            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15061            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15062            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15063        }
15064
15065        saveCount = canvas.getSaveCount();
15066
15067        int solidColor = getSolidColor();
15068        if (solidColor == 0) {
15069            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15070
15071            if (drawTop) {
15072                canvas.saveLayer(left, top, right, top + length, null, flags);
15073            }
15074
15075            if (drawBottom) {
15076                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15077            }
15078
15079            if (drawLeft) {
15080                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15081            }
15082
15083            if (drawRight) {
15084                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15085            }
15086        } else {
15087            scrollabilityCache.setFadeColor(solidColor);
15088        }
15089
15090        // Step 3, draw the content
15091        if (!dirtyOpaque) onDraw(canvas);
15092
15093        // Step 4, draw the children
15094        dispatchDraw(canvas);
15095
15096        // Step 5, draw the fade effect and restore layers
15097        final Paint p = scrollabilityCache.paint;
15098        final Matrix matrix = scrollabilityCache.matrix;
15099        final Shader fade = scrollabilityCache.shader;
15100
15101        if (drawTop) {
15102            matrix.setScale(1, fadeHeight * topFadeStrength);
15103            matrix.postTranslate(left, top);
15104            fade.setLocalMatrix(matrix);
15105            canvas.drawRect(left, top, right, top + length, p);
15106        }
15107
15108        if (drawBottom) {
15109            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15110            matrix.postRotate(180);
15111            matrix.postTranslate(left, bottom);
15112            fade.setLocalMatrix(matrix);
15113            canvas.drawRect(left, bottom - length, right, bottom, p);
15114        }
15115
15116        if (drawLeft) {
15117            matrix.setScale(1, fadeHeight * leftFadeStrength);
15118            matrix.postRotate(-90);
15119            matrix.postTranslate(left, top);
15120            fade.setLocalMatrix(matrix);
15121            canvas.drawRect(left, top, left + length, bottom, p);
15122        }
15123
15124        if (drawRight) {
15125            matrix.setScale(1, fadeHeight * rightFadeStrength);
15126            matrix.postRotate(90);
15127            matrix.postTranslate(right, top);
15128            fade.setLocalMatrix(matrix);
15129            canvas.drawRect(right - length, top, right, bottom, p);
15130        }
15131
15132        canvas.restoreToCount(saveCount);
15133
15134        // Step 6, draw decorations (scrollbars)
15135        onDrawScrollBars(canvas);
15136
15137        if (mOverlay != null && !mOverlay.isEmpty()) {
15138            mOverlay.getOverlayView().dispatchDraw(canvas);
15139        }
15140    }
15141
15142    /**
15143     * Draws the background onto the specified canvas.
15144     *
15145     * @param canvas Canvas on which to draw the background
15146     */
15147    private void drawBackground(Canvas canvas) {
15148        final Drawable background = mBackground;
15149        if (background == null) {
15150            return;
15151        }
15152
15153        if (mBackgroundSizeChanged) {
15154            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15155            mBackgroundSizeChanged = false;
15156            if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
15157                // Outline not currently define, query from background
15158                mOutline = background.getOutline();
15159                if (mDisplayList != null) {
15160                    mDisplayList.setOutline(mOutline);
15161                }
15162            }
15163        }
15164
15165        // Attempt to use a display list if requested.
15166        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15167                && mAttachInfo.mHardwareRenderer != null) {
15168            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15169
15170            final RenderNode displayList = mBackgroundDisplayList;
15171            if (displayList != null && displayList.isValid()) {
15172                setBackgroundDisplayListProperties(displayList);
15173                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15174                return;
15175            }
15176        }
15177
15178        final int scrollX = mScrollX;
15179        final int scrollY = mScrollY;
15180        if ((scrollX | scrollY) == 0) {
15181            background.draw(canvas);
15182        } else {
15183            canvas.translate(scrollX, scrollY);
15184            background.draw(canvas);
15185            canvas.translate(-scrollX, -scrollY);
15186        }
15187    }
15188
15189    /**
15190     * Set up background drawable display list properties.
15191     *
15192     * @param displayList Valid display list for the background drawable
15193     */
15194    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15195        displayList.setTranslationX(mScrollX);
15196        displayList.setTranslationY(mScrollY);
15197    }
15198
15199    /**
15200     * Creates a new display list or updates the existing display list for the
15201     * specified Drawable.
15202     *
15203     * @param drawable Drawable for which to create a display list
15204     * @param displayList Existing display list, or {@code null}
15205     * @return A valid display list for the specified drawable
15206     */
15207    private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) {
15208        if (displayList == null) {
15209            displayList = RenderNode.create(drawable.getClass().getName());
15210        }
15211
15212        final Rect bounds = drawable.getBounds();
15213        final int width = bounds.width();
15214        final int height = bounds.height();
15215        final HardwareCanvas canvas = displayList.start(width, height);
15216        drawable.draw(canvas);
15217        displayList.end(getHardwareRenderer(), canvas);
15218
15219        // Set up drawable properties that are view-independent.
15220        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15221        displayList.setProjectBackwards(drawable.isProjected());
15222        displayList.setProjectionReceiver(true);
15223        displayList.setClipToBounds(false);
15224        return displayList;
15225    }
15226
15227    /**
15228     * Returns the overlay for this view, creating it if it does not yet exist.
15229     * Adding drawables to the overlay will cause them to be displayed whenever
15230     * the view itself is redrawn. Objects in the overlay should be actively
15231     * managed: remove them when they should not be displayed anymore. The
15232     * overlay will always have the same size as its host view.
15233     *
15234     * <p>Note: Overlays do not currently work correctly with {@link
15235     * SurfaceView} or {@link TextureView}; contents in overlays for these
15236     * types of views may not display correctly.</p>
15237     *
15238     * @return The ViewOverlay object for this view.
15239     * @see ViewOverlay
15240     */
15241    public ViewOverlay getOverlay() {
15242        if (mOverlay == null) {
15243            mOverlay = new ViewOverlay(mContext, this);
15244        }
15245        return mOverlay;
15246    }
15247
15248    /**
15249     * Override this if your view is known to always be drawn on top of a solid color background,
15250     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15251     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15252     * should be set to 0xFF.
15253     *
15254     * @see #setVerticalFadingEdgeEnabled(boolean)
15255     * @see #setHorizontalFadingEdgeEnabled(boolean)
15256     *
15257     * @return The known solid color background for this view, or 0 if the color may vary
15258     */
15259    @ViewDebug.ExportedProperty(category = "drawing")
15260    public int getSolidColor() {
15261        return 0;
15262    }
15263
15264    /**
15265     * Build a human readable string representation of the specified view flags.
15266     *
15267     * @param flags the view flags to convert to a string
15268     * @return a String representing the supplied flags
15269     */
15270    private static String printFlags(int flags) {
15271        String output = "";
15272        int numFlags = 0;
15273        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15274            output += "TAKES_FOCUS";
15275            numFlags++;
15276        }
15277
15278        switch (flags & VISIBILITY_MASK) {
15279        case INVISIBLE:
15280            if (numFlags > 0) {
15281                output += " ";
15282            }
15283            output += "INVISIBLE";
15284            // USELESS HERE numFlags++;
15285            break;
15286        case GONE:
15287            if (numFlags > 0) {
15288                output += " ";
15289            }
15290            output += "GONE";
15291            // USELESS HERE numFlags++;
15292            break;
15293        default:
15294            break;
15295        }
15296        return output;
15297    }
15298
15299    /**
15300     * Build a human readable string representation of the specified private
15301     * view flags.
15302     *
15303     * @param privateFlags the private view flags to convert to a string
15304     * @return a String representing the supplied flags
15305     */
15306    private static String printPrivateFlags(int privateFlags) {
15307        String output = "";
15308        int numFlags = 0;
15309
15310        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15311            output += "WANTS_FOCUS";
15312            numFlags++;
15313        }
15314
15315        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15316            if (numFlags > 0) {
15317                output += " ";
15318            }
15319            output += "FOCUSED";
15320            numFlags++;
15321        }
15322
15323        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15324            if (numFlags > 0) {
15325                output += " ";
15326            }
15327            output += "SELECTED";
15328            numFlags++;
15329        }
15330
15331        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15332            if (numFlags > 0) {
15333                output += " ";
15334            }
15335            output += "IS_ROOT_NAMESPACE";
15336            numFlags++;
15337        }
15338
15339        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15340            if (numFlags > 0) {
15341                output += " ";
15342            }
15343            output += "HAS_BOUNDS";
15344            numFlags++;
15345        }
15346
15347        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15348            if (numFlags > 0) {
15349                output += " ";
15350            }
15351            output += "DRAWN";
15352            // USELESS HERE numFlags++;
15353        }
15354        return output;
15355    }
15356
15357    /**
15358     * <p>Indicates whether or not this view's layout will be requested during
15359     * the next hierarchy layout pass.</p>
15360     *
15361     * @return true if the layout will be forced during next layout pass
15362     */
15363    public boolean isLayoutRequested() {
15364        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15365    }
15366
15367    /**
15368     * Return true if o is a ViewGroup that is laying out using optical bounds.
15369     * @hide
15370     */
15371    public static boolean isLayoutModeOptical(Object o) {
15372        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15373    }
15374
15375    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15376        Insets parentInsets = mParent instanceof View ?
15377                ((View) mParent).getOpticalInsets() : Insets.NONE;
15378        Insets childInsets = getOpticalInsets();
15379        return setFrame(
15380                left   + parentInsets.left - childInsets.left,
15381                top    + parentInsets.top  - childInsets.top,
15382                right  + parentInsets.left + childInsets.right,
15383                bottom + parentInsets.top  + childInsets.bottom);
15384    }
15385
15386    /**
15387     * Assign a size and position to a view and all of its
15388     * descendants
15389     *
15390     * <p>This is the second phase of the layout mechanism.
15391     * (The first is measuring). In this phase, each parent calls
15392     * layout on all of its children to position them.
15393     * This is typically done using the child measurements
15394     * that were stored in the measure pass().</p>
15395     *
15396     * <p>Derived classes should not override this method.
15397     * Derived classes with children should override
15398     * onLayout. In that method, they should
15399     * call layout on each of their children.</p>
15400     *
15401     * @param l Left position, relative to parent
15402     * @param t Top position, relative to parent
15403     * @param r Right position, relative to parent
15404     * @param b Bottom position, relative to parent
15405     */
15406    @SuppressWarnings({"unchecked"})
15407    public void layout(int l, int t, int r, int b) {
15408        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15409            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15410            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15411        }
15412
15413        int oldL = mLeft;
15414        int oldT = mTop;
15415        int oldB = mBottom;
15416        int oldR = mRight;
15417
15418        boolean changed = isLayoutModeOptical(mParent) ?
15419                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15420
15421        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15422            onLayout(changed, l, t, r, b);
15423            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15424
15425            ListenerInfo li = mListenerInfo;
15426            if (li != null && li.mOnLayoutChangeListeners != null) {
15427                ArrayList<OnLayoutChangeListener> listenersCopy =
15428                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15429                int numListeners = listenersCopy.size();
15430                for (int i = 0; i < numListeners; ++i) {
15431                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15432                }
15433            }
15434        }
15435
15436        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15437        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15438    }
15439
15440    /**
15441     * Called from layout when this view should
15442     * assign a size and position to each of its children.
15443     *
15444     * Derived classes with children should override
15445     * this method and call layout on each of
15446     * their children.
15447     * @param changed This is a new size or position for this view
15448     * @param left Left position, relative to parent
15449     * @param top Top position, relative to parent
15450     * @param right Right position, relative to parent
15451     * @param bottom Bottom position, relative to parent
15452     */
15453    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15454    }
15455
15456    /**
15457     * Assign a size and position to this view.
15458     *
15459     * This is called from layout.
15460     *
15461     * @param left Left position, relative to parent
15462     * @param top Top position, relative to parent
15463     * @param right Right position, relative to parent
15464     * @param bottom Bottom position, relative to parent
15465     * @return true if the new size and position are different than the
15466     *         previous ones
15467     * {@hide}
15468     */
15469    protected boolean setFrame(int left, int top, int right, int bottom) {
15470        boolean changed = false;
15471
15472        if (DBG) {
15473            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15474                    + right + "," + bottom + ")");
15475        }
15476
15477        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15478            changed = true;
15479
15480            // Remember our drawn bit
15481            int drawn = mPrivateFlags & PFLAG_DRAWN;
15482
15483            int oldWidth = mRight - mLeft;
15484            int oldHeight = mBottom - mTop;
15485            int newWidth = right - left;
15486            int newHeight = bottom - top;
15487            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15488
15489            // Invalidate our old position
15490            invalidate(sizeChanged);
15491
15492            mLeft = left;
15493            mTop = top;
15494            mRight = right;
15495            mBottom = bottom;
15496            if (mDisplayList != null) {
15497                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15498            }
15499
15500            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15501
15502
15503            if (sizeChanged) {
15504                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
15505                    // A change in dimension means an auto-centered pivot point changes, too
15506                    if (mTransformationInfo != null) {
15507                        mTransformationInfo.mMatrixDirty = true;
15508                    }
15509                }
15510                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15511            }
15512
15513            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15514                // If we are visible, force the DRAWN bit to on so that
15515                // this invalidate will go through (at least to our parent).
15516                // This is because someone may have invalidated this view
15517                // before this call to setFrame came in, thereby clearing
15518                // the DRAWN bit.
15519                mPrivateFlags |= PFLAG_DRAWN;
15520                invalidate(sizeChanged);
15521                // parent display list may need to be recreated based on a change in the bounds
15522                // of any child
15523                invalidateParentCaches();
15524            }
15525
15526            // Reset drawn bit to original value (invalidate turns it off)
15527            mPrivateFlags |= drawn;
15528
15529            mBackgroundSizeChanged = true;
15530
15531            notifySubtreeAccessibilityStateChangedIfNeeded();
15532        }
15533        return changed;
15534    }
15535
15536    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15537        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15538        if (mOverlay != null) {
15539            mOverlay.getOverlayView().setRight(newWidth);
15540            mOverlay.getOverlayView().setBottom(newHeight);
15541        }
15542    }
15543
15544    /**
15545     * Finalize inflating a view from XML.  This is called as the last phase
15546     * of inflation, after all child views have been added.
15547     *
15548     * <p>Even if the subclass overrides onFinishInflate, they should always be
15549     * sure to call the super method, so that we get called.
15550     */
15551    protected void onFinishInflate() {
15552    }
15553
15554    /**
15555     * Returns the resources associated with this view.
15556     *
15557     * @return Resources object.
15558     */
15559    public Resources getResources() {
15560        return mResources;
15561    }
15562
15563    /**
15564     * Invalidates the specified Drawable.
15565     *
15566     * @param drawable the drawable to invalidate
15567     */
15568    @Override
15569    public void invalidateDrawable(Drawable drawable) {
15570        if (verifyDrawable(drawable)) {
15571            final Rect dirty = drawable.getDirtyBounds();
15572            final int scrollX = mScrollX;
15573            final int scrollY = mScrollY;
15574
15575            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15576                    dirty.right + scrollX, dirty.bottom + scrollY);
15577        }
15578    }
15579
15580    /**
15581     * Schedules an action on a drawable to occur at a specified time.
15582     *
15583     * @param who the recipient of the action
15584     * @param what the action to run on the drawable
15585     * @param when the time at which the action must occur. Uses the
15586     *        {@link SystemClock#uptimeMillis} timebase.
15587     */
15588    @Override
15589    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15590        if (verifyDrawable(who) && what != null) {
15591            final long delay = when - SystemClock.uptimeMillis();
15592            if (mAttachInfo != null) {
15593                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15594                        Choreographer.CALLBACK_ANIMATION, what, who,
15595                        Choreographer.subtractFrameDelay(delay));
15596            } else {
15597                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15598            }
15599        }
15600    }
15601
15602    /**
15603     * Cancels a scheduled action on a drawable.
15604     *
15605     * @param who the recipient of the action
15606     * @param what the action to cancel
15607     */
15608    @Override
15609    public void unscheduleDrawable(Drawable who, Runnable what) {
15610        if (verifyDrawable(who) && what != null) {
15611            if (mAttachInfo != null) {
15612                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15613                        Choreographer.CALLBACK_ANIMATION, what, who);
15614            }
15615            ViewRootImpl.getRunQueue().removeCallbacks(what);
15616        }
15617    }
15618
15619    /**
15620     * Unschedule any events associated with the given Drawable.  This can be
15621     * used when selecting a new Drawable into a view, so that the previous
15622     * one is completely unscheduled.
15623     *
15624     * @param who The Drawable to unschedule.
15625     *
15626     * @see #drawableStateChanged
15627     */
15628    public void unscheduleDrawable(Drawable who) {
15629        if (mAttachInfo != null && who != null) {
15630            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15631                    Choreographer.CALLBACK_ANIMATION, null, who);
15632        }
15633    }
15634
15635    /**
15636     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15637     * that the View directionality can and will be resolved before its Drawables.
15638     *
15639     * Will call {@link View#onResolveDrawables} when resolution is done.
15640     *
15641     * @hide
15642     */
15643    protected void resolveDrawables() {
15644        // Drawables resolution may need to happen before resolving the layout direction (which is
15645        // done only during the measure() call).
15646        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15647        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15648        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15649        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15650        // direction to be resolved as its resolved value will be the same as its raw value.
15651        if (!isLayoutDirectionResolved() &&
15652                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15653            return;
15654        }
15655
15656        final int layoutDirection = isLayoutDirectionResolved() ?
15657                getLayoutDirection() : getRawLayoutDirection();
15658
15659        if (mBackground != null) {
15660            mBackground.setLayoutDirection(layoutDirection);
15661        }
15662        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15663        onResolveDrawables(layoutDirection);
15664    }
15665
15666    /**
15667     * Called when layout direction has been resolved.
15668     *
15669     * The default implementation does nothing.
15670     *
15671     * @param layoutDirection The resolved layout direction.
15672     *
15673     * @see #LAYOUT_DIRECTION_LTR
15674     * @see #LAYOUT_DIRECTION_RTL
15675     *
15676     * @hide
15677     */
15678    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15679    }
15680
15681    /**
15682     * @hide
15683     */
15684    protected void resetResolvedDrawables() {
15685        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15686    }
15687
15688    private boolean isDrawablesResolved() {
15689        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15690    }
15691
15692    /**
15693     * If your view subclass is displaying its own Drawable objects, it should
15694     * override this function and return true for any Drawable it is
15695     * displaying.  This allows animations for those drawables to be
15696     * scheduled.
15697     *
15698     * <p>Be sure to call through to the super class when overriding this
15699     * function.
15700     *
15701     * @param who The Drawable to verify.  Return true if it is one you are
15702     *            displaying, else return the result of calling through to the
15703     *            super class.
15704     *
15705     * @return boolean If true than the Drawable is being displayed in the
15706     *         view; else false and it is not allowed to animate.
15707     *
15708     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15709     * @see #drawableStateChanged()
15710     */
15711    protected boolean verifyDrawable(Drawable who) {
15712        return who == mBackground;
15713    }
15714
15715    /**
15716     * This function is called whenever the state of the view changes in such
15717     * a way that it impacts the state of drawables being shown.
15718     *
15719     * <p>Be sure to call through to the superclass when overriding this
15720     * function.
15721     *
15722     * @see Drawable#setState(int[])
15723     */
15724    protected void drawableStateChanged() {
15725        final Drawable d = mBackground;
15726        if (d != null && d.isStateful()) {
15727            d.setState(getDrawableState());
15728        }
15729    }
15730
15731    /**
15732     * Call this to force a view to update its drawable state. This will cause
15733     * drawableStateChanged to be called on this view. Views that are interested
15734     * in the new state should call getDrawableState.
15735     *
15736     * @see #drawableStateChanged
15737     * @see #getDrawableState
15738     */
15739    public void refreshDrawableState() {
15740        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15741        drawableStateChanged();
15742
15743        ViewParent parent = mParent;
15744        if (parent != null) {
15745            parent.childDrawableStateChanged(this);
15746        }
15747    }
15748
15749    /**
15750     * Return an array of resource IDs of the drawable states representing the
15751     * current state of the view.
15752     *
15753     * @return The current drawable state
15754     *
15755     * @see Drawable#setState(int[])
15756     * @see #drawableStateChanged()
15757     * @see #onCreateDrawableState(int)
15758     */
15759    public final int[] getDrawableState() {
15760        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15761            return mDrawableState;
15762        } else {
15763            mDrawableState = onCreateDrawableState(0);
15764            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15765            return mDrawableState;
15766        }
15767    }
15768
15769    /**
15770     * Generate the new {@link android.graphics.drawable.Drawable} state for
15771     * this view. This is called by the view
15772     * system when the cached Drawable state is determined to be invalid.  To
15773     * retrieve the current state, you should use {@link #getDrawableState}.
15774     *
15775     * @param extraSpace if non-zero, this is the number of extra entries you
15776     * would like in the returned array in which you can place your own
15777     * states.
15778     *
15779     * @return Returns an array holding the current {@link Drawable} state of
15780     * the view.
15781     *
15782     * @see #mergeDrawableStates(int[], int[])
15783     */
15784    protected int[] onCreateDrawableState(int extraSpace) {
15785        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15786                mParent instanceof View) {
15787            return ((View) mParent).onCreateDrawableState(extraSpace);
15788        }
15789
15790        int[] drawableState;
15791
15792        int privateFlags = mPrivateFlags;
15793
15794        int viewStateIndex = 0;
15795        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15796        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15797        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15798        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15799        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15800        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15801        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15802                HardwareRenderer.isAvailable()) {
15803            // This is set if HW acceleration is requested, even if the current
15804            // process doesn't allow it.  This is just to allow app preview
15805            // windows to better match their app.
15806            viewStateIndex |= VIEW_STATE_ACCELERATED;
15807        }
15808        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15809
15810        final int privateFlags2 = mPrivateFlags2;
15811        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15812        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15813
15814        drawableState = VIEW_STATE_SETS[viewStateIndex];
15815
15816        //noinspection ConstantIfStatement
15817        if (false) {
15818            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15819            Log.i("View", toString()
15820                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15821                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15822                    + " fo=" + hasFocus()
15823                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15824                    + " wf=" + hasWindowFocus()
15825                    + ": " + Arrays.toString(drawableState));
15826        }
15827
15828        if (extraSpace == 0) {
15829            return drawableState;
15830        }
15831
15832        final int[] fullState;
15833        if (drawableState != null) {
15834            fullState = new int[drawableState.length + extraSpace];
15835            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15836        } else {
15837            fullState = new int[extraSpace];
15838        }
15839
15840        return fullState;
15841    }
15842
15843    /**
15844     * Merge your own state values in <var>additionalState</var> into the base
15845     * state values <var>baseState</var> that were returned by
15846     * {@link #onCreateDrawableState(int)}.
15847     *
15848     * @param baseState The base state values returned by
15849     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15850     * own additional state values.
15851     *
15852     * @param additionalState The additional state values you would like
15853     * added to <var>baseState</var>; this array is not modified.
15854     *
15855     * @return As a convenience, the <var>baseState</var> array you originally
15856     * passed into the function is returned.
15857     *
15858     * @see #onCreateDrawableState(int)
15859     */
15860    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15861        final int N = baseState.length;
15862        int i = N - 1;
15863        while (i >= 0 && baseState[i] == 0) {
15864            i--;
15865        }
15866        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15867        return baseState;
15868    }
15869
15870    /**
15871     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15872     * on all Drawable objects associated with this view.
15873     */
15874    public void jumpDrawablesToCurrentState() {
15875        if (mBackground != null) {
15876            mBackground.jumpToCurrentState();
15877        }
15878    }
15879
15880    /**
15881     * Sets the background color for this view.
15882     * @param color the color of the background
15883     */
15884    @RemotableViewMethod
15885    public void setBackgroundColor(int color) {
15886        if (mBackground instanceof ColorDrawable) {
15887            ((ColorDrawable) mBackground.mutate()).setColor(color);
15888            computeOpaqueFlags();
15889            mBackgroundResource = 0;
15890        } else {
15891            setBackground(new ColorDrawable(color));
15892        }
15893    }
15894
15895    /**
15896     * Set the background to a given resource. The resource should refer to
15897     * a Drawable object or 0 to remove the background.
15898     * @param resid The identifier of the resource.
15899     *
15900     * @attr ref android.R.styleable#View_background
15901     */
15902    @RemotableViewMethod
15903    public void setBackgroundResource(int resid) {
15904        if (resid != 0 && resid == mBackgroundResource) {
15905            return;
15906        }
15907
15908        Drawable d= null;
15909        if (resid != 0) {
15910            d = mContext.getDrawable(resid);
15911        }
15912        setBackground(d);
15913
15914        mBackgroundResource = resid;
15915    }
15916
15917    /**
15918     * Set the background to a given Drawable, or remove the background. If the
15919     * background has padding, this View's padding is set to the background's
15920     * padding. However, when a background is removed, this View's padding isn't
15921     * touched. If setting the padding is desired, please use
15922     * {@link #setPadding(int, int, int, int)}.
15923     *
15924     * @param background The Drawable to use as the background, or null to remove the
15925     *        background
15926     */
15927    public void setBackground(Drawable background) {
15928        //noinspection deprecation
15929        setBackgroundDrawable(background);
15930    }
15931
15932    /**
15933     * @deprecated use {@link #setBackground(Drawable)} instead
15934     */
15935    @Deprecated
15936    public void setBackgroundDrawable(Drawable background) {
15937        computeOpaqueFlags();
15938
15939        if (background == mBackground) {
15940            return;
15941        }
15942
15943        boolean requestLayout = false;
15944
15945        mBackgroundResource = 0;
15946
15947        /*
15948         * Regardless of whether we're setting a new background or not, we want
15949         * to clear the previous drawable.
15950         */
15951        if (mBackground != null) {
15952            mBackground.setCallback(null);
15953            unscheduleDrawable(mBackground);
15954        }
15955
15956        if (background != null) {
15957            Rect padding = sThreadLocal.get();
15958            if (padding == null) {
15959                padding = new Rect();
15960                sThreadLocal.set(padding);
15961            }
15962            resetResolvedDrawables();
15963            background.setLayoutDirection(getLayoutDirection());
15964            if (background.getPadding(padding)) {
15965                resetResolvedPadding();
15966                switch (background.getLayoutDirection()) {
15967                    case LAYOUT_DIRECTION_RTL:
15968                        mUserPaddingLeftInitial = padding.right;
15969                        mUserPaddingRightInitial = padding.left;
15970                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15971                        break;
15972                    case LAYOUT_DIRECTION_LTR:
15973                    default:
15974                        mUserPaddingLeftInitial = padding.left;
15975                        mUserPaddingRightInitial = padding.right;
15976                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15977                }
15978                mLeftPaddingDefined = false;
15979                mRightPaddingDefined = false;
15980            }
15981
15982            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15983            // if it has a different minimum size, we should layout again
15984            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15985                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15986                requestLayout = true;
15987            }
15988
15989            background.setCallback(this);
15990            if (background.isStateful()) {
15991                background.setState(getDrawableState());
15992            }
15993            background.setVisible(getVisibility() == VISIBLE, false);
15994            mBackground = background;
15995
15996            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15997                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15998                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15999                requestLayout = true;
16000            }
16001        } else {
16002            /* Remove the background */
16003            mBackground = null;
16004
16005            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16006                /*
16007                 * This view ONLY drew the background before and we're removing
16008                 * the background, so now it won't draw anything
16009                 * (hence we SKIP_DRAW)
16010                 */
16011                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16012                mPrivateFlags |= PFLAG_SKIP_DRAW;
16013            }
16014
16015            /*
16016             * When the background is set, we try to apply its padding to this
16017             * View. When the background is removed, we don't touch this View's
16018             * padding. This is noted in the Javadocs. Hence, we don't need to
16019             * requestLayout(), the invalidate() below is sufficient.
16020             */
16021
16022            // The old background's minimum size could have affected this
16023            // View's layout, so let's requestLayout
16024            requestLayout = true;
16025        }
16026
16027        computeOpaqueFlags();
16028
16029        if (requestLayout) {
16030            requestLayout();
16031        }
16032
16033        mBackgroundSizeChanged = true;
16034        invalidate(true);
16035    }
16036
16037    /**
16038     * Gets the background drawable
16039     *
16040     * @return The drawable used as the background for this view, if any.
16041     *
16042     * @see #setBackground(Drawable)
16043     *
16044     * @attr ref android.R.styleable#View_background
16045     */
16046    public Drawable getBackground() {
16047        return mBackground;
16048    }
16049
16050    /**
16051     * Sets the padding. The view may add on the space required to display
16052     * the scrollbars, depending on the style and visibility of the scrollbars.
16053     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16054     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16055     * from the values set in this call.
16056     *
16057     * @attr ref android.R.styleable#View_padding
16058     * @attr ref android.R.styleable#View_paddingBottom
16059     * @attr ref android.R.styleable#View_paddingLeft
16060     * @attr ref android.R.styleable#View_paddingRight
16061     * @attr ref android.R.styleable#View_paddingTop
16062     * @param left the left padding in pixels
16063     * @param top the top padding in pixels
16064     * @param right the right padding in pixels
16065     * @param bottom the bottom padding in pixels
16066     */
16067    public void setPadding(int left, int top, int right, int bottom) {
16068        resetResolvedPadding();
16069
16070        mUserPaddingStart = UNDEFINED_PADDING;
16071        mUserPaddingEnd = UNDEFINED_PADDING;
16072
16073        mUserPaddingLeftInitial = left;
16074        mUserPaddingRightInitial = right;
16075
16076        mLeftPaddingDefined = true;
16077        mRightPaddingDefined = true;
16078
16079        internalSetPadding(left, top, right, bottom);
16080    }
16081
16082    /**
16083     * @hide
16084     */
16085    protected void internalSetPadding(int left, int top, int right, int bottom) {
16086        mUserPaddingLeft = left;
16087        mUserPaddingRight = right;
16088        mUserPaddingBottom = bottom;
16089
16090        final int viewFlags = mViewFlags;
16091        boolean changed = false;
16092
16093        // Common case is there are no scroll bars.
16094        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16095            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16096                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16097                        ? 0 : getVerticalScrollbarWidth();
16098                switch (mVerticalScrollbarPosition) {
16099                    case SCROLLBAR_POSITION_DEFAULT:
16100                        if (isLayoutRtl()) {
16101                            left += offset;
16102                        } else {
16103                            right += offset;
16104                        }
16105                        break;
16106                    case SCROLLBAR_POSITION_RIGHT:
16107                        right += offset;
16108                        break;
16109                    case SCROLLBAR_POSITION_LEFT:
16110                        left += offset;
16111                        break;
16112                }
16113            }
16114            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16115                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16116                        ? 0 : getHorizontalScrollbarHeight();
16117            }
16118        }
16119
16120        if (mPaddingLeft != left) {
16121            changed = true;
16122            mPaddingLeft = left;
16123        }
16124        if (mPaddingTop != top) {
16125            changed = true;
16126            mPaddingTop = top;
16127        }
16128        if (mPaddingRight != right) {
16129            changed = true;
16130            mPaddingRight = right;
16131        }
16132        if (mPaddingBottom != bottom) {
16133            changed = true;
16134            mPaddingBottom = bottom;
16135        }
16136
16137        if (changed) {
16138            requestLayout();
16139        }
16140    }
16141
16142    /**
16143     * Sets the relative padding. The view may add on the space required to display
16144     * the scrollbars, depending on the style and visibility of the scrollbars.
16145     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16146     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16147     * from the values set in this call.
16148     *
16149     * @attr ref android.R.styleable#View_padding
16150     * @attr ref android.R.styleable#View_paddingBottom
16151     * @attr ref android.R.styleable#View_paddingStart
16152     * @attr ref android.R.styleable#View_paddingEnd
16153     * @attr ref android.R.styleable#View_paddingTop
16154     * @param start the start padding in pixels
16155     * @param top the top padding in pixels
16156     * @param end the end padding in pixels
16157     * @param bottom the bottom padding in pixels
16158     */
16159    public void setPaddingRelative(int start, int top, int end, int bottom) {
16160        resetResolvedPadding();
16161
16162        mUserPaddingStart = start;
16163        mUserPaddingEnd = end;
16164        mLeftPaddingDefined = true;
16165        mRightPaddingDefined = true;
16166
16167        switch(getLayoutDirection()) {
16168            case LAYOUT_DIRECTION_RTL:
16169                mUserPaddingLeftInitial = end;
16170                mUserPaddingRightInitial = start;
16171                internalSetPadding(end, top, start, bottom);
16172                break;
16173            case LAYOUT_DIRECTION_LTR:
16174            default:
16175                mUserPaddingLeftInitial = start;
16176                mUserPaddingRightInitial = end;
16177                internalSetPadding(start, top, end, bottom);
16178        }
16179    }
16180
16181    /**
16182     * Returns the top padding of this view.
16183     *
16184     * @return the top padding in pixels
16185     */
16186    public int getPaddingTop() {
16187        return mPaddingTop;
16188    }
16189
16190    /**
16191     * Returns the bottom padding of this view. If there are inset and enabled
16192     * scrollbars, this value may include the space required to display the
16193     * scrollbars as well.
16194     *
16195     * @return the bottom padding in pixels
16196     */
16197    public int getPaddingBottom() {
16198        return mPaddingBottom;
16199    }
16200
16201    /**
16202     * Returns the left padding of this view. If there are inset and enabled
16203     * scrollbars, this value may include the space required to display the
16204     * scrollbars as well.
16205     *
16206     * @return the left padding in pixels
16207     */
16208    public int getPaddingLeft() {
16209        if (!isPaddingResolved()) {
16210            resolvePadding();
16211        }
16212        return mPaddingLeft;
16213    }
16214
16215    /**
16216     * Returns the start padding of this view depending on its resolved layout direction.
16217     * If there are inset and enabled scrollbars, this value may include the space
16218     * required to display the scrollbars as well.
16219     *
16220     * @return the start padding in pixels
16221     */
16222    public int getPaddingStart() {
16223        if (!isPaddingResolved()) {
16224            resolvePadding();
16225        }
16226        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16227                mPaddingRight : mPaddingLeft;
16228    }
16229
16230    /**
16231     * Returns the right padding of this view. If there are inset and enabled
16232     * scrollbars, this value may include the space required to display the
16233     * scrollbars as well.
16234     *
16235     * @return the right padding in pixels
16236     */
16237    public int getPaddingRight() {
16238        if (!isPaddingResolved()) {
16239            resolvePadding();
16240        }
16241        return mPaddingRight;
16242    }
16243
16244    /**
16245     * Returns the end padding of this view depending on its resolved layout direction.
16246     * If there are inset and enabled scrollbars, this value may include the space
16247     * required to display the scrollbars as well.
16248     *
16249     * @return the end padding in pixels
16250     */
16251    public int getPaddingEnd() {
16252        if (!isPaddingResolved()) {
16253            resolvePadding();
16254        }
16255        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16256                mPaddingLeft : mPaddingRight;
16257    }
16258
16259    /**
16260     * Return if the padding as been set thru relative values
16261     * {@link #setPaddingRelative(int, int, int, int)} or thru
16262     * @attr ref android.R.styleable#View_paddingStart or
16263     * @attr ref android.R.styleable#View_paddingEnd
16264     *
16265     * @return true if the padding is relative or false if it is not.
16266     */
16267    public boolean isPaddingRelative() {
16268        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16269    }
16270
16271    Insets computeOpticalInsets() {
16272        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16273    }
16274
16275    /**
16276     * @hide
16277     */
16278    public void resetPaddingToInitialValues() {
16279        if (isRtlCompatibilityMode()) {
16280            mPaddingLeft = mUserPaddingLeftInitial;
16281            mPaddingRight = mUserPaddingRightInitial;
16282            return;
16283        }
16284        if (isLayoutRtl()) {
16285            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16286            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16287        } else {
16288            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16289            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16290        }
16291    }
16292
16293    /**
16294     * @hide
16295     */
16296    public Insets getOpticalInsets() {
16297        if (mLayoutInsets == null) {
16298            mLayoutInsets = computeOpticalInsets();
16299        }
16300        return mLayoutInsets;
16301    }
16302
16303    /**
16304     * Changes the selection state of this view. A view can be selected or not.
16305     * Note that selection is not the same as focus. Views are typically
16306     * selected in the context of an AdapterView like ListView or GridView;
16307     * the selected view is the view that is highlighted.
16308     *
16309     * @param selected true if the view must be selected, false otherwise
16310     */
16311    public void setSelected(boolean selected) {
16312        //noinspection DoubleNegation
16313        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16314            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16315            if (!selected) resetPressedState();
16316            invalidate(true);
16317            refreshDrawableState();
16318            dispatchSetSelected(selected);
16319            notifyViewAccessibilityStateChangedIfNeeded(
16320                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16321        }
16322    }
16323
16324    /**
16325     * Dispatch setSelected to all of this View's children.
16326     *
16327     * @see #setSelected(boolean)
16328     *
16329     * @param selected The new selected state
16330     */
16331    protected void dispatchSetSelected(boolean selected) {
16332    }
16333
16334    /**
16335     * Indicates the selection state of this view.
16336     *
16337     * @return true if the view is selected, false otherwise
16338     */
16339    @ViewDebug.ExportedProperty
16340    public boolean isSelected() {
16341        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16342    }
16343
16344    /**
16345     * Changes the activated state of this view. A view can be activated or not.
16346     * Note that activation is not the same as selection.  Selection is
16347     * a transient property, representing the view (hierarchy) the user is
16348     * currently interacting with.  Activation is a longer-term state that the
16349     * user can move views in and out of.  For example, in a list view with
16350     * single or multiple selection enabled, the views in the current selection
16351     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16352     * here.)  The activated state is propagated down to children of the view it
16353     * is set on.
16354     *
16355     * @param activated true if the view must be activated, false otherwise
16356     */
16357    public void setActivated(boolean activated) {
16358        //noinspection DoubleNegation
16359        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16360            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16361            invalidate(true);
16362            refreshDrawableState();
16363            dispatchSetActivated(activated);
16364        }
16365    }
16366
16367    /**
16368     * Dispatch setActivated to all of this View's children.
16369     *
16370     * @see #setActivated(boolean)
16371     *
16372     * @param activated The new activated state
16373     */
16374    protected void dispatchSetActivated(boolean activated) {
16375    }
16376
16377    /**
16378     * Indicates the activation state of this view.
16379     *
16380     * @return true if the view is activated, false otherwise
16381     */
16382    @ViewDebug.ExportedProperty
16383    public boolean isActivated() {
16384        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16385    }
16386
16387    /**
16388     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16389     * observer can be used to get notifications when global events, like
16390     * layout, happen.
16391     *
16392     * The returned ViewTreeObserver observer is not guaranteed to remain
16393     * valid for the lifetime of this View. If the caller of this method keeps
16394     * a long-lived reference to ViewTreeObserver, it should always check for
16395     * the return value of {@link ViewTreeObserver#isAlive()}.
16396     *
16397     * @return The ViewTreeObserver for this view's hierarchy.
16398     */
16399    public ViewTreeObserver getViewTreeObserver() {
16400        if (mAttachInfo != null) {
16401            return mAttachInfo.mTreeObserver;
16402        }
16403        if (mFloatingTreeObserver == null) {
16404            mFloatingTreeObserver = new ViewTreeObserver();
16405        }
16406        return mFloatingTreeObserver;
16407    }
16408
16409    /**
16410     * <p>Finds the topmost view in the current view hierarchy.</p>
16411     *
16412     * @return the topmost view containing this view
16413     */
16414    public View getRootView() {
16415        if (mAttachInfo != null) {
16416            final View v = mAttachInfo.mRootView;
16417            if (v != null) {
16418                return v;
16419            }
16420        }
16421
16422        View parent = this;
16423
16424        while (parent.mParent != null && parent.mParent instanceof View) {
16425            parent = (View) parent.mParent;
16426        }
16427
16428        return parent;
16429    }
16430
16431    /**
16432     * Transforms a motion event from view-local coordinates to on-screen
16433     * coordinates.
16434     *
16435     * @param ev the view-local motion event
16436     * @return false if the transformation could not be applied
16437     * @hide
16438     */
16439    public boolean toGlobalMotionEvent(MotionEvent ev) {
16440        final AttachInfo info = mAttachInfo;
16441        if (info == null) {
16442            return false;
16443        }
16444
16445        final Matrix m = info.mTmpMatrix;
16446        m.set(Matrix.IDENTITY_MATRIX);
16447        transformMatrixToGlobal(m);
16448        ev.transform(m);
16449        return true;
16450    }
16451
16452    /**
16453     * Transforms a motion event from on-screen coordinates to view-local
16454     * coordinates.
16455     *
16456     * @param ev the on-screen motion event
16457     * @return false if the transformation could not be applied
16458     * @hide
16459     */
16460    public boolean toLocalMotionEvent(MotionEvent ev) {
16461        final AttachInfo info = mAttachInfo;
16462        if (info == null) {
16463            return false;
16464        }
16465
16466        final Matrix m = info.mTmpMatrix;
16467        m.set(Matrix.IDENTITY_MATRIX);
16468        transformMatrixToLocal(m);
16469        ev.transform(m);
16470        return true;
16471    }
16472
16473    /**
16474     * Modifies the input matrix such that it maps view-local coordinates to
16475     * on-screen coordinates.
16476     *
16477     * @param m input matrix to modify
16478     */
16479    void transformMatrixToGlobal(Matrix m) {
16480        final ViewParent parent = mParent;
16481        if (parent instanceof View) {
16482            final View vp = (View) parent;
16483            vp.transformMatrixToGlobal(m);
16484            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16485        } else if (parent instanceof ViewRootImpl) {
16486            final ViewRootImpl vr = (ViewRootImpl) parent;
16487            vr.transformMatrixToGlobal(m);
16488            m.postTranslate(0, -vr.mCurScrollY);
16489        }
16490
16491        m.postTranslate(mLeft, mTop);
16492
16493        if (!hasIdentityMatrix()) {
16494            m.postConcat(getMatrix());
16495        }
16496    }
16497
16498    /**
16499     * Modifies the input matrix such that it maps on-screen coordinates to
16500     * view-local coordinates.
16501     *
16502     * @param m input matrix to modify
16503     */
16504    void transformMatrixToLocal(Matrix m) {
16505        final ViewParent parent = mParent;
16506        if (parent instanceof View) {
16507            final View vp = (View) parent;
16508            vp.transformMatrixToLocal(m);
16509            m.preTranslate(vp.mScrollX, vp.mScrollY);
16510        } else if (parent instanceof ViewRootImpl) {
16511            final ViewRootImpl vr = (ViewRootImpl) parent;
16512            vr.transformMatrixToLocal(m);
16513            m.preTranslate(0, vr.mCurScrollY);
16514        }
16515
16516        m.preTranslate(-mLeft, -mTop);
16517
16518        if (!hasIdentityMatrix()) {
16519            m.preConcat(getInverseMatrix());
16520        }
16521    }
16522
16523    /**
16524     * <p>Computes the coordinates of this view on the screen. The argument
16525     * must be an array of two integers. After the method returns, the array
16526     * contains the x and y location in that order.</p>
16527     *
16528     * @param location an array of two integers in which to hold the coordinates
16529     */
16530    public void getLocationOnScreen(int[] location) {
16531        getLocationInWindow(location);
16532
16533        final AttachInfo info = mAttachInfo;
16534        if (info != null) {
16535            location[0] += info.mWindowLeft;
16536            location[1] += info.mWindowTop;
16537        }
16538    }
16539
16540    /**
16541     * <p>Computes the coordinates of this view in its window. The argument
16542     * must be an array of two integers. After the method returns, the array
16543     * contains the x and y location in that order.</p>
16544     *
16545     * @param location an array of two integers in which to hold the coordinates
16546     */
16547    public void getLocationInWindow(int[] location) {
16548        if (location == null || location.length < 2) {
16549            throw new IllegalArgumentException("location must be an array of two integers");
16550        }
16551
16552        if (mAttachInfo == null) {
16553            // When the view is not attached to a window, this method does not make sense
16554            location[0] = location[1] = 0;
16555            return;
16556        }
16557
16558        float[] position = mAttachInfo.mTmpTransformLocation;
16559        position[0] = position[1] = 0.0f;
16560
16561        if (!hasIdentityMatrix()) {
16562            getMatrix().mapPoints(position);
16563        }
16564
16565        position[0] += mLeft;
16566        position[1] += mTop;
16567
16568        ViewParent viewParent = mParent;
16569        while (viewParent instanceof View) {
16570            final View view = (View) viewParent;
16571
16572            position[0] -= view.mScrollX;
16573            position[1] -= view.mScrollY;
16574
16575            if (!view.hasIdentityMatrix()) {
16576                view.getMatrix().mapPoints(position);
16577            }
16578
16579            position[0] += view.mLeft;
16580            position[1] += view.mTop;
16581
16582            viewParent = view.mParent;
16583         }
16584
16585        if (viewParent instanceof ViewRootImpl) {
16586            // *cough*
16587            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16588            position[1] -= vr.mCurScrollY;
16589        }
16590
16591        location[0] = (int) (position[0] + 0.5f);
16592        location[1] = (int) (position[1] + 0.5f);
16593    }
16594
16595    /**
16596     * {@hide}
16597     * @param id the id of the view to be found
16598     * @return the view of the specified id, null if cannot be found
16599     */
16600    protected View findViewTraversal(int id) {
16601        if (id == mID) {
16602            return this;
16603        }
16604        return null;
16605    }
16606
16607    /**
16608     * {@hide}
16609     * @param tag the tag of the view to be found
16610     * @return the view of specified tag, null if cannot be found
16611     */
16612    protected View findViewWithTagTraversal(Object tag) {
16613        if (tag != null && tag.equals(mTag)) {
16614            return this;
16615        }
16616        return null;
16617    }
16618
16619    /**
16620     * {@hide}
16621     * @param predicate The predicate to evaluate.
16622     * @param childToSkip If not null, ignores this child during the recursive traversal.
16623     * @return The first view that matches the predicate or null.
16624     */
16625    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16626        if (predicate.apply(this)) {
16627            return this;
16628        }
16629        return null;
16630    }
16631
16632    /**
16633     * Look for a child view with the given id.  If this view has the given
16634     * id, return this view.
16635     *
16636     * @param id The id to search for.
16637     * @return The view that has the given id in the hierarchy or null
16638     */
16639    public final View findViewById(int id) {
16640        if (id < 0) {
16641            return null;
16642        }
16643        return findViewTraversal(id);
16644    }
16645
16646    /**
16647     * Finds a view by its unuque and stable accessibility id.
16648     *
16649     * @param accessibilityId The searched accessibility id.
16650     * @return The found view.
16651     */
16652    final View findViewByAccessibilityId(int accessibilityId) {
16653        if (accessibilityId < 0) {
16654            return null;
16655        }
16656        return findViewByAccessibilityIdTraversal(accessibilityId);
16657    }
16658
16659    /**
16660     * Performs the traversal to find a view by its unuque and stable accessibility id.
16661     *
16662     * <strong>Note:</strong>This method does not stop at the root namespace
16663     * boundary since the user can touch the screen at an arbitrary location
16664     * potentially crossing the root namespace bounday which will send an
16665     * accessibility event to accessibility services and they should be able
16666     * to obtain the event source. Also accessibility ids are guaranteed to be
16667     * unique in the window.
16668     *
16669     * @param accessibilityId The accessibility id.
16670     * @return The found view.
16671     *
16672     * @hide
16673     */
16674    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16675        if (getAccessibilityViewId() == accessibilityId) {
16676            return this;
16677        }
16678        return null;
16679    }
16680
16681    /**
16682     * Look for a child view with the given tag.  If this view has the given
16683     * tag, return this view.
16684     *
16685     * @param tag The tag to search for, using "tag.equals(getTag())".
16686     * @return The View that has the given tag in the hierarchy or null
16687     */
16688    public final View findViewWithTag(Object tag) {
16689        if (tag == null) {
16690            return null;
16691        }
16692        return findViewWithTagTraversal(tag);
16693    }
16694
16695    /**
16696     * {@hide}
16697     * Look for a child view that matches the specified predicate.
16698     * If this view matches the predicate, return this view.
16699     *
16700     * @param predicate The predicate to evaluate.
16701     * @return The first view that matches the predicate or null.
16702     */
16703    public final View findViewByPredicate(Predicate<View> predicate) {
16704        return findViewByPredicateTraversal(predicate, null);
16705    }
16706
16707    /**
16708     * {@hide}
16709     * Look for a child view that matches the specified predicate,
16710     * starting with the specified view and its descendents and then
16711     * recusively searching the ancestors and siblings of that view
16712     * until this view is reached.
16713     *
16714     * This method is useful in cases where the predicate does not match
16715     * a single unique view (perhaps multiple views use the same id)
16716     * and we are trying to find the view that is "closest" in scope to the
16717     * starting view.
16718     *
16719     * @param start The view to start from.
16720     * @param predicate The predicate to evaluate.
16721     * @return The first view that matches the predicate or null.
16722     */
16723    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16724        View childToSkip = null;
16725        for (;;) {
16726            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16727            if (view != null || start == this) {
16728                return view;
16729            }
16730
16731            ViewParent parent = start.getParent();
16732            if (parent == null || !(parent instanceof View)) {
16733                return null;
16734            }
16735
16736            childToSkip = start;
16737            start = (View) parent;
16738        }
16739    }
16740
16741    /**
16742     * Sets the identifier for this view. The identifier does not have to be
16743     * unique in this view's hierarchy. The identifier should be a positive
16744     * number.
16745     *
16746     * @see #NO_ID
16747     * @see #getId()
16748     * @see #findViewById(int)
16749     *
16750     * @param id a number used to identify the view
16751     *
16752     * @attr ref android.R.styleable#View_id
16753     */
16754    public void setId(int id) {
16755        mID = id;
16756        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16757            mID = generateViewId();
16758        }
16759    }
16760
16761    /**
16762     * {@hide}
16763     *
16764     * @param isRoot true if the view belongs to the root namespace, false
16765     *        otherwise
16766     */
16767    public void setIsRootNamespace(boolean isRoot) {
16768        if (isRoot) {
16769            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16770        } else {
16771            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16772        }
16773    }
16774
16775    /**
16776     * {@hide}
16777     *
16778     * @return true if the view belongs to the root namespace, false otherwise
16779     */
16780    public boolean isRootNamespace() {
16781        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16782    }
16783
16784    /**
16785     * Returns this view's identifier.
16786     *
16787     * @return a positive integer used to identify the view or {@link #NO_ID}
16788     *         if the view has no ID
16789     *
16790     * @see #setId(int)
16791     * @see #findViewById(int)
16792     * @attr ref android.R.styleable#View_id
16793     */
16794    @ViewDebug.CapturedViewProperty
16795    public int getId() {
16796        return mID;
16797    }
16798
16799    /**
16800     * Returns this view's tag.
16801     *
16802     * @return the Object stored in this view as a tag, or {@code null} if not
16803     *         set
16804     *
16805     * @see #setTag(Object)
16806     * @see #getTag(int)
16807     */
16808    @ViewDebug.ExportedProperty
16809    public Object getTag() {
16810        return mTag;
16811    }
16812
16813    /**
16814     * Sets the tag associated with this view. A tag can be used to mark
16815     * a view in its hierarchy and does not have to be unique within the
16816     * hierarchy. Tags can also be used to store data within a view without
16817     * resorting to another data structure.
16818     *
16819     * @param tag an Object to tag the view with
16820     *
16821     * @see #getTag()
16822     * @see #setTag(int, Object)
16823     */
16824    public void setTag(final Object tag) {
16825        mTag = tag;
16826    }
16827
16828    /**
16829     * Returns the tag associated with this view and the specified key.
16830     *
16831     * @param key The key identifying the tag
16832     *
16833     * @return the Object stored in this view as a tag, or {@code null} if not
16834     *         set
16835     *
16836     * @see #setTag(int, Object)
16837     * @see #getTag()
16838     */
16839    public Object getTag(int key) {
16840        if (mKeyedTags != null) return mKeyedTags.get(key);
16841        return null;
16842    }
16843
16844    /**
16845     * Sets a tag associated with this view and a key. A tag can be used
16846     * to mark a view in its hierarchy and does not have to be unique within
16847     * the hierarchy. Tags can also be used to store data within a view
16848     * without resorting to another data structure.
16849     *
16850     * The specified key should be an id declared in the resources of the
16851     * application to ensure it is unique (see the <a
16852     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16853     * Keys identified as belonging to
16854     * the Android framework or not associated with any package will cause
16855     * an {@link IllegalArgumentException} to be thrown.
16856     *
16857     * @param key The key identifying the tag
16858     * @param tag An Object to tag the view with
16859     *
16860     * @throws IllegalArgumentException If they specified key is not valid
16861     *
16862     * @see #setTag(Object)
16863     * @see #getTag(int)
16864     */
16865    public void setTag(int key, final Object tag) {
16866        // If the package id is 0x00 or 0x01, it's either an undefined package
16867        // or a framework id
16868        if ((key >>> 24) < 2) {
16869            throw new IllegalArgumentException("The key must be an application-specific "
16870                    + "resource id.");
16871        }
16872
16873        setKeyedTag(key, tag);
16874    }
16875
16876    /**
16877     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16878     * framework id.
16879     *
16880     * @hide
16881     */
16882    public void setTagInternal(int key, Object tag) {
16883        if ((key >>> 24) != 0x1) {
16884            throw new IllegalArgumentException("The key must be a framework-specific "
16885                    + "resource id.");
16886        }
16887
16888        setKeyedTag(key, tag);
16889    }
16890
16891    private void setKeyedTag(int key, Object tag) {
16892        if (mKeyedTags == null) {
16893            mKeyedTags = new SparseArray<Object>(2);
16894        }
16895
16896        mKeyedTags.put(key, tag);
16897    }
16898
16899    /**
16900     * Prints information about this view in the log output, with the tag
16901     * {@link #VIEW_LOG_TAG}.
16902     *
16903     * @hide
16904     */
16905    public void debug() {
16906        debug(0);
16907    }
16908
16909    /**
16910     * Prints information about this view in the log output, with the tag
16911     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16912     * indentation defined by the <code>depth</code>.
16913     *
16914     * @param depth the indentation level
16915     *
16916     * @hide
16917     */
16918    protected void debug(int depth) {
16919        String output = debugIndent(depth - 1);
16920
16921        output += "+ " + this;
16922        int id = getId();
16923        if (id != -1) {
16924            output += " (id=" + id + ")";
16925        }
16926        Object tag = getTag();
16927        if (tag != null) {
16928            output += " (tag=" + tag + ")";
16929        }
16930        Log.d(VIEW_LOG_TAG, output);
16931
16932        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16933            output = debugIndent(depth) + " FOCUSED";
16934            Log.d(VIEW_LOG_TAG, output);
16935        }
16936
16937        output = debugIndent(depth);
16938        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16939                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16940                + "} ";
16941        Log.d(VIEW_LOG_TAG, output);
16942
16943        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16944                || mPaddingBottom != 0) {
16945            output = debugIndent(depth);
16946            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16947                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16948            Log.d(VIEW_LOG_TAG, output);
16949        }
16950
16951        output = debugIndent(depth);
16952        output += "mMeasureWidth=" + mMeasuredWidth +
16953                " mMeasureHeight=" + mMeasuredHeight;
16954        Log.d(VIEW_LOG_TAG, output);
16955
16956        output = debugIndent(depth);
16957        if (mLayoutParams == null) {
16958            output += "BAD! no layout params";
16959        } else {
16960            output = mLayoutParams.debug(output);
16961        }
16962        Log.d(VIEW_LOG_TAG, output);
16963
16964        output = debugIndent(depth);
16965        output += "flags={";
16966        output += View.printFlags(mViewFlags);
16967        output += "}";
16968        Log.d(VIEW_LOG_TAG, output);
16969
16970        output = debugIndent(depth);
16971        output += "privateFlags={";
16972        output += View.printPrivateFlags(mPrivateFlags);
16973        output += "}";
16974        Log.d(VIEW_LOG_TAG, output);
16975    }
16976
16977    /**
16978     * Creates a string of whitespaces used for indentation.
16979     *
16980     * @param depth the indentation level
16981     * @return a String containing (depth * 2 + 3) * 2 white spaces
16982     *
16983     * @hide
16984     */
16985    protected static String debugIndent(int depth) {
16986        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16987        for (int i = 0; i < (depth * 2) + 3; i++) {
16988            spaces.append(' ').append(' ');
16989        }
16990        return spaces.toString();
16991    }
16992
16993    /**
16994     * <p>Return the offset of the widget's text baseline from the widget's top
16995     * boundary. If this widget does not support baseline alignment, this
16996     * method returns -1. </p>
16997     *
16998     * @return the offset of the baseline within the widget's bounds or -1
16999     *         if baseline alignment is not supported
17000     */
17001    @ViewDebug.ExportedProperty(category = "layout")
17002    public int getBaseline() {
17003        return -1;
17004    }
17005
17006    /**
17007     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17008     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17009     * a layout pass.
17010     *
17011     * @return whether the view hierarchy is currently undergoing a layout pass
17012     */
17013    public boolean isInLayout() {
17014        ViewRootImpl viewRoot = getViewRootImpl();
17015        return (viewRoot != null && viewRoot.isInLayout());
17016    }
17017
17018    /**
17019     * Call this when something has changed which has invalidated the
17020     * layout of this view. This will schedule a layout pass of the view
17021     * tree. This should not be called while the view hierarchy is currently in a layout
17022     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17023     * end of the current layout pass (and then layout will run again) or after the current
17024     * frame is drawn and the next layout occurs.
17025     *
17026     * <p>Subclasses which override this method should call the superclass method to
17027     * handle possible request-during-layout errors correctly.</p>
17028     */
17029    public void requestLayout() {
17030        if (mMeasureCache != null) mMeasureCache.clear();
17031
17032        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17033            // Only trigger request-during-layout logic if this is the view requesting it,
17034            // not the views in its parent hierarchy
17035            ViewRootImpl viewRoot = getViewRootImpl();
17036            if (viewRoot != null && viewRoot.isInLayout()) {
17037                if (!viewRoot.requestLayoutDuringLayout(this)) {
17038                    return;
17039                }
17040            }
17041            mAttachInfo.mViewRequestingLayout = this;
17042        }
17043
17044        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17045        mPrivateFlags |= PFLAG_INVALIDATED;
17046
17047        if (mParent != null && !mParent.isLayoutRequested()) {
17048            mParent.requestLayout();
17049        }
17050        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17051            mAttachInfo.mViewRequestingLayout = null;
17052        }
17053    }
17054
17055    /**
17056     * Forces this view to be laid out during the next layout pass.
17057     * This method does not call requestLayout() or forceLayout()
17058     * on the parent.
17059     */
17060    public void forceLayout() {
17061        if (mMeasureCache != null) mMeasureCache.clear();
17062
17063        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17064        mPrivateFlags |= PFLAG_INVALIDATED;
17065    }
17066
17067    /**
17068     * <p>
17069     * This is called to find out how big a view should be. The parent
17070     * supplies constraint information in the width and height parameters.
17071     * </p>
17072     *
17073     * <p>
17074     * The actual measurement work of a view is performed in
17075     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17076     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17077     * </p>
17078     *
17079     *
17080     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17081     *        parent
17082     * @param heightMeasureSpec Vertical space requirements as imposed by the
17083     *        parent
17084     *
17085     * @see #onMeasure(int, int)
17086     */
17087    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17088        boolean optical = isLayoutModeOptical(this);
17089        if (optical != isLayoutModeOptical(mParent)) {
17090            Insets insets = getOpticalInsets();
17091            int oWidth  = insets.left + insets.right;
17092            int oHeight = insets.top  + insets.bottom;
17093            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17094            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17095        }
17096
17097        // Suppress sign extension for the low bytes
17098        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17099        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17100
17101        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17102                widthMeasureSpec != mOldWidthMeasureSpec ||
17103                heightMeasureSpec != mOldHeightMeasureSpec) {
17104
17105            // first clears the measured dimension flag
17106            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17107
17108            resolveRtlPropertiesIfNeeded();
17109
17110            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17111                    mMeasureCache.indexOfKey(key);
17112            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17113                // measure ourselves, this should set the measured dimension flag back
17114                onMeasure(widthMeasureSpec, heightMeasureSpec);
17115                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17116            } else {
17117                long value = mMeasureCache.valueAt(cacheIndex);
17118                // Casting a long to int drops the high 32 bits, no mask needed
17119                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17120                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17121            }
17122
17123            // flag not set, setMeasuredDimension() was not invoked, we raise
17124            // an exception to warn the developer
17125            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17126                throw new IllegalStateException("onMeasure() did not set the"
17127                        + " measured dimension by calling"
17128                        + " setMeasuredDimension()");
17129            }
17130
17131            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17132        }
17133
17134        mOldWidthMeasureSpec = widthMeasureSpec;
17135        mOldHeightMeasureSpec = heightMeasureSpec;
17136
17137        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17138                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17139    }
17140
17141    /**
17142     * <p>
17143     * Measure the view and its content to determine the measured width and the
17144     * measured height. This method is invoked by {@link #measure(int, int)} and
17145     * should be overriden by subclasses to provide accurate and efficient
17146     * measurement of their contents.
17147     * </p>
17148     *
17149     * <p>
17150     * <strong>CONTRACT:</strong> When overriding this method, you
17151     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17152     * measured width and height of this view. Failure to do so will trigger an
17153     * <code>IllegalStateException</code>, thrown by
17154     * {@link #measure(int, int)}. Calling the superclass'
17155     * {@link #onMeasure(int, int)} is a valid use.
17156     * </p>
17157     *
17158     * <p>
17159     * The base class implementation of measure defaults to the background size,
17160     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17161     * override {@link #onMeasure(int, int)} to provide better measurements of
17162     * their content.
17163     * </p>
17164     *
17165     * <p>
17166     * If this method is overridden, it is the subclass's responsibility to make
17167     * sure the measured height and width are at least the view's minimum height
17168     * and width ({@link #getSuggestedMinimumHeight()} and
17169     * {@link #getSuggestedMinimumWidth()}).
17170     * </p>
17171     *
17172     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17173     *                         The requirements are encoded with
17174     *                         {@link android.view.View.MeasureSpec}.
17175     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17176     *                         The requirements are encoded with
17177     *                         {@link android.view.View.MeasureSpec}.
17178     *
17179     * @see #getMeasuredWidth()
17180     * @see #getMeasuredHeight()
17181     * @see #setMeasuredDimension(int, int)
17182     * @see #getSuggestedMinimumHeight()
17183     * @see #getSuggestedMinimumWidth()
17184     * @see android.view.View.MeasureSpec#getMode(int)
17185     * @see android.view.View.MeasureSpec#getSize(int)
17186     */
17187    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17188        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17189                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17190    }
17191
17192    /**
17193     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17194     * measured width and measured height. Failing to do so will trigger an
17195     * exception at measurement time.</p>
17196     *
17197     * @param measuredWidth The measured width of this view.  May be a complex
17198     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17199     * {@link #MEASURED_STATE_TOO_SMALL}.
17200     * @param measuredHeight The measured height of this view.  May be a complex
17201     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17202     * {@link #MEASURED_STATE_TOO_SMALL}.
17203     */
17204    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17205        boolean optical = isLayoutModeOptical(this);
17206        if (optical != isLayoutModeOptical(mParent)) {
17207            Insets insets = getOpticalInsets();
17208            int opticalWidth  = insets.left + insets.right;
17209            int opticalHeight = insets.top  + insets.bottom;
17210
17211            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17212            measuredHeight += optical ? opticalHeight : -opticalHeight;
17213        }
17214        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17215    }
17216
17217    /**
17218     * Sets the measured dimension without extra processing for things like optical bounds.
17219     * Useful for reapplying consistent values that have already been cooked with adjustments
17220     * for optical bounds, etc. such as those from the measurement cache.
17221     *
17222     * @param measuredWidth The measured width of this view.  May be a complex
17223     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17224     * {@link #MEASURED_STATE_TOO_SMALL}.
17225     * @param measuredHeight The measured height of this view.  May be a complex
17226     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17227     * {@link #MEASURED_STATE_TOO_SMALL}.
17228     */
17229    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17230        mMeasuredWidth = measuredWidth;
17231        mMeasuredHeight = measuredHeight;
17232
17233        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17234    }
17235
17236    /**
17237     * Merge two states as returned by {@link #getMeasuredState()}.
17238     * @param curState The current state as returned from a view or the result
17239     * of combining multiple views.
17240     * @param newState The new view state to combine.
17241     * @return Returns a new integer reflecting the combination of the two
17242     * states.
17243     */
17244    public static int combineMeasuredStates(int curState, int newState) {
17245        return curState | newState;
17246    }
17247
17248    /**
17249     * Version of {@link #resolveSizeAndState(int, int, int)}
17250     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17251     */
17252    public static int resolveSize(int size, int measureSpec) {
17253        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17254    }
17255
17256    /**
17257     * Utility to reconcile a desired size and state, with constraints imposed
17258     * by a MeasureSpec.  Will take the desired size, unless a different size
17259     * is imposed by the constraints.  The returned value is a compound integer,
17260     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17261     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17262     * size is smaller than the size the view wants to be.
17263     *
17264     * @param size How big the view wants to be
17265     * @param measureSpec Constraints imposed by the parent
17266     * @return Size information bit mask as defined by
17267     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17268     */
17269    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17270        int result = size;
17271        int specMode = MeasureSpec.getMode(measureSpec);
17272        int specSize =  MeasureSpec.getSize(measureSpec);
17273        switch (specMode) {
17274        case MeasureSpec.UNSPECIFIED:
17275            result = size;
17276            break;
17277        case MeasureSpec.AT_MOST:
17278            if (specSize < size) {
17279                result = specSize | MEASURED_STATE_TOO_SMALL;
17280            } else {
17281                result = size;
17282            }
17283            break;
17284        case MeasureSpec.EXACTLY:
17285            result = specSize;
17286            break;
17287        }
17288        return result | (childMeasuredState&MEASURED_STATE_MASK);
17289    }
17290
17291    /**
17292     * Utility to return a default size. Uses the supplied size if the
17293     * MeasureSpec imposed no constraints. Will get larger if allowed
17294     * by the MeasureSpec.
17295     *
17296     * @param size Default size for this view
17297     * @param measureSpec Constraints imposed by the parent
17298     * @return The size this view should be.
17299     */
17300    public static int getDefaultSize(int size, int measureSpec) {
17301        int result = size;
17302        int specMode = MeasureSpec.getMode(measureSpec);
17303        int specSize = MeasureSpec.getSize(measureSpec);
17304
17305        switch (specMode) {
17306        case MeasureSpec.UNSPECIFIED:
17307            result = size;
17308            break;
17309        case MeasureSpec.AT_MOST:
17310        case MeasureSpec.EXACTLY:
17311            result = specSize;
17312            break;
17313        }
17314        return result;
17315    }
17316
17317    /**
17318     * Returns the suggested minimum height that the view should use. This
17319     * returns the maximum of the view's minimum height
17320     * and the background's minimum height
17321     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17322     * <p>
17323     * When being used in {@link #onMeasure(int, int)}, the caller should still
17324     * ensure the returned height is within the requirements of the parent.
17325     *
17326     * @return The suggested minimum height of the view.
17327     */
17328    protected int getSuggestedMinimumHeight() {
17329        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17330
17331    }
17332
17333    /**
17334     * Returns the suggested minimum width that the view should use. This
17335     * returns the maximum of the view's minimum width)
17336     * and the background's minimum width
17337     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17338     * <p>
17339     * When being used in {@link #onMeasure(int, int)}, the caller should still
17340     * ensure the returned width is within the requirements of the parent.
17341     *
17342     * @return The suggested minimum width of the view.
17343     */
17344    protected int getSuggestedMinimumWidth() {
17345        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17346    }
17347
17348    /**
17349     * Returns the minimum height of the view.
17350     *
17351     * @return the minimum height the view will try to be.
17352     *
17353     * @see #setMinimumHeight(int)
17354     *
17355     * @attr ref android.R.styleable#View_minHeight
17356     */
17357    public int getMinimumHeight() {
17358        return mMinHeight;
17359    }
17360
17361    /**
17362     * Sets the minimum height of the view. It is not guaranteed the view will
17363     * be able to achieve this minimum height (for example, if its parent layout
17364     * constrains it with less available height).
17365     *
17366     * @param minHeight The minimum height the view will try to be.
17367     *
17368     * @see #getMinimumHeight()
17369     *
17370     * @attr ref android.R.styleable#View_minHeight
17371     */
17372    public void setMinimumHeight(int minHeight) {
17373        mMinHeight = minHeight;
17374        requestLayout();
17375    }
17376
17377    /**
17378     * Returns the minimum width of the view.
17379     *
17380     * @return the minimum width the view will try to be.
17381     *
17382     * @see #setMinimumWidth(int)
17383     *
17384     * @attr ref android.R.styleable#View_minWidth
17385     */
17386    public int getMinimumWidth() {
17387        return mMinWidth;
17388    }
17389
17390    /**
17391     * Sets the minimum width of the view. It is not guaranteed the view will
17392     * be able to achieve this minimum width (for example, if its parent layout
17393     * constrains it with less available width).
17394     *
17395     * @param minWidth The minimum width the view will try to be.
17396     *
17397     * @see #getMinimumWidth()
17398     *
17399     * @attr ref android.R.styleable#View_minWidth
17400     */
17401    public void setMinimumWidth(int minWidth) {
17402        mMinWidth = minWidth;
17403        requestLayout();
17404
17405    }
17406
17407    /**
17408     * Get the animation currently associated with this view.
17409     *
17410     * @return The animation that is currently playing or
17411     *         scheduled to play for this view.
17412     */
17413    public Animation getAnimation() {
17414        return mCurrentAnimation;
17415    }
17416
17417    /**
17418     * Start the specified animation now.
17419     *
17420     * @param animation the animation to start now
17421     */
17422    public void startAnimation(Animation animation) {
17423        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17424        setAnimation(animation);
17425        invalidateParentCaches();
17426        invalidate(true);
17427    }
17428
17429    /**
17430     * Cancels any animations for this view.
17431     */
17432    public void clearAnimation() {
17433        if (mCurrentAnimation != null) {
17434            mCurrentAnimation.detach();
17435        }
17436        mCurrentAnimation = null;
17437        invalidateParentIfNeeded();
17438    }
17439
17440    /**
17441     * Sets the next animation to play for this view.
17442     * If you want the animation to play immediately, use
17443     * {@link #startAnimation(android.view.animation.Animation)} instead.
17444     * This method provides allows fine-grained
17445     * control over the start time and invalidation, but you
17446     * must make sure that 1) the animation has a start time set, and
17447     * 2) the view's parent (which controls animations on its children)
17448     * will be invalidated when the animation is supposed to
17449     * start.
17450     *
17451     * @param animation The next animation, or null.
17452     */
17453    public void setAnimation(Animation animation) {
17454        mCurrentAnimation = animation;
17455
17456        if (animation != null) {
17457            // If the screen is off assume the animation start time is now instead of
17458            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17459            // would cause the animation to start when the screen turns back on
17460            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
17461                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17462                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17463            }
17464            animation.reset();
17465        }
17466    }
17467
17468    /**
17469     * Invoked by a parent ViewGroup to notify the start of the animation
17470     * currently associated with this view. If you override this method,
17471     * always call super.onAnimationStart();
17472     *
17473     * @see #setAnimation(android.view.animation.Animation)
17474     * @see #getAnimation()
17475     */
17476    protected void onAnimationStart() {
17477        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17478    }
17479
17480    /**
17481     * Invoked by a parent ViewGroup to notify the end of the animation
17482     * currently associated with this view. If you override this method,
17483     * always call super.onAnimationEnd();
17484     *
17485     * @see #setAnimation(android.view.animation.Animation)
17486     * @see #getAnimation()
17487     */
17488    protected void onAnimationEnd() {
17489        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17490    }
17491
17492    /**
17493     * Invoked if there is a Transform that involves alpha. Subclass that can
17494     * draw themselves with the specified alpha should return true, and then
17495     * respect that alpha when their onDraw() is called. If this returns false
17496     * then the view may be redirected to draw into an offscreen buffer to
17497     * fulfill the request, which will look fine, but may be slower than if the
17498     * subclass handles it internally. The default implementation returns false.
17499     *
17500     * @param alpha The alpha (0..255) to apply to the view's drawing
17501     * @return true if the view can draw with the specified alpha.
17502     */
17503    protected boolean onSetAlpha(int alpha) {
17504        return false;
17505    }
17506
17507    /**
17508     * This is used by the RootView to perform an optimization when
17509     * the view hierarchy contains one or several SurfaceView.
17510     * SurfaceView is always considered transparent, but its children are not,
17511     * therefore all View objects remove themselves from the global transparent
17512     * region (passed as a parameter to this function).
17513     *
17514     * @param region The transparent region for this ViewAncestor (window).
17515     *
17516     * @return Returns true if the effective visibility of the view at this
17517     * point is opaque, regardless of the transparent region; returns false
17518     * if it is possible for underlying windows to be seen behind the view.
17519     *
17520     * {@hide}
17521     */
17522    public boolean gatherTransparentRegion(Region region) {
17523        final AttachInfo attachInfo = mAttachInfo;
17524        if (region != null && attachInfo != null) {
17525            final int pflags = mPrivateFlags;
17526            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17527                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17528                // remove it from the transparent region.
17529                final int[] location = attachInfo.mTransparentLocation;
17530                getLocationInWindow(location);
17531                region.op(location[0], location[1], location[0] + mRight - mLeft,
17532                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17533            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17534                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17535                // exists, so we remove the background drawable's non-transparent
17536                // parts from this transparent region.
17537                applyDrawableToTransparentRegion(mBackground, region);
17538            }
17539        }
17540        return true;
17541    }
17542
17543    /**
17544     * Play a sound effect for this view.
17545     *
17546     * <p>The framework will play sound effects for some built in actions, such as
17547     * clicking, but you may wish to play these effects in your widget,
17548     * for instance, for internal navigation.
17549     *
17550     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17551     * {@link #isSoundEffectsEnabled()} is true.
17552     *
17553     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17554     */
17555    public void playSoundEffect(int soundConstant) {
17556        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17557            return;
17558        }
17559        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17560    }
17561
17562    /**
17563     * BZZZTT!!1!
17564     *
17565     * <p>Provide haptic feedback to the user for this view.
17566     *
17567     * <p>The framework will provide haptic feedback for some built in actions,
17568     * such as long presses, but you may wish to provide feedback for your
17569     * own widget.
17570     *
17571     * <p>The feedback will only be performed if
17572     * {@link #isHapticFeedbackEnabled()} is true.
17573     *
17574     * @param feedbackConstant One of the constants defined in
17575     * {@link HapticFeedbackConstants}
17576     */
17577    public boolean performHapticFeedback(int feedbackConstant) {
17578        return performHapticFeedback(feedbackConstant, 0);
17579    }
17580
17581    /**
17582     * BZZZTT!!1!
17583     *
17584     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17585     *
17586     * @param feedbackConstant One of the constants defined in
17587     * {@link HapticFeedbackConstants}
17588     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17589     */
17590    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17591        if (mAttachInfo == null) {
17592            return false;
17593        }
17594        //noinspection SimplifiableIfStatement
17595        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17596                && !isHapticFeedbackEnabled()) {
17597            return false;
17598        }
17599        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17600                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17601    }
17602
17603    /**
17604     * Request that the visibility of the status bar or other screen/window
17605     * decorations be changed.
17606     *
17607     * <p>This method is used to put the over device UI into temporary modes
17608     * where the user's attention is focused more on the application content,
17609     * by dimming or hiding surrounding system affordances.  This is typically
17610     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17611     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17612     * to be placed behind the action bar (and with these flags other system
17613     * affordances) so that smooth transitions between hiding and showing them
17614     * can be done.
17615     *
17616     * <p>Two representative examples of the use of system UI visibility is
17617     * implementing a content browsing application (like a magazine reader)
17618     * and a video playing application.
17619     *
17620     * <p>The first code shows a typical implementation of a View in a content
17621     * browsing application.  In this implementation, the application goes
17622     * into a content-oriented mode by hiding the status bar and action bar,
17623     * and putting the navigation elements into lights out mode.  The user can
17624     * then interact with content while in this mode.  Such an application should
17625     * provide an easy way for the user to toggle out of the mode (such as to
17626     * check information in the status bar or access notifications).  In the
17627     * implementation here, this is done simply by tapping on the content.
17628     *
17629     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17630     *      content}
17631     *
17632     * <p>This second code sample shows a typical implementation of a View
17633     * in a video playing application.  In this situation, while the video is
17634     * playing the application would like to go into a complete full-screen mode,
17635     * to use as much of the display as possible for the video.  When in this state
17636     * the user can not interact with the application; the system intercepts
17637     * touching on the screen to pop the UI out of full screen mode.  See
17638     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17639     *
17640     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17641     *      content}
17642     *
17643     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17644     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17645     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17646     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17647     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17648     */
17649    public void setSystemUiVisibility(int visibility) {
17650        if (visibility != mSystemUiVisibility) {
17651            mSystemUiVisibility = visibility;
17652            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17653                mParent.recomputeViewAttributes(this);
17654            }
17655        }
17656    }
17657
17658    /**
17659     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17660     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17661     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17662     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17663     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17664     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17665     */
17666    public int getSystemUiVisibility() {
17667        return mSystemUiVisibility;
17668    }
17669
17670    /**
17671     * Returns the current system UI visibility that is currently set for
17672     * the entire window.  This is the combination of the
17673     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17674     * views in the window.
17675     */
17676    public int getWindowSystemUiVisibility() {
17677        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17678    }
17679
17680    /**
17681     * Override to find out when the window's requested system UI visibility
17682     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17683     * This is different from the callbacks received through
17684     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17685     * in that this is only telling you about the local request of the window,
17686     * not the actual values applied by the system.
17687     */
17688    public void onWindowSystemUiVisibilityChanged(int visible) {
17689    }
17690
17691    /**
17692     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17693     * the view hierarchy.
17694     */
17695    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17696        onWindowSystemUiVisibilityChanged(visible);
17697    }
17698
17699    /**
17700     * Set a listener to receive callbacks when the visibility of the system bar changes.
17701     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17702     */
17703    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17704        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17705        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17706            mParent.recomputeViewAttributes(this);
17707        }
17708    }
17709
17710    /**
17711     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17712     * the view hierarchy.
17713     */
17714    public void dispatchSystemUiVisibilityChanged(int visibility) {
17715        ListenerInfo li = mListenerInfo;
17716        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17717            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17718                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17719        }
17720    }
17721
17722    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17723        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17724        if (val != mSystemUiVisibility) {
17725            setSystemUiVisibility(val);
17726            return true;
17727        }
17728        return false;
17729    }
17730
17731    /** @hide */
17732    public void setDisabledSystemUiVisibility(int flags) {
17733        if (mAttachInfo != null) {
17734            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17735                mAttachInfo.mDisabledSystemUiVisibility = flags;
17736                if (mParent != null) {
17737                    mParent.recomputeViewAttributes(this);
17738                }
17739            }
17740        }
17741    }
17742
17743    /**
17744     * Creates an image that the system displays during the drag and drop
17745     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17746     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17747     * appearance as the given View. The default also positions the center of the drag shadow
17748     * directly under the touch point. If no View is provided (the constructor with no parameters
17749     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17750     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17751     * default is an invisible drag shadow.
17752     * <p>
17753     * You are not required to use the View you provide to the constructor as the basis of the
17754     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17755     * anything you want as the drag shadow.
17756     * </p>
17757     * <p>
17758     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17759     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17760     *  size and position of the drag shadow. It uses this data to construct a
17761     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17762     *  so that your application can draw the shadow image in the Canvas.
17763     * </p>
17764     *
17765     * <div class="special reference">
17766     * <h3>Developer Guides</h3>
17767     * <p>For a guide to implementing drag and drop features, read the
17768     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17769     * </div>
17770     */
17771    public static class DragShadowBuilder {
17772        private final WeakReference<View> mView;
17773
17774        /**
17775         * Constructs a shadow image builder based on a View. By default, the resulting drag
17776         * shadow will have the same appearance and dimensions as the View, with the touch point
17777         * over the center of the View.
17778         * @param view A View. Any View in scope can be used.
17779         */
17780        public DragShadowBuilder(View view) {
17781            mView = new WeakReference<View>(view);
17782        }
17783
17784        /**
17785         * Construct a shadow builder object with no associated View.  This
17786         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17787         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17788         * to supply the drag shadow's dimensions and appearance without
17789         * reference to any View object. If they are not overridden, then the result is an
17790         * invisible drag shadow.
17791         */
17792        public DragShadowBuilder() {
17793            mView = new WeakReference<View>(null);
17794        }
17795
17796        /**
17797         * Returns the View object that had been passed to the
17798         * {@link #View.DragShadowBuilder(View)}
17799         * constructor.  If that View parameter was {@code null} or if the
17800         * {@link #View.DragShadowBuilder()}
17801         * constructor was used to instantiate the builder object, this method will return
17802         * null.
17803         *
17804         * @return The View object associate with this builder object.
17805         */
17806        @SuppressWarnings({"JavadocReference"})
17807        final public View getView() {
17808            return mView.get();
17809        }
17810
17811        /**
17812         * Provides the metrics for the shadow image. These include the dimensions of
17813         * the shadow image, and the point within that shadow that should
17814         * be centered under the touch location while dragging.
17815         * <p>
17816         * The default implementation sets the dimensions of the shadow to be the
17817         * same as the dimensions of the View itself and centers the shadow under
17818         * the touch point.
17819         * </p>
17820         *
17821         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17822         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17823         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17824         * image.
17825         *
17826         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17827         * shadow image that should be underneath the touch point during the drag and drop
17828         * operation. Your application must set {@link android.graphics.Point#x} to the
17829         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17830         */
17831        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17832            final View view = mView.get();
17833            if (view != null) {
17834                shadowSize.set(view.getWidth(), view.getHeight());
17835                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17836            } else {
17837                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17838            }
17839        }
17840
17841        /**
17842         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17843         * based on the dimensions it received from the
17844         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17845         *
17846         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17847         */
17848        public void onDrawShadow(Canvas canvas) {
17849            final View view = mView.get();
17850            if (view != null) {
17851                view.draw(canvas);
17852            } else {
17853                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17854            }
17855        }
17856    }
17857
17858    /**
17859     * Starts a drag and drop operation. When your application calls this method, it passes a
17860     * {@link android.view.View.DragShadowBuilder} object to the system. The
17861     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17862     * to get metrics for the drag shadow, and then calls the object's
17863     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17864     * <p>
17865     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17866     *  drag events to all the View objects in your application that are currently visible. It does
17867     *  this either by calling the View object's drag listener (an implementation of
17868     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17869     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17870     *  Both are passed a {@link android.view.DragEvent} object that has a
17871     *  {@link android.view.DragEvent#getAction()} value of
17872     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17873     * </p>
17874     * <p>
17875     * Your application can invoke startDrag() on any attached View object. The View object does not
17876     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17877     * be related to the View the user selected for dragging.
17878     * </p>
17879     * @param data A {@link android.content.ClipData} object pointing to the data to be
17880     * transferred by the drag and drop operation.
17881     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17882     * drag shadow.
17883     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17884     * drop operation. This Object is put into every DragEvent object sent by the system during the
17885     * current drag.
17886     * <p>
17887     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17888     * to the target Views. For example, it can contain flags that differentiate between a
17889     * a copy operation and a move operation.
17890     * </p>
17891     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17892     * so the parameter should be set to 0.
17893     * @return {@code true} if the method completes successfully, or
17894     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17895     * do a drag, and so no drag operation is in progress.
17896     */
17897    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17898            Object myLocalState, int flags) {
17899        if (ViewDebug.DEBUG_DRAG) {
17900            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17901        }
17902        boolean okay = false;
17903
17904        Point shadowSize = new Point();
17905        Point shadowTouchPoint = new Point();
17906        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17907
17908        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17909                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17910            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17911        }
17912
17913        if (ViewDebug.DEBUG_DRAG) {
17914            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17915                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17916        }
17917        Surface surface = new Surface();
17918        try {
17919            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17920                    flags, shadowSize.x, shadowSize.y, surface);
17921            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17922                    + " surface=" + surface);
17923            if (token != null) {
17924                Canvas canvas = surface.lockCanvas(null);
17925                try {
17926                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17927                    shadowBuilder.onDrawShadow(canvas);
17928                } finally {
17929                    surface.unlockCanvasAndPost(canvas);
17930                }
17931
17932                final ViewRootImpl root = getViewRootImpl();
17933
17934                // Cache the local state object for delivery with DragEvents
17935                root.setLocalDragState(myLocalState);
17936
17937                // repurpose 'shadowSize' for the last touch point
17938                root.getLastTouchPoint(shadowSize);
17939
17940                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17941                        shadowSize.x, shadowSize.y,
17942                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17943                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17944
17945                // Off and running!  Release our local surface instance; the drag
17946                // shadow surface is now managed by the system process.
17947                surface.release();
17948            }
17949        } catch (Exception e) {
17950            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17951            surface.destroy();
17952        }
17953
17954        return okay;
17955    }
17956
17957    /**
17958     * Handles drag events sent by the system following a call to
17959     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17960     *<p>
17961     * When the system calls this method, it passes a
17962     * {@link android.view.DragEvent} object. A call to
17963     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17964     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17965     * operation.
17966     * @param event The {@link android.view.DragEvent} sent by the system.
17967     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17968     * in DragEvent, indicating the type of drag event represented by this object.
17969     * @return {@code true} if the method was successful, otherwise {@code false}.
17970     * <p>
17971     *  The method should return {@code true} in response to an action type of
17972     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17973     *  operation.
17974     * </p>
17975     * <p>
17976     *  The method should also return {@code true} in response to an action type of
17977     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17978     *  {@code false} if it didn't.
17979     * </p>
17980     */
17981    public boolean onDragEvent(DragEvent event) {
17982        return false;
17983    }
17984
17985    /**
17986     * Detects if this View is enabled and has a drag event listener.
17987     * If both are true, then it calls the drag event listener with the
17988     * {@link android.view.DragEvent} it received. If the drag event listener returns
17989     * {@code true}, then dispatchDragEvent() returns {@code true}.
17990     * <p>
17991     * For all other cases, the method calls the
17992     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17993     * method and returns its result.
17994     * </p>
17995     * <p>
17996     * This ensures that a drag event is always consumed, even if the View does not have a drag
17997     * event listener. However, if the View has a listener and the listener returns true, then
17998     * onDragEvent() is not called.
17999     * </p>
18000     */
18001    public boolean dispatchDragEvent(DragEvent event) {
18002        ListenerInfo li = mListenerInfo;
18003        //noinspection SimplifiableIfStatement
18004        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18005                && li.mOnDragListener.onDrag(this, event)) {
18006            return true;
18007        }
18008        return onDragEvent(event);
18009    }
18010
18011    boolean canAcceptDrag() {
18012        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18013    }
18014
18015    /**
18016     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18017     * it is ever exposed at all.
18018     * @hide
18019     */
18020    public void onCloseSystemDialogs(String reason) {
18021    }
18022
18023    /**
18024     * Given a Drawable whose bounds have been set to draw into this view,
18025     * update a Region being computed for
18026     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18027     * that any non-transparent parts of the Drawable are removed from the
18028     * given transparent region.
18029     *
18030     * @param dr The Drawable whose transparency is to be applied to the region.
18031     * @param region A Region holding the current transparency information,
18032     * where any parts of the region that are set are considered to be
18033     * transparent.  On return, this region will be modified to have the
18034     * transparency information reduced by the corresponding parts of the
18035     * Drawable that are not transparent.
18036     * {@hide}
18037     */
18038    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18039        if (DBG) {
18040            Log.i("View", "Getting transparent region for: " + this);
18041        }
18042        final Region r = dr.getTransparentRegion();
18043        final Rect db = dr.getBounds();
18044        final AttachInfo attachInfo = mAttachInfo;
18045        if (r != null && attachInfo != null) {
18046            final int w = getRight()-getLeft();
18047            final int h = getBottom()-getTop();
18048            if (db.left > 0) {
18049                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18050                r.op(0, 0, db.left, h, Region.Op.UNION);
18051            }
18052            if (db.right < w) {
18053                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18054                r.op(db.right, 0, w, h, Region.Op.UNION);
18055            }
18056            if (db.top > 0) {
18057                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18058                r.op(0, 0, w, db.top, Region.Op.UNION);
18059            }
18060            if (db.bottom < h) {
18061                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18062                r.op(0, db.bottom, w, h, Region.Op.UNION);
18063            }
18064            final int[] location = attachInfo.mTransparentLocation;
18065            getLocationInWindow(location);
18066            r.translate(location[0], location[1]);
18067            region.op(r, Region.Op.INTERSECT);
18068        } else {
18069            region.op(db, Region.Op.DIFFERENCE);
18070        }
18071    }
18072
18073    private void checkForLongClick(int delayOffset) {
18074        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18075            mHasPerformedLongPress = false;
18076
18077            if (mPendingCheckForLongPress == null) {
18078                mPendingCheckForLongPress = new CheckForLongPress();
18079            }
18080            mPendingCheckForLongPress.rememberWindowAttachCount();
18081            postDelayed(mPendingCheckForLongPress,
18082                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18083        }
18084    }
18085
18086    /**
18087     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18088     * LayoutInflater} class, which provides a full range of options for view inflation.
18089     *
18090     * @param context The Context object for your activity or application.
18091     * @param resource The resource ID to inflate
18092     * @param root A view group that will be the parent.  Used to properly inflate the
18093     * layout_* parameters.
18094     * @see LayoutInflater
18095     */
18096    public static View inflate(Context context, int resource, ViewGroup root) {
18097        LayoutInflater factory = LayoutInflater.from(context);
18098        return factory.inflate(resource, root);
18099    }
18100
18101    /**
18102     * Scroll the view with standard behavior for scrolling beyond the normal
18103     * content boundaries. Views that call this method should override
18104     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18105     * results of an over-scroll operation.
18106     *
18107     * Views can use this method to handle any touch or fling-based scrolling.
18108     *
18109     * @param deltaX Change in X in pixels
18110     * @param deltaY Change in Y in pixels
18111     * @param scrollX Current X scroll value in pixels before applying deltaX
18112     * @param scrollY Current Y scroll value in pixels before applying deltaY
18113     * @param scrollRangeX Maximum content scroll range along the X axis
18114     * @param scrollRangeY Maximum content scroll range along the Y axis
18115     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18116     *          along the X axis.
18117     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18118     *          along the Y axis.
18119     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18120     * @return true if scrolling was clamped to an over-scroll boundary along either
18121     *          axis, false otherwise.
18122     */
18123    @SuppressWarnings({"UnusedParameters"})
18124    protected boolean overScrollBy(int deltaX, int deltaY,
18125            int scrollX, int scrollY,
18126            int scrollRangeX, int scrollRangeY,
18127            int maxOverScrollX, int maxOverScrollY,
18128            boolean isTouchEvent) {
18129        final int overScrollMode = mOverScrollMode;
18130        final boolean canScrollHorizontal =
18131                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18132        final boolean canScrollVertical =
18133                computeVerticalScrollRange() > computeVerticalScrollExtent();
18134        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18135                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18136        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18137                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18138
18139        int newScrollX = scrollX + deltaX;
18140        if (!overScrollHorizontal) {
18141            maxOverScrollX = 0;
18142        }
18143
18144        int newScrollY = scrollY + deltaY;
18145        if (!overScrollVertical) {
18146            maxOverScrollY = 0;
18147        }
18148
18149        // Clamp values if at the limits and record
18150        final int left = -maxOverScrollX;
18151        final int right = maxOverScrollX + scrollRangeX;
18152        final int top = -maxOverScrollY;
18153        final int bottom = maxOverScrollY + scrollRangeY;
18154
18155        boolean clampedX = false;
18156        if (newScrollX > right) {
18157            newScrollX = right;
18158            clampedX = true;
18159        } else if (newScrollX < left) {
18160            newScrollX = left;
18161            clampedX = true;
18162        }
18163
18164        boolean clampedY = false;
18165        if (newScrollY > bottom) {
18166            newScrollY = bottom;
18167            clampedY = true;
18168        } else if (newScrollY < top) {
18169            newScrollY = top;
18170            clampedY = true;
18171        }
18172
18173        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18174
18175        return clampedX || clampedY;
18176    }
18177
18178    /**
18179     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18180     * respond to the results of an over-scroll operation.
18181     *
18182     * @param scrollX New X scroll value in pixels
18183     * @param scrollY New Y scroll value in pixels
18184     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18185     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18186     */
18187    protected void onOverScrolled(int scrollX, int scrollY,
18188            boolean clampedX, boolean clampedY) {
18189        // Intentionally empty.
18190    }
18191
18192    /**
18193     * Returns the over-scroll mode for this view. The result will be
18194     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18195     * (allow over-scrolling only if the view content is larger than the container),
18196     * or {@link #OVER_SCROLL_NEVER}.
18197     *
18198     * @return This view's over-scroll mode.
18199     */
18200    public int getOverScrollMode() {
18201        return mOverScrollMode;
18202    }
18203
18204    /**
18205     * Set the over-scroll mode for this view. Valid over-scroll modes are
18206     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18207     * (allow over-scrolling only if the view content is larger than the container),
18208     * or {@link #OVER_SCROLL_NEVER}.
18209     *
18210     * Setting the over-scroll mode of a view will have an effect only if the
18211     * view is capable of scrolling.
18212     *
18213     * @param overScrollMode The new over-scroll mode for this view.
18214     */
18215    public void setOverScrollMode(int overScrollMode) {
18216        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18217                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18218                overScrollMode != OVER_SCROLL_NEVER) {
18219            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18220        }
18221        mOverScrollMode = overScrollMode;
18222    }
18223
18224    /**
18225     * Gets a scale factor that determines the distance the view should scroll
18226     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18227     * @return The vertical scroll scale factor.
18228     * @hide
18229     */
18230    protected float getVerticalScrollFactor() {
18231        if (mVerticalScrollFactor == 0) {
18232            TypedValue outValue = new TypedValue();
18233            if (!mContext.getTheme().resolveAttribute(
18234                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18235                throw new IllegalStateException(
18236                        "Expected theme to define listPreferredItemHeight.");
18237            }
18238            mVerticalScrollFactor = outValue.getDimension(
18239                    mContext.getResources().getDisplayMetrics());
18240        }
18241        return mVerticalScrollFactor;
18242    }
18243
18244    /**
18245     * Gets a scale factor that determines the distance the view should scroll
18246     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18247     * @return The horizontal scroll scale factor.
18248     * @hide
18249     */
18250    protected float getHorizontalScrollFactor() {
18251        // TODO: Should use something else.
18252        return getVerticalScrollFactor();
18253    }
18254
18255    /**
18256     * Return the value specifying the text direction or policy that was set with
18257     * {@link #setTextDirection(int)}.
18258     *
18259     * @return the defined text direction. It can be one of:
18260     *
18261     * {@link #TEXT_DIRECTION_INHERIT},
18262     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18263     * {@link #TEXT_DIRECTION_ANY_RTL},
18264     * {@link #TEXT_DIRECTION_LTR},
18265     * {@link #TEXT_DIRECTION_RTL},
18266     * {@link #TEXT_DIRECTION_LOCALE}
18267     *
18268     * @attr ref android.R.styleable#View_textDirection
18269     *
18270     * @hide
18271     */
18272    @ViewDebug.ExportedProperty(category = "text", mapping = {
18273            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18274            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18275            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18276            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18277            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18278            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18279    })
18280    public int getRawTextDirection() {
18281        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18282    }
18283
18284    /**
18285     * Set the text direction.
18286     *
18287     * @param textDirection the direction to set. Should be one of:
18288     *
18289     * {@link #TEXT_DIRECTION_INHERIT},
18290     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18291     * {@link #TEXT_DIRECTION_ANY_RTL},
18292     * {@link #TEXT_DIRECTION_LTR},
18293     * {@link #TEXT_DIRECTION_RTL},
18294     * {@link #TEXT_DIRECTION_LOCALE}
18295     *
18296     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18297     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18298     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18299     *
18300     * @attr ref android.R.styleable#View_textDirection
18301     */
18302    public void setTextDirection(int textDirection) {
18303        if (getRawTextDirection() != textDirection) {
18304            // Reset the current text direction and the resolved one
18305            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18306            resetResolvedTextDirection();
18307            // Set the new text direction
18308            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18309            // Do resolution
18310            resolveTextDirection();
18311            // Notify change
18312            onRtlPropertiesChanged(getLayoutDirection());
18313            // Refresh
18314            requestLayout();
18315            invalidate(true);
18316        }
18317    }
18318
18319    /**
18320     * Return the resolved text direction.
18321     *
18322     * @return the resolved text direction. Returns one of:
18323     *
18324     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18325     * {@link #TEXT_DIRECTION_ANY_RTL},
18326     * {@link #TEXT_DIRECTION_LTR},
18327     * {@link #TEXT_DIRECTION_RTL},
18328     * {@link #TEXT_DIRECTION_LOCALE}
18329     *
18330     * @attr ref android.R.styleable#View_textDirection
18331     */
18332    @ViewDebug.ExportedProperty(category = "text", mapping = {
18333            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18334            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18335            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18336            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18337            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18338            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18339    })
18340    public int getTextDirection() {
18341        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18342    }
18343
18344    /**
18345     * Resolve the text direction.
18346     *
18347     * @return true if resolution has been done, false otherwise.
18348     *
18349     * @hide
18350     */
18351    public boolean resolveTextDirection() {
18352        // Reset any previous text direction resolution
18353        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18354
18355        if (hasRtlSupport()) {
18356            // Set resolved text direction flag depending on text direction flag
18357            final int textDirection = getRawTextDirection();
18358            switch(textDirection) {
18359                case TEXT_DIRECTION_INHERIT:
18360                    if (!canResolveTextDirection()) {
18361                        // We cannot do the resolution if there is no parent, so use the default one
18362                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18363                        // Resolution will need to happen again later
18364                        return false;
18365                    }
18366
18367                    // Parent has not yet resolved, so we still return the default
18368                    try {
18369                        if (!mParent.isTextDirectionResolved()) {
18370                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18371                            // Resolution will need to happen again later
18372                            return false;
18373                        }
18374                    } catch (AbstractMethodError e) {
18375                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18376                                " does not fully implement ViewParent", e);
18377                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18378                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18379                        return true;
18380                    }
18381
18382                    // Set current resolved direction to the same value as the parent's one
18383                    int parentResolvedDirection;
18384                    try {
18385                        parentResolvedDirection = mParent.getTextDirection();
18386                    } catch (AbstractMethodError e) {
18387                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18388                                " does not fully implement ViewParent", e);
18389                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18390                    }
18391                    switch (parentResolvedDirection) {
18392                        case TEXT_DIRECTION_FIRST_STRONG:
18393                        case TEXT_DIRECTION_ANY_RTL:
18394                        case TEXT_DIRECTION_LTR:
18395                        case TEXT_DIRECTION_RTL:
18396                        case TEXT_DIRECTION_LOCALE:
18397                            mPrivateFlags2 |=
18398                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18399                            break;
18400                        default:
18401                            // Default resolved direction is "first strong" heuristic
18402                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18403                    }
18404                    break;
18405                case TEXT_DIRECTION_FIRST_STRONG:
18406                case TEXT_DIRECTION_ANY_RTL:
18407                case TEXT_DIRECTION_LTR:
18408                case TEXT_DIRECTION_RTL:
18409                case TEXT_DIRECTION_LOCALE:
18410                    // Resolved direction is the same as text direction
18411                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18412                    break;
18413                default:
18414                    // Default resolved direction is "first strong" heuristic
18415                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18416            }
18417        } else {
18418            // Default resolved direction is "first strong" heuristic
18419            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18420        }
18421
18422        // Set to resolved
18423        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18424        return true;
18425    }
18426
18427    /**
18428     * Check if text direction resolution can be done.
18429     *
18430     * @return true if text direction resolution can be done otherwise return false.
18431     */
18432    public boolean canResolveTextDirection() {
18433        switch (getRawTextDirection()) {
18434            case TEXT_DIRECTION_INHERIT:
18435                if (mParent != null) {
18436                    try {
18437                        return mParent.canResolveTextDirection();
18438                    } catch (AbstractMethodError e) {
18439                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18440                                " does not fully implement ViewParent", e);
18441                    }
18442                }
18443                return false;
18444
18445            default:
18446                return true;
18447        }
18448    }
18449
18450    /**
18451     * Reset resolved text direction. Text direction will be resolved during a call to
18452     * {@link #onMeasure(int, int)}.
18453     *
18454     * @hide
18455     */
18456    public void resetResolvedTextDirection() {
18457        // Reset any previous text direction resolution
18458        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18459        // Set to default value
18460        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18461    }
18462
18463    /**
18464     * @return true if text direction is inherited.
18465     *
18466     * @hide
18467     */
18468    public boolean isTextDirectionInherited() {
18469        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18470    }
18471
18472    /**
18473     * @return true if text direction is resolved.
18474     */
18475    public boolean isTextDirectionResolved() {
18476        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18477    }
18478
18479    /**
18480     * Return the value specifying the text alignment or policy that was set with
18481     * {@link #setTextAlignment(int)}.
18482     *
18483     * @return the defined text alignment. It can be one of:
18484     *
18485     * {@link #TEXT_ALIGNMENT_INHERIT},
18486     * {@link #TEXT_ALIGNMENT_GRAVITY},
18487     * {@link #TEXT_ALIGNMENT_CENTER},
18488     * {@link #TEXT_ALIGNMENT_TEXT_START},
18489     * {@link #TEXT_ALIGNMENT_TEXT_END},
18490     * {@link #TEXT_ALIGNMENT_VIEW_START},
18491     * {@link #TEXT_ALIGNMENT_VIEW_END}
18492     *
18493     * @attr ref android.R.styleable#View_textAlignment
18494     *
18495     * @hide
18496     */
18497    @ViewDebug.ExportedProperty(category = "text", mapping = {
18498            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18499            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18500            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18501            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18502            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18503            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18504            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18505    })
18506    @TextAlignment
18507    public int getRawTextAlignment() {
18508        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18509    }
18510
18511    /**
18512     * Set the text alignment.
18513     *
18514     * @param textAlignment The text alignment to set. Should be one of
18515     *
18516     * {@link #TEXT_ALIGNMENT_INHERIT},
18517     * {@link #TEXT_ALIGNMENT_GRAVITY},
18518     * {@link #TEXT_ALIGNMENT_CENTER},
18519     * {@link #TEXT_ALIGNMENT_TEXT_START},
18520     * {@link #TEXT_ALIGNMENT_TEXT_END},
18521     * {@link #TEXT_ALIGNMENT_VIEW_START},
18522     * {@link #TEXT_ALIGNMENT_VIEW_END}
18523     *
18524     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18525     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18526     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18527     *
18528     * @attr ref android.R.styleable#View_textAlignment
18529     */
18530    public void setTextAlignment(@TextAlignment int textAlignment) {
18531        if (textAlignment != getRawTextAlignment()) {
18532            // Reset the current and resolved text alignment
18533            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18534            resetResolvedTextAlignment();
18535            // Set the new text alignment
18536            mPrivateFlags2 |=
18537                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18538            // Do resolution
18539            resolveTextAlignment();
18540            // Notify change
18541            onRtlPropertiesChanged(getLayoutDirection());
18542            // Refresh
18543            requestLayout();
18544            invalidate(true);
18545        }
18546    }
18547
18548    /**
18549     * Return the resolved text alignment.
18550     *
18551     * @return the resolved text alignment. Returns one of:
18552     *
18553     * {@link #TEXT_ALIGNMENT_GRAVITY},
18554     * {@link #TEXT_ALIGNMENT_CENTER},
18555     * {@link #TEXT_ALIGNMENT_TEXT_START},
18556     * {@link #TEXT_ALIGNMENT_TEXT_END},
18557     * {@link #TEXT_ALIGNMENT_VIEW_START},
18558     * {@link #TEXT_ALIGNMENT_VIEW_END}
18559     *
18560     * @attr ref android.R.styleable#View_textAlignment
18561     */
18562    @ViewDebug.ExportedProperty(category = "text", mapping = {
18563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18566            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18568            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18569            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18570    })
18571    @TextAlignment
18572    public int getTextAlignment() {
18573        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18574                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18575    }
18576
18577    /**
18578     * Resolve the text alignment.
18579     *
18580     * @return true if resolution has been done, false otherwise.
18581     *
18582     * @hide
18583     */
18584    public boolean resolveTextAlignment() {
18585        // Reset any previous text alignment resolution
18586        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18587
18588        if (hasRtlSupport()) {
18589            // Set resolved text alignment flag depending on text alignment flag
18590            final int textAlignment = getRawTextAlignment();
18591            switch (textAlignment) {
18592                case TEXT_ALIGNMENT_INHERIT:
18593                    // Check if we can resolve the text alignment
18594                    if (!canResolveTextAlignment()) {
18595                        // We cannot do the resolution if there is no parent so use the default
18596                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18597                        // Resolution will need to happen again later
18598                        return false;
18599                    }
18600
18601                    // Parent has not yet resolved, so we still return the default
18602                    try {
18603                        if (!mParent.isTextAlignmentResolved()) {
18604                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18605                            // Resolution will need to happen again later
18606                            return false;
18607                        }
18608                    } catch (AbstractMethodError e) {
18609                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18610                                " does not fully implement ViewParent", e);
18611                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18612                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18613                        return true;
18614                    }
18615
18616                    int parentResolvedTextAlignment;
18617                    try {
18618                        parentResolvedTextAlignment = mParent.getTextAlignment();
18619                    } catch (AbstractMethodError e) {
18620                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18621                                " does not fully implement ViewParent", e);
18622                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18623                    }
18624                    switch (parentResolvedTextAlignment) {
18625                        case TEXT_ALIGNMENT_GRAVITY:
18626                        case TEXT_ALIGNMENT_TEXT_START:
18627                        case TEXT_ALIGNMENT_TEXT_END:
18628                        case TEXT_ALIGNMENT_CENTER:
18629                        case TEXT_ALIGNMENT_VIEW_START:
18630                        case TEXT_ALIGNMENT_VIEW_END:
18631                            // Resolved text alignment is the same as the parent resolved
18632                            // text alignment
18633                            mPrivateFlags2 |=
18634                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18635                            break;
18636                        default:
18637                            // Use default resolved text alignment
18638                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18639                    }
18640                    break;
18641                case TEXT_ALIGNMENT_GRAVITY:
18642                case TEXT_ALIGNMENT_TEXT_START:
18643                case TEXT_ALIGNMENT_TEXT_END:
18644                case TEXT_ALIGNMENT_CENTER:
18645                case TEXT_ALIGNMENT_VIEW_START:
18646                case TEXT_ALIGNMENT_VIEW_END:
18647                    // Resolved text alignment is the same as text alignment
18648                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18649                    break;
18650                default:
18651                    // Use default resolved text alignment
18652                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18653            }
18654        } else {
18655            // Use default resolved text alignment
18656            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18657        }
18658
18659        // Set the resolved
18660        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18661        return true;
18662    }
18663
18664    /**
18665     * Check if text alignment resolution can be done.
18666     *
18667     * @return true if text alignment resolution can be done otherwise return false.
18668     */
18669    public boolean canResolveTextAlignment() {
18670        switch (getRawTextAlignment()) {
18671            case TEXT_DIRECTION_INHERIT:
18672                if (mParent != null) {
18673                    try {
18674                        return mParent.canResolveTextAlignment();
18675                    } catch (AbstractMethodError e) {
18676                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18677                                " does not fully implement ViewParent", e);
18678                    }
18679                }
18680                return false;
18681
18682            default:
18683                return true;
18684        }
18685    }
18686
18687    /**
18688     * Reset resolved text alignment. Text alignment will be resolved during a call to
18689     * {@link #onMeasure(int, int)}.
18690     *
18691     * @hide
18692     */
18693    public void resetResolvedTextAlignment() {
18694        // Reset any previous text alignment resolution
18695        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18696        // Set to default
18697        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18698    }
18699
18700    /**
18701     * @return true if text alignment is inherited.
18702     *
18703     * @hide
18704     */
18705    public boolean isTextAlignmentInherited() {
18706        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18707    }
18708
18709    /**
18710     * @return true if text alignment is resolved.
18711     */
18712    public boolean isTextAlignmentResolved() {
18713        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18714    }
18715
18716    /**
18717     * Generate a value suitable for use in {@link #setId(int)}.
18718     * This value will not collide with ID values generated at build time by aapt for R.id.
18719     *
18720     * @return a generated ID value
18721     */
18722    public static int generateViewId() {
18723        for (;;) {
18724            final int result = sNextGeneratedId.get();
18725            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18726            int newValue = result + 1;
18727            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18728            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18729                return result;
18730            }
18731        }
18732    }
18733
18734    /**
18735     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18736     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18737     *                           a normal View or a ViewGroup with
18738     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18739     * @hide
18740     */
18741    public void captureTransitioningViews(List<View> transitioningViews) {
18742        if (getVisibility() == View.VISIBLE) {
18743            transitioningViews.add(this);
18744        }
18745    }
18746
18747    /**
18748     * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements.
18749     * @param sharedElements Will contain all Views in the hierarchy having a shared element name.
18750     * @hide
18751     */
18752    public void findSharedElements(Map<String, View> sharedElements) {
18753        if (getVisibility() == VISIBLE) {
18754            String sharedElementName = getSharedElementName();
18755            if (sharedElementName != null) {
18756                sharedElements.put(sharedElementName, this);
18757            }
18758        }
18759    }
18760
18761    //
18762    // Properties
18763    //
18764    /**
18765     * A Property wrapper around the <code>alpha</code> functionality handled by the
18766     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18767     */
18768    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18769        @Override
18770        public void setValue(View object, float value) {
18771            object.setAlpha(value);
18772        }
18773
18774        @Override
18775        public Float get(View object) {
18776            return object.getAlpha();
18777        }
18778    };
18779
18780    /**
18781     * A Property wrapper around the <code>translationX</code> functionality handled by the
18782     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18783     */
18784    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18785        @Override
18786        public void setValue(View object, float value) {
18787            object.setTranslationX(value);
18788        }
18789
18790                @Override
18791        public Float get(View object) {
18792            return object.getTranslationX();
18793        }
18794    };
18795
18796    /**
18797     * A Property wrapper around the <code>translationY</code> functionality handled by the
18798     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18799     */
18800    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18801        @Override
18802        public void setValue(View object, float value) {
18803            object.setTranslationY(value);
18804        }
18805
18806        @Override
18807        public Float get(View object) {
18808            return object.getTranslationY();
18809        }
18810    };
18811
18812    /**
18813     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18814     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18815     */
18816    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18817        @Override
18818        public void setValue(View object, float value) {
18819            object.setTranslationZ(value);
18820        }
18821
18822        @Override
18823        public Float get(View object) {
18824            return object.getTranslationZ();
18825        }
18826    };
18827
18828    /**
18829     * A Property wrapper around the <code>x</code> functionality handled by the
18830     * {@link View#setX(float)} and {@link View#getX()} methods.
18831     */
18832    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18833        @Override
18834        public void setValue(View object, float value) {
18835            object.setX(value);
18836        }
18837
18838        @Override
18839        public Float get(View object) {
18840            return object.getX();
18841        }
18842    };
18843
18844    /**
18845     * A Property wrapper around the <code>y</code> functionality handled by the
18846     * {@link View#setY(float)} and {@link View#getY()} methods.
18847     */
18848    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18849        @Override
18850        public void setValue(View object, float value) {
18851            object.setY(value);
18852        }
18853
18854        @Override
18855        public Float get(View object) {
18856            return object.getY();
18857        }
18858    };
18859
18860    /**
18861     * A Property wrapper around the <code>rotation</code> functionality handled by the
18862     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18863     */
18864    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18865        @Override
18866        public void setValue(View object, float value) {
18867            object.setRotation(value);
18868        }
18869
18870        @Override
18871        public Float get(View object) {
18872            return object.getRotation();
18873        }
18874    };
18875
18876    /**
18877     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18878     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18879     */
18880    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18881        @Override
18882        public void setValue(View object, float value) {
18883            object.setRotationX(value);
18884        }
18885
18886        @Override
18887        public Float get(View object) {
18888            return object.getRotationX();
18889        }
18890    };
18891
18892    /**
18893     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18894     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18895     */
18896    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18897        @Override
18898        public void setValue(View object, float value) {
18899            object.setRotationY(value);
18900        }
18901
18902        @Override
18903        public Float get(View object) {
18904            return object.getRotationY();
18905        }
18906    };
18907
18908    /**
18909     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18910     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18911     */
18912    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18913        @Override
18914        public void setValue(View object, float value) {
18915            object.setScaleX(value);
18916        }
18917
18918        @Override
18919        public Float get(View object) {
18920            return object.getScaleX();
18921        }
18922    };
18923
18924    /**
18925     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18926     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18927     */
18928    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18929        @Override
18930        public void setValue(View object, float value) {
18931            object.setScaleY(value);
18932        }
18933
18934        @Override
18935        public Float get(View object) {
18936            return object.getScaleY();
18937        }
18938    };
18939
18940    /**
18941     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18942     * Each MeasureSpec represents a requirement for either the width or the height.
18943     * A MeasureSpec is comprised of a size and a mode. There are three possible
18944     * modes:
18945     * <dl>
18946     * <dt>UNSPECIFIED</dt>
18947     * <dd>
18948     * The parent has not imposed any constraint on the child. It can be whatever size
18949     * it wants.
18950     * </dd>
18951     *
18952     * <dt>EXACTLY</dt>
18953     * <dd>
18954     * The parent has determined an exact size for the child. The child is going to be
18955     * given those bounds regardless of how big it wants to be.
18956     * </dd>
18957     *
18958     * <dt>AT_MOST</dt>
18959     * <dd>
18960     * The child can be as large as it wants up to the specified size.
18961     * </dd>
18962     * </dl>
18963     *
18964     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18965     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18966     */
18967    public static class MeasureSpec {
18968        private static final int MODE_SHIFT = 30;
18969        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18970
18971        /**
18972         * Measure specification mode: The parent has not imposed any constraint
18973         * on the child. It can be whatever size it wants.
18974         */
18975        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18976
18977        /**
18978         * Measure specification mode: The parent has determined an exact size
18979         * for the child. The child is going to be given those bounds regardless
18980         * of how big it wants to be.
18981         */
18982        public static final int EXACTLY     = 1 << MODE_SHIFT;
18983
18984        /**
18985         * Measure specification mode: The child can be as large as it wants up
18986         * to the specified size.
18987         */
18988        public static final int AT_MOST     = 2 << MODE_SHIFT;
18989
18990        /**
18991         * Creates a measure specification based on the supplied size and mode.
18992         *
18993         * The mode must always be one of the following:
18994         * <ul>
18995         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18996         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18997         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18998         * </ul>
18999         *
19000         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19001         * implementation was such that the order of arguments did not matter
19002         * and overflow in either value could impact the resulting MeasureSpec.
19003         * {@link android.widget.RelativeLayout} was affected by this bug.
19004         * Apps targeting API levels greater than 17 will get the fixed, more strict
19005         * behavior.</p>
19006         *
19007         * @param size the size of the measure specification
19008         * @param mode the mode of the measure specification
19009         * @return the measure specification based on size and mode
19010         */
19011        public static int makeMeasureSpec(int size, int mode) {
19012            if (sUseBrokenMakeMeasureSpec) {
19013                return size + mode;
19014            } else {
19015                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19016            }
19017        }
19018
19019        /**
19020         * Extracts the mode from the supplied measure specification.
19021         *
19022         * @param measureSpec the measure specification to extract the mode from
19023         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19024         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19025         *         {@link android.view.View.MeasureSpec#EXACTLY}
19026         */
19027        public static int getMode(int measureSpec) {
19028            return (measureSpec & MODE_MASK);
19029        }
19030
19031        /**
19032         * Extracts the size from the supplied measure specification.
19033         *
19034         * @param measureSpec the measure specification to extract the size from
19035         * @return the size in pixels defined in the supplied measure specification
19036         */
19037        public static int getSize(int measureSpec) {
19038            return (measureSpec & ~MODE_MASK);
19039        }
19040
19041        static int adjust(int measureSpec, int delta) {
19042            final int mode = getMode(measureSpec);
19043            if (mode == UNSPECIFIED) {
19044                // No need to adjust size for UNSPECIFIED mode.
19045                return makeMeasureSpec(0, UNSPECIFIED);
19046            }
19047            int size = getSize(measureSpec) + delta;
19048            if (size < 0) {
19049                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19050                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19051                size = 0;
19052            }
19053            return makeMeasureSpec(size, mode);
19054        }
19055
19056        /**
19057         * Returns a String representation of the specified measure
19058         * specification.
19059         *
19060         * @param measureSpec the measure specification to convert to a String
19061         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19062         */
19063        public static String toString(int measureSpec) {
19064            int mode = getMode(measureSpec);
19065            int size = getSize(measureSpec);
19066
19067            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19068
19069            if (mode == UNSPECIFIED)
19070                sb.append("UNSPECIFIED ");
19071            else if (mode == EXACTLY)
19072                sb.append("EXACTLY ");
19073            else if (mode == AT_MOST)
19074                sb.append("AT_MOST ");
19075            else
19076                sb.append(mode).append(" ");
19077
19078            sb.append(size);
19079            return sb.toString();
19080        }
19081    }
19082
19083    class CheckForLongPress implements Runnable {
19084
19085        private int mOriginalWindowAttachCount;
19086
19087        public void run() {
19088            if (isPressed() && (mParent != null)
19089                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19090                if (performLongClick()) {
19091                    mHasPerformedLongPress = true;
19092                }
19093            }
19094        }
19095
19096        public void rememberWindowAttachCount() {
19097            mOriginalWindowAttachCount = mWindowAttachCount;
19098        }
19099    }
19100
19101    private final class CheckForTap implements Runnable {
19102        public void run() {
19103            mPrivateFlags &= ~PFLAG_PREPRESSED;
19104            setPressed(true);
19105            checkForLongClick(ViewConfiguration.getTapTimeout());
19106        }
19107    }
19108
19109    private final class PerformClick implements Runnable {
19110        public void run() {
19111            performClick();
19112        }
19113    }
19114
19115    /** @hide */
19116    public void hackTurnOffWindowResizeAnim(boolean off) {
19117        mAttachInfo.mTurnOffWindowResizeAnim = off;
19118    }
19119
19120    /**
19121     * This method returns a ViewPropertyAnimator object, which can be used to animate
19122     * specific properties on this View.
19123     *
19124     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19125     */
19126    public ViewPropertyAnimator animate() {
19127        if (mAnimator == null) {
19128            mAnimator = new ViewPropertyAnimator(this);
19129        }
19130        return mAnimator;
19131    }
19132
19133    /**
19134     * Specifies that the shared name of the View to be shared with another Activity.
19135     * When transitioning between Activities, the name links a UI element in the starting
19136     * Activity to UI element in the called Activity. Names should be unique in the
19137     * View hierarchy.
19138     *
19139     * @param sharedElementName The cross-Activity View identifier. The called Activity will use
19140     *                 the name to match the location with a View in its layout.
19141     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle)
19142     */
19143    public void setSharedElementName(String sharedElementName) {
19144        setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName);
19145    }
19146
19147    /**
19148     * Returns the shared name of the View to be shared with another Activity.
19149     * When transitioning between Activities, the name links a UI element in the starting
19150     * Activity to UI element in the called Activity. Names should be unique in the
19151     * View hierarchy.
19152     *
19153     * <p>This returns null if the View is not a shared element or the name if it is.</p>
19154     *
19155     * @return The name used for this View for cross-Activity transitions or null if
19156     * this View has not been identified as shared.
19157     */
19158    public String getSharedElementName() {
19159        return (String) getTag(com.android.internal.R.id.shared_element_name);
19160    }
19161
19162    /**
19163     * Interface definition for a callback to be invoked when a hardware key event is
19164     * dispatched to this view. The callback will be invoked before the key event is
19165     * given to the view. This is only useful for hardware keyboards; a software input
19166     * method has no obligation to trigger this listener.
19167     */
19168    public interface OnKeyListener {
19169        /**
19170         * Called when a hardware key is dispatched to a view. This allows listeners to
19171         * get a chance to respond before the target view.
19172         * <p>Key presses in software keyboards will generally NOT trigger this method,
19173         * although some may elect to do so in some situations. Do not assume a
19174         * software input method has to be key-based; even if it is, it may use key presses
19175         * in a different way than you expect, so there is no way to reliably catch soft
19176         * input key presses.
19177         *
19178         * @param v The view the key has been dispatched to.
19179         * @param keyCode The code for the physical key that was pressed
19180         * @param event The KeyEvent object containing full information about
19181         *        the event.
19182         * @return True if the listener has consumed the event, false otherwise.
19183         */
19184        boolean onKey(View v, int keyCode, KeyEvent event);
19185    }
19186
19187    /**
19188     * Interface definition for a callback to be invoked when a touch event is
19189     * dispatched to this view. The callback will be invoked before the touch
19190     * event is given to the view.
19191     */
19192    public interface OnTouchListener {
19193        /**
19194         * Called when a touch event is dispatched to a view. This allows listeners to
19195         * get a chance to respond before the target view.
19196         *
19197         * @param v The view the touch event has been dispatched to.
19198         * @param event The MotionEvent object containing full information about
19199         *        the event.
19200         * @return True if the listener has consumed the event, false otherwise.
19201         */
19202        boolean onTouch(View v, MotionEvent event);
19203    }
19204
19205    /**
19206     * Interface definition for a callback to be invoked when a hover event is
19207     * dispatched to this view. The callback will be invoked before the hover
19208     * event is given to the view.
19209     */
19210    public interface OnHoverListener {
19211        /**
19212         * Called when a hover event is dispatched to a view. This allows listeners to
19213         * get a chance to respond before the target view.
19214         *
19215         * @param v The view the hover event has been dispatched to.
19216         * @param event The MotionEvent object containing full information about
19217         *        the event.
19218         * @return True if the listener has consumed the event, false otherwise.
19219         */
19220        boolean onHover(View v, MotionEvent event);
19221    }
19222
19223    /**
19224     * Interface definition for a callback to be invoked when a generic motion event is
19225     * dispatched to this view. The callback will be invoked before the generic motion
19226     * event is given to the view.
19227     */
19228    public interface OnGenericMotionListener {
19229        /**
19230         * Called when a generic motion event is dispatched to a view. This allows listeners to
19231         * get a chance to respond before the target view.
19232         *
19233         * @param v The view the generic motion event has been dispatched to.
19234         * @param event The MotionEvent object containing full information about
19235         *        the event.
19236         * @return True if the listener has consumed the event, false otherwise.
19237         */
19238        boolean onGenericMotion(View v, MotionEvent event);
19239    }
19240
19241    /**
19242     * Interface definition for a callback to be invoked when a view has been clicked and held.
19243     */
19244    public interface OnLongClickListener {
19245        /**
19246         * Called when a view has been clicked and held.
19247         *
19248         * @param v The view that was clicked and held.
19249         *
19250         * @return true if the callback consumed the long click, false otherwise.
19251         */
19252        boolean onLongClick(View v);
19253    }
19254
19255    /**
19256     * Interface definition for a callback to be invoked when a drag is being dispatched
19257     * to this view.  The callback will be invoked before the hosting view's own
19258     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19259     * onDrag(event) behavior, it should return 'false' from this callback.
19260     *
19261     * <div class="special reference">
19262     * <h3>Developer Guides</h3>
19263     * <p>For a guide to implementing drag and drop features, read the
19264     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19265     * </div>
19266     */
19267    public interface OnDragListener {
19268        /**
19269         * Called when a drag event is dispatched to a view. This allows listeners
19270         * to get a chance to override base View behavior.
19271         *
19272         * @param v The View that received the drag event.
19273         * @param event The {@link android.view.DragEvent} object for the drag event.
19274         * @return {@code true} if the drag event was handled successfully, or {@code false}
19275         * if the drag event was not handled. Note that {@code false} will trigger the View
19276         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19277         */
19278        boolean onDrag(View v, DragEvent event);
19279    }
19280
19281    /**
19282     * Interface definition for a callback to be invoked when the focus state of
19283     * a view changed.
19284     */
19285    public interface OnFocusChangeListener {
19286        /**
19287         * Called when the focus state of a view has changed.
19288         *
19289         * @param v The view whose state has changed.
19290         * @param hasFocus The new focus state of v.
19291         */
19292        void onFocusChange(View v, boolean hasFocus);
19293    }
19294
19295    /**
19296     * Interface definition for a callback to be invoked when a view is clicked.
19297     */
19298    public interface OnClickListener {
19299        /**
19300         * Called when a view has been clicked.
19301         *
19302         * @param v The view that was clicked.
19303         */
19304        void onClick(View v);
19305    }
19306
19307    /**
19308     * Interface definition for a callback to be invoked when the context menu
19309     * for this view is being built.
19310     */
19311    public interface OnCreateContextMenuListener {
19312        /**
19313         * Called when the context menu for this view is being built. It is not
19314         * safe to hold onto the menu after this method returns.
19315         *
19316         * @param menu The context menu that is being built
19317         * @param v The view for which the context menu is being built
19318         * @param menuInfo Extra information about the item for which the
19319         *            context menu should be shown. This information will vary
19320         *            depending on the class of v.
19321         */
19322        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19323    }
19324
19325    /**
19326     * Interface definition for a callback to be invoked when the status bar changes
19327     * visibility.  This reports <strong>global</strong> changes to the system UI
19328     * state, not what the application is requesting.
19329     *
19330     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19331     */
19332    public interface OnSystemUiVisibilityChangeListener {
19333        /**
19334         * Called when the status bar changes visibility because of a call to
19335         * {@link View#setSystemUiVisibility(int)}.
19336         *
19337         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19338         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19339         * This tells you the <strong>global</strong> state of these UI visibility
19340         * flags, not what your app is currently applying.
19341         */
19342        public void onSystemUiVisibilityChange(int visibility);
19343    }
19344
19345    /**
19346     * Interface definition for a callback to be invoked when this view is attached
19347     * or detached from its window.
19348     */
19349    public interface OnAttachStateChangeListener {
19350        /**
19351         * Called when the view is attached to a window.
19352         * @param v The view that was attached
19353         */
19354        public void onViewAttachedToWindow(View v);
19355        /**
19356         * Called when the view is detached from a window.
19357         * @param v The view that was detached
19358         */
19359        public void onViewDetachedFromWindow(View v);
19360    }
19361
19362    /**
19363     * Listener for applying window insets on a view in a custom way.
19364     *
19365     * <p>Apps may choose to implement this interface if they want to apply custom policy
19366     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19367     * is set, its
19368     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19369     * method will be called instead of the View's own
19370     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19371     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19372     * the View's normal behavior as part of its own.</p>
19373     */
19374    public interface OnApplyWindowInsetsListener {
19375        /**
19376         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19377         * on a View, this listener method will be called instead of the view's own
19378         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19379         *
19380         * @param v The view applying window insets
19381         * @param insets The insets to apply
19382         * @return The insets supplied, minus any insets that were consumed
19383         */
19384        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19385    }
19386
19387    private final class UnsetPressedState implements Runnable {
19388        public void run() {
19389            setPressed(false);
19390        }
19391    }
19392
19393    /**
19394     * Base class for derived classes that want to save and restore their own
19395     * state in {@link android.view.View#onSaveInstanceState()}.
19396     */
19397    public static class BaseSavedState extends AbsSavedState {
19398        /**
19399         * Constructor used when reading from a parcel. Reads the state of the superclass.
19400         *
19401         * @param source
19402         */
19403        public BaseSavedState(Parcel source) {
19404            super(source);
19405        }
19406
19407        /**
19408         * Constructor called by derived classes when creating their SavedState objects
19409         *
19410         * @param superState The state of the superclass of this view
19411         */
19412        public BaseSavedState(Parcelable superState) {
19413            super(superState);
19414        }
19415
19416        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19417                new Parcelable.Creator<BaseSavedState>() {
19418            public BaseSavedState createFromParcel(Parcel in) {
19419                return new BaseSavedState(in);
19420            }
19421
19422            public BaseSavedState[] newArray(int size) {
19423                return new BaseSavedState[size];
19424            }
19425        };
19426    }
19427
19428    /**
19429     * A set of information given to a view when it is attached to its parent
19430     * window.
19431     */
19432    static class AttachInfo {
19433        interface Callbacks {
19434            void playSoundEffect(int effectId);
19435            boolean performHapticFeedback(int effectId, boolean always);
19436        }
19437
19438        /**
19439         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19440         * to a Handler. This class contains the target (View) to invalidate and
19441         * the coordinates of the dirty rectangle.
19442         *
19443         * For performance purposes, this class also implements a pool of up to
19444         * POOL_LIMIT objects that get reused. This reduces memory allocations
19445         * whenever possible.
19446         */
19447        static class InvalidateInfo {
19448            private static final int POOL_LIMIT = 10;
19449
19450            private static final SynchronizedPool<InvalidateInfo> sPool =
19451                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19452
19453            View target;
19454
19455            int left;
19456            int top;
19457            int right;
19458            int bottom;
19459
19460            public static InvalidateInfo obtain() {
19461                InvalidateInfo instance = sPool.acquire();
19462                return (instance != null) ? instance : new InvalidateInfo();
19463            }
19464
19465            public void recycle() {
19466                target = null;
19467                sPool.release(this);
19468            }
19469        }
19470
19471        final IWindowSession mSession;
19472
19473        final IWindow mWindow;
19474
19475        final IBinder mWindowToken;
19476
19477        final Display mDisplay;
19478
19479        final Callbacks mRootCallbacks;
19480
19481        IWindowId mIWindowId;
19482        WindowId mWindowId;
19483
19484        /**
19485         * The top view of the hierarchy.
19486         */
19487        View mRootView;
19488
19489        IBinder mPanelParentWindowToken;
19490
19491        boolean mHardwareAccelerated;
19492        boolean mHardwareAccelerationRequested;
19493        HardwareRenderer mHardwareRenderer;
19494
19495        boolean mScreenOn;
19496
19497        /**
19498         * Scale factor used by the compatibility mode
19499         */
19500        float mApplicationScale;
19501
19502        /**
19503         * Indicates whether the application is in compatibility mode
19504         */
19505        boolean mScalingRequired;
19506
19507        /**
19508         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19509         */
19510        boolean mTurnOffWindowResizeAnim;
19511
19512        /**
19513         * Left position of this view's window
19514         */
19515        int mWindowLeft;
19516
19517        /**
19518         * Top position of this view's window
19519         */
19520        int mWindowTop;
19521
19522        /**
19523         * Indicates whether views need to use 32-bit drawing caches
19524         */
19525        boolean mUse32BitDrawingCache;
19526
19527        /**
19528         * For windows that are full-screen but using insets to layout inside
19529         * of the screen areas, these are the current insets to appear inside
19530         * the overscan area of the display.
19531         */
19532        final Rect mOverscanInsets = new Rect();
19533
19534        /**
19535         * For windows that are full-screen but using insets to layout inside
19536         * of the screen decorations, these are the current insets for the
19537         * content of the window.
19538         */
19539        final Rect mContentInsets = new Rect();
19540
19541        /**
19542         * For windows that are full-screen but using insets to layout inside
19543         * of the screen decorations, these are the current insets for the
19544         * actual visible parts of the window.
19545         */
19546        final Rect mVisibleInsets = new Rect();
19547
19548        /**
19549         * The internal insets given by this window.  This value is
19550         * supplied by the client (through
19551         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19552         * be given to the window manager when changed to be used in laying
19553         * out windows behind it.
19554         */
19555        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19556                = new ViewTreeObserver.InternalInsetsInfo();
19557
19558        /**
19559         * Set to true when mGivenInternalInsets is non-empty.
19560         */
19561        boolean mHasNonEmptyGivenInternalInsets;
19562
19563        /**
19564         * All views in the window's hierarchy that serve as scroll containers,
19565         * used to determine if the window can be resized or must be panned
19566         * to adjust for a soft input area.
19567         */
19568        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19569
19570        final KeyEvent.DispatcherState mKeyDispatchState
19571                = new KeyEvent.DispatcherState();
19572
19573        /**
19574         * Indicates whether the view's window currently has the focus.
19575         */
19576        boolean mHasWindowFocus;
19577
19578        /**
19579         * The current visibility of the window.
19580         */
19581        int mWindowVisibility;
19582
19583        /**
19584         * Indicates the time at which drawing started to occur.
19585         */
19586        long mDrawingTime;
19587
19588        /**
19589         * Indicates whether or not ignoring the DIRTY_MASK flags.
19590         */
19591        boolean mIgnoreDirtyState;
19592
19593        /**
19594         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19595         * to avoid clearing that flag prematurely.
19596         */
19597        boolean mSetIgnoreDirtyState = false;
19598
19599        /**
19600         * Indicates whether the view's window is currently in touch mode.
19601         */
19602        boolean mInTouchMode;
19603
19604        /**
19605         * Indicates that ViewAncestor should trigger a global layout change
19606         * the next time it performs a traversal
19607         */
19608        boolean mRecomputeGlobalAttributes;
19609
19610        /**
19611         * Always report new attributes at next traversal.
19612         */
19613        boolean mForceReportNewAttributes;
19614
19615        /**
19616         * Set during a traveral if any views want to keep the screen on.
19617         */
19618        boolean mKeepScreenOn;
19619
19620        /**
19621         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19622         */
19623        int mSystemUiVisibility;
19624
19625        /**
19626         * Hack to force certain system UI visibility flags to be cleared.
19627         */
19628        int mDisabledSystemUiVisibility;
19629
19630        /**
19631         * Last global system UI visibility reported by the window manager.
19632         */
19633        int mGlobalSystemUiVisibility;
19634
19635        /**
19636         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19637         * attached.
19638         */
19639        boolean mHasSystemUiListeners;
19640
19641        /**
19642         * Set if the window has requested to extend into the overscan region
19643         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19644         */
19645        boolean mOverscanRequested;
19646
19647        /**
19648         * Set if the visibility of any views has changed.
19649         */
19650        boolean mViewVisibilityChanged;
19651
19652        /**
19653         * Set to true if a view has been scrolled.
19654         */
19655        boolean mViewScrollChanged;
19656
19657        /**
19658         * Global to the view hierarchy used as a temporary for dealing with
19659         * x/y points in the transparent region computations.
19660         */
19661        final int[] mTransparentLocation = new int[2];
19662
19663        /**
19664         * Global to the view hierarchy used as a temporary for dealing with
19665         * x/y points in the ViewGroup.invalidateChild implementation.
19666         */
19667        final int[] mInvalidateChildLocation = new int[2];
19668
19669
19670        /**
19671         * Global to the view hierarchy used as a temporary for dealing with
19672         * x/y location when view is transformed.
19673         */
19674        final float[] mTmpTransformLocation = new float[2];
19675
19676        /**
19677         * The view tree observer used to dispatch global events like
19678         * layout, pre-draw, touch mode change, etc.
19679         */
19680        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19681
19682        /**
19683         * A Canvas used by the view hierarchy to perform bitmap caching.
19684         */
19685        Canvas mCanvas;
19686
19687        /**
19688         * The view root impl.
19689         */
19690        final ViewRootImpl mViewRootImpl;
19691
19692        /**
19693         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19694         * handler can be used to pump events in the UI events queue.
19695         */
19696        final Handler mHandler;
19697
19698        /**
19699         * Temporary for use in computing invalidate rectangles while
19700         * calling up the hierarchy.
19701         */
19702        final Rect mTmpInvalRect = new Rect();
19703
19704        /**
19705         * Temporary for use in computing hit areas with transformed views
19706         */
19707        final RectF mTmpTransformRect = new RectF();
19708
19709        /**
19710         * Temporary for use in transforming invalidation rect
19711         */
19712        final Matrix mTmpMatrix = new Matrix();
19713
19714        /**
19715         * Temporary for use in transforming invalidation rect
19716         */
19717        final Transformation mTmpTransformation = new Transformation();
19718
19719        /**
19720         * Temporary list for use in collecting focusable descendents of a view.
19721         */
19722        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19723
19724        /**
19725         * The id of the window for accessibility purposes.
19726         */
19727        int mAccessibilityWindowId = View.NO_ID;
19728
19729        /**
19730         * Flags related to accessibility processing.
19731         *
19732         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19733         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19734         */
19735        int mAccessibilityFetchFlags;
19736
19737        /**
19738         * The drawable for highlighting accessibility focus.
19739         */
19740        Drawable mAccessibilityFocusDrawable;
19741
19742        /**
19743         * Show where the margins, bounds and layout bounds are for each view.
19744         */
19745        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19746
19747        /**
19748         * Point used to compute visible regions.
19749         */
19750        final Point mPoint = new Point();
19751
19752        /**
19753         * Used to track which View originated a requestLayout() call, used when
19754         * requestLayout() is called during layout.
19755         */
19756        View mViewRequestingLayout;
19757
19758        /**
19759         * Creates a new set of attachment information with the specified
19760         * events handler and thread.
19761         *
19762         * @param handler the events handler the view must use
19763         */
19764        AttachInfo(IWindowSession session, IWindow window, Display display,
19765                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19766            mSession = session;
19767            mWindow = window;
19768            mWindowToken = window.asBinder();
19769            mDisplay = display;
19770            mViewRootImpl = viewRootImpl;
19771            mHandler = handler;
19772            mRootCallbacks = effectPlayer;
19773        }
19774    }
19775
19776    /**
19777     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19778     * is supported. This avoids keeping too many unused fields in most
19779     * instances of View.</p>
19780     */
19781    private static class ScrollabilityCache implements Runnable {
19782
19783        /**
19784         * Scrollbars are not visible
19785         */
19786        public static final int OFF = 0;
19787
19788        /**
19789         * Scrollbars are visible
19790         */
19791        public static final int ON = 1;
19792
19793        /**
19794         * Scrollbars are fading away
19795         */
19796        public static final int FADING = 2;
19797
19798        public boolean fadeScrollBars;
19799
19800        public int fadingEdgeLength;
19801        public int scrollBarDefaultDelayBeforeFade;
19802        public int scrollBarFadeDuration;
19803
19804        public int scrollBarSize;
19805        public ScrollBarDrawable scrollBar;
19806        public float[] interpolatorValues;
19807        public View host;
19808
19809        public final Paint paint;
19810        public final Matrix matrix;
19811        public Shader shader;
19812
19813        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19814
19815        private static final float[] OPAQUE = { 255 };
19816        private static final float[] TRANSPARENT = { 0.0f };
19817
19818        /**
19819         * When fading should start. This time moves into the future every time
19820         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19821         */
19822        public long fadeStartTime;
19823
19824
19825        /**
19826         * The current state of the scrollbars: ON, OFF, or FADING
19827         */
19828        public int state = OFF;
19829
19830        private int mLastColor;
19831
19832        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19833            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19834            scrollBarSize = configuration.getScaledScrollBarSize();
19835            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19836            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19837
19838            paint = new Paint();
19839            matrix = new Matrix();
19840            // use use a height of 1, and then wack the matrix each time we
19841            // actually use it.
19842            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19843            paint.setShader(shader);
19844            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19845
19846            this.host = host;
19847        }
19848
19849        public void setFadeColor(int color) {
19850            if (color != mLastColor) {
19851                mLastColor = color;
19852
19853                if (color != 0) {
19854                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19855                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19856                    paint.setShader(shader);
19857                    // Restore the default transfer mode (src_over)
19858                    paint.setXfermode(null);
19859                } else {
19860                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19861                    paint.setShader(shader);
19862                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19863                }
19864            }
19865        }
19866
19867        public void run() {
19868            long now = AnimationUtils.currentAnimationTimeMillis();
19869            if (now >= fadeStartTime) {
19870
19871                // the animation fades the scrollbars out by changing
19872                // the opacity (alpha) from fully opaque to fully
19873                // transparent
19874                int nextFrame = (int) now;
19875                int framesCount = 0;
19876
19877                Interpolator interpolator = scrollBarInterpolator;
19878
19879                // Start opaque
19880                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19881
19882                // End transparent
19883                nextFrame += scrollBarFadeDuration;
19884                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19885
19886                state = FADING;
19887
19888                // Kick off the fade animation
19889                host.invalidate(true);
19890            }
19891        }
19892    }
19893
19894    /**
19895     * Resuable callback for sending
19896     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19897     */
19898    private class SendViewScrolledAccessibilityEvent implements Runnable {
19899        public volatile boolean mIsPending;
19900
19901        public void run() {
19902            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19903            mIsPending = false;
19904        }
19905    }
19906
19907    /**
19908     * <p>
19909     * This class represents a delegate that can be registered in a {@link View}
19910     * to enhance accessibility support via composition rather via inheritance.
19911     * It is specifically targeted to widget developers that extend basic View
19912     * classes i.e. classes in package android.view, that would like their
19913     * applications to be backwards compatible.
19914     * </p>
19915     * <div class="special reference">
19916     * <h3>Developer Guides</h3>
19917     * <p>For more information about making applications accessible, read the
19918     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19919     * developer guide.</p>
19920     * </div>
19921     * <p>
19922     * A scenario in which a developer would like to use an accessibility delegate
19923     * is overriding a method introduced in a later API version then the minimal API
19924     * version supported by the application. For example, the method
19925     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19926     * in API version 4 when the accessibility APIs were first introduced. If a
19927     * developer would like his application to run on API version 4 devices (assuming
19928     * all other APIs used by the application are version 4 or lower) and take advantage
19929     * of this method, instead of overriding the method which would break the application's
19930     * backwards compatibility, he can override the corresponding method in this
19931     * delegate and register the delegate in the target View if the API version of
19932     * the system is high enough i.e. the API version is same or higher to the API
19933     * version that introduced
19934     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19935     * </p>
19936     * <p>
19937     * Here is an example implementation:
19938     * </p>
19939     * <code><pre><p>
19940     * if (Build.VERSION.SDK_INT >= 14) {
19941     *     // If the API version is equal of higher than the version in
19942     *     // which onInitializeAccessibilityNodeInfo was introduced we
19943     *     // register a delegate with a customized implementation.
19944     *     View view = findViewById(R.id.view_id);
19945     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19946     *         public void onInitializeAccessibilityNodeInfo(View host,
19947     *                 AccessibilityNodeInfo info) {
19948     *             // Let the default implementation populate the info.
19949     *             super.onInitializeAccessibilityNodeInfo(host, info);
19950     *             // Set some other information.
19951     *             info.setEnabled(host.isEnabled());
19952     *         }
19953     *     });
19954     * }
19955     * </code></pre></p>
19956     * <p>
19957     * This delegate contains methods that correspond to the accessibility methods
19958     * in View. If a delegate has been specified the implementation in View hands
19959     * off handling to the corresponding method in this delegate. The default
19960     * implementation the delegate methods behaves exactly as the corresponding
19961     * method in View for the case of no accessibility delegate been set. Hence,
19962     * to customize the behavior of a View method, clients can override only the
19963     * corresponding delegate method without altering the behavior of the rest
19964     * accessibility related methods of the host view.
19965     * </p>
19966     */
19967    public static class AccessibilityDelegate {
19968
19969        /**
19970         * Sends an accessibility event of the given type. If accessibility is not
19971         * enabled this method has no effect.
19972         * <p>
19973         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19974         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19975         * been set.
19976         * </p>
19977         *
19978         * @param host The View hosting the delegate.
19979         * @param eventType The type of the event to send.
19980         *
19981         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19982         */
19983        public void sendAccessibilityEvent(View host, int eventType) {
19984            host.sendAccessibilityEventInternal(eventType);
19985        }
19986
19987        /**
19988         * Performs the specified accessibility action on the view. For
19989         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19990         * <p>
19991         * The default implementation behaves as
19992         * {@link View#performAccessibilityAction(int, Bundle)
19993         *  View#performAccessibilityAction(int, Bundle)} for the case of
19994         *  no accessibility delegate been set.
19995         * </p>
19996         *
19997         * @param action The action to perform.
19998         * @return Whether the action was performed.
19999         *
20000         * @see View#performAccessibilityAction(int, Bundle)
20001         *      View#performAccessibilityAction(int, Bundle)
20002         */
20003        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20004            return host.performAccessibilityActionInternal(action, args);
20005        }
20006
20007        /**
20008         * Sends an accessibility event. This method behaves exactly as
20009         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20010         * empty {@link AccessibilityEvent} and does not perform a check whether
20011         * accessibility is enabled.
20012         * <p>
20013         * The default implementation behaves as
20014         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20015         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20016         * the case of no accessibility delegate been set.
20017         * </p>
20018         *
20019         * @param host The View hosting the delegate.
20020         * @param event The event to send.
20021         *
20022         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20023         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20024         */
20025        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20026            host.sendAccessibilityEventUncheckedInternal(event);
20027        }
20028
20029        /**
20030         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20031         * to its children for adding their text content to the event.
20032         * <p>
20033         * The default implementation behaves as
20034         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20035         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20036         * the case of no accessibility delegate been set.
20037         * </p>
20038         *
20039         * @param host The View hosting the delegate.
20040         * @param event The event.
20041         * @return True if the event population was completed.
20042         *
20043         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20044         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20045         */
20046        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20047            return host.dispatchPopulateAccessibilityEventInternal(event);
20048        }
20049
20050        /**
20051         * Gives a chance to the host View to populate the accessibility event with its
20052         * text content.
20053         * <p>
20054         * The default implementation behaves as
20055         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20056         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20057         * the case of no accessibility delegate been set.
20058         * </p>
20059         *
20060         * @param host The View hosting the delegate.
20061         * @param event The accessibility event which to populate.
20062         *
20063         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20064         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20065         */
20066        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20067            host.onPopulateAccessibilityEventInternal(event);
20068        }
20069
20070        /**
20071         * Initializes an {@link AccessibilityEvent} with information about the
20072         * the host View which is the event source.
20073         * <p>
20074         * The default implementation behaves as
20075         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20076         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20077         * the case of no accessibility delegate been set.
20078         * </p>
20079         *
20080         * @param host The View hosting the delegate.
20081         * @param event The event to initialize.
20082         *
20083         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20084         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20085         */
20086        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20087            host.onInitializeAccessibilityEventInternal(event);
20088        }
20089
20090        /**
20091         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20092         * <p>
20093         * The default implementation behaves as
20094         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20095         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20096         * the case of no accessibility delegate been set.
20097         * </p>
20098         *
20099         * @param host The View hosting the delegate.
20100         * @param info The instance to initialize.
20101         *
20102         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20103         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20104         */
20105        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20106            host.onInitializeAccessibilityNodeInfoInternal(info);
20107        }
20108
20109        /**
20110         * Called when a child of the host View has requested sending an
20111         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20112         * to augment the event.
20113         * <p>
20114         * The default implementation behaves as
20115         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20116         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20117         * the case of no accessibility delegate been set.
20118         * </p>
20119         *
20120         * @param host The View hosting the delegate.
20121         * @param child The child which requests sending the event.
20122         * @param event The event to be sent.
20123         * @return True if the event should be sent
20124         *
20125         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20126         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20127         */
20128        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20129                AccessibilityEvent event) {
20130            return host.onRequestSendAccessibilityEventInternal(child, event);
20131        }
20132
20133        /**
20134         * Gets the provider for managing a virtual view hierarchy rooted at this View
20135         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20136         * that explore the window content.
20137         * <p>
20138         * The default implementation behaves as
20139         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20140         * the case of no accessibility delegate been set.
20141         * </p>
20142         *
20143         * @return The provider.
20144         *
20145         * @see AccessibilityNodeProvider
20146         */
20147        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20148            return null;
20149        }
20150
20151        /**
20152         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20153         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20154         * This method is responsible for obtaining an accessibility node info from a
20155         * pool of reusable instances and calling
20156         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20157         * view to initialize the former.
20158         * <p>
20159         * <strong>Note:</strong> The client is responsible for recycling the obtained
20160         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20161         * creation.
20162         * </p>
20163         * <p>
20164         * The default implementation behaves as
20165         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20166         * the case of no accessibility delegate been set.
20167         * </p>
20168         * @return A populated {@link AccessibilityNodeInfo}.
20169         *
20170         * @see AccessibilityNodeInfo
20171         *
20172         * @hide
20173         */
20174        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20175            return host.createAccessibilityNodeInfoInternal();
20176        }
20177    }
20178
20179    private class MatchIdPredicate implements Predicate<View> {
20180        public int mId;
20181
20182        @Override
20183        public boolean apply(View view) {
20184            return (view.mID == mId);
20185        }
20186    }
20187
20188    private class MatchLabelForPredicate implements Predicate<View> {
20189        private int mLabeledId;
20190
20191        @Override
20192        public boolean apply(View view) {
20193            return (view.mLabelForId == mLabeledId);
20194        }
20195    }
20196
20197    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20198        private int mChangeTypes = 0;
20199        private boolean mPosted;
20200        private boolean mPostedWithDelay;
20201        private long mLastEventTimeMillis;
20202
20203        @Override
20204        public void run() {
20205            mPosted = false;
20206            mPostedWithDelay = false;
20207            mLastEventTimeMillis = SystemClock.uptimeMillis();
20208            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20209                final AccessibilityEvent event = AccessibilityEvent.obtain();
20210                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20211                event.setContentChangeTypes(mChangeTypes);
20212                sendAccessibilityEventUnchecked(event);
20213            }
20214            mChangeTypes = 0;
20215        }
20216
20217        public void runOrPost(int changeType) {
20218            mChangeTypes |= changeType;
20219
20220            // If this is a live region or the child of a live region, collect
20221            // all events from this frame and send them on the next frame.
20222            if (inLiveRegion()) {
20223                // If we're already posted with a delay, remove that.
20224                if (mPostedWithDelay) {
20225                    removeCallbacks(this);
20226                    mPostedWithDelay = false;
20227                }
20228                // Only post if we're not already posted.
20229                if (!mPosted) {
20230                    post(this);
20231                    mPosted = true;
20232                }
20233                return;
20234            }
20235
20236            if (mPosted) {
20237                return;
20238            }
20239            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20240            final long minEventIntevalMillis =
20241                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20242            if (timeSinceLastMillis >= minEventIntevalMillis) {
20243                removeCallbacks(this);
20244                run();
20245            } else {
20246                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20247                mPosted = true;
20248                mPostedWithDelay = true;
20249            }
20250        }
20251    }
20252
20253    private boolean inLiveRegion() {
20254        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20255            return true;
20256        }
20257
20258        ViewParent parent = getParent();
20259        while (parent instanceof View) {
20260            if (((View) parent).getAccessibilityLiveRegion()
20261                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20262                return true;
20263            }
20264            parent = parent.getParent();
20265        }
20266
20267        return false;
20268    }
20269
20270    /**
20271     * Dump all private flags in readable format, useful for documentation and
20272     * sanity checking.
20273     */
20274    private static void dumpFlags() {
20275        final HashMap<String, String> found = Maps.newHashMap();
20276        try {
20277            for (Field field : View.class.getDeclaredFields()) {
20278                final int modifiers = field.getModifiers();
20279                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20280                    if (field.getType().equals(int.class)) {
20281                        final int value = field.getInt(null);
20282                        dumpFlag(found, field.getName(), value);
20283                    } else if (field.getType().equals(int[].class)) {
20284                        final int[] values = (int[]) field.get(null);
20285                        for (int i = 0; i < values.length; i++) {
20286                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20287                        }
20288                    }
20289                }
20290            }
20291        } catch (IllegalAccessException e) {
20292            throw new RuntimeException(e);
20293        }
20294
20295        final ArrayList<String> keys = Lists.newArrayList();
20296        keys.addAll(found.keySet());
20297        Collections.sort(keys);
20298        for (String key : keys) {
20299            Log.d(VIEW_LOG_TAG, found.get(key));
20300        }
20301    }
20302
20303    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20304        // Sort flags by prefix, then by bits, always keeping unique keys
20305        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20306        final int prefix = name.indexOf('_');
20307        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20308        final String output = bits + " " + name;
20309        found.put(key, output);
20310    }
20311}
20312