View.java revision 1e96bdf344d7395bd377ae07eacaa75ba17c1204
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.animation.AnimatorInflater;
20import android.animation.RevealAnimator;
21import android.animation.StateListAnimator;
22import android.animation.ValueAnimator;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.content.ClipData;
27import android.content.Context;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.content.res.TypedArray;
31import android.graphics.Bitmap;
32import android.graphics.Canvas;
33import android.graphics.Insets;
34import android.graphics.Interpolator;
35import android.graphics.LinearGradient;
36import android.graphics.Matrix;
37import android.graphics.Outline;
38import android.graphics.Paint;
39import android.graphics.PixelFormat;
40import android.graphics.Point;
41import android.graphics.PorterDuff;
42import android.graphics.PorterDuffXfermode;
43import android.graphics.Rect;
44import android.graphics.RectF;
45import android.graphics.Region;
46import android.graphics.Shader;
47import android.graphics.drawable.ColorDrawable;
48import android.graphics.drawable.Drawable;
49import android.hardware.display.DisplayManagerGlobal;
50import android.os.Bundle;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.Parcel;
54import android.os.Parcelable;
55import android.os.RemoteException;
56import android.os.SystemClock;
57import android.os.SystemProperties;
58import android.text.TextUtils;
59import android.util.AttributeSet;
60import android.util.FloatProperty;
61import android.util.LayoutDirection;
62import android.util.Log;
63import android.util.LongSparseLongArray;
64import android.util.Pools.SynchronizedPool;
65import android.util.Property;
66import android.util.SparseArray;
67import android.util.SuperNotCalledException;
68import android.util.TypedValue;
69import android.view.ContextMenu.ContextMenuInfo;
70import android.view.AccessibilityIterators.TextSegmentIterator;
71import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
72import android.view.AccessibilityIterators.WordTextSegmentIterator;
73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
74import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityEventSource;
76import android.view.accessibility.AccessibilityManager;
77import android.view.accessibility.AccessibilityNodeInfo;
78import android.view.accessibility.AccessibilityNodeProvider;
79import android.view.animation.Animation;
80import android.view.animation.AnimationUtils;
81import android.view.animation.Transformation;
82import android.view.inputmethod.EditorInfo;
83import android.view.inputmethod.InputConnection;
84import android.view.inputmethod.InputMethodManager;
85import android.widget.ScrollBarDrawable;
86
87import static android.os.Build.VERSION_CODES.*;
88import static java.lang.Math.max;
89
90import com.android.internal.R;
91import com.android.internal.util.Predicate;
92import com.android.internal.view.menu.MenuBuilder;
93import com.google.android.collect.Lists;
94import com.google.android.collect.Maps;
95
96import java.lang.annotation.Retention;
97import java.lang.annotation.RetentionPolicy;
98import java.lang.ref.WeakReference;
99import java.lang.reflect.Field;
100import java.lang.reflect.InvocationTargetException;
101import java.lang.reflect.Method;
102import java.lang.reflect.Modifier;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.HashMap;
107import java.util.List;
108import java.util.Locale;
109import java.util.Map;
110import java.util.concurrent.CopyOnWriteArrayList;
111import java.util.concurrent.atomic.AtomicInteger;
112
113/**
114 * <p>
115 * This class represents the basic building block for user interface components. A View
116 * occupies a rectangular area on the screen and is responsible for drawing and
117 * event handling. View is the base class for <em>widgets</em>, which are
118 * used to create interactive UI components (buttons, text fields, etc.). The
119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
120 * are invisible containers that hold other Views (or other ViewGroups) and define
121 * their layout properties.
122 * </p>
123 *
124 * <div class="special reference">
125 * <h3>Developer Guides</h3>
126 * <p>For information about using this class to develop your application's user interface,
127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
128 * </div>
129 *
130 * <a name="Using"></a>
131 * <h3>Using Views</h3>
132 * <p>
133 * All of the views in a window are arranged in a single tree. You can add views
134 * either from code or by specifying a tree of views in one or more XML layout
135 * files. There are many specialized subclasses of views that act as controls or
136 * are capable of displaying text, images, or other content.
137 * </p>
138 * <p>
139 * Once you have created a tree of views, there are typically a few types of
140 * common operations you may wish to perform:
141 * <ul>
142 * <li><strong>Set properties:</strong> for example setting the text of a
143 * {@link android.widget.TextView}. The available properties and the methods
144 * that set them will vary among the different subclasses of views. Note that
145 * properties that are known at build time can be set in the XML layout
146 * files.</li>
147 * <li><strong>Set focus:</strong> The framework will handled moving focus in
148 * response to user input. To force focus to a specific view, call
149 * {@link #requestFocus}.</li>
150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
151 * that will be notified when something interesting happens to the view. For
152 * example, all views will let you set a listener to be notified when the view
153 * gains or loses focus. You can register such a listener using
154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
155 * Other view subclasses offer more specialized listeners. For example, a Button
156 * exposes a listener to notify clients when the button is clicked.</li>
157 * <li><strong>Set visibility:</strong> You can hide or show views using
158 * {@link #setVisibility(int)}.</li>
159 * </ul>
160 * </p>
161 * <p><em>
162 * Note: The Android framework is responsible for measuring, laying out and
163 * drawing views. You should not call methods that perform these actions on
164 * views yourself unless you are actually implementing a
165 * {@link android.view.ViewGroup}.
166 * </em></p>
167 *
168 * <a name="Lifecycle"></a>
169 * <h3>Implementing a Custom View</h3>
170 *
171 * <p>
172 * To implement a custom view, you will usually begin by providing overrides for
173 * some of the standard methods that the framework calls on all views. You do
174 * not need to override all of these methods. In fact, you can start by just
175 * overriding {@link #onDraw(android.graphics.Canvas)}.
176 * <table border="2" width="85%" align="center" cellpadding="5">
177 *     <thead>
178 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
179 *     </thead>
180 *
181 *     <tbody>
182 *     <tr>
183 *         <td rowspan="2">Creation</td>
184 *         <td>Constructors</td>
185 *         <td>There is a form of the constructor that are called when the view
186 *         is created from code and a form that is called when the view is
187 *         inflated from a layout file. The second form should parse and apply
188 *         any attributes defined in the layout file.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onFinishInflate()}</code></td>
193 *         <td>Called after a view and all of its children has been inflated
194 *         from XML.</td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="3">Layout</td>
199 *         <td><code>{@link #onMeasure(int, int)}</code></td>
200 *         <td>Called to determine the size requirements for this view and all
201 *         of its children.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
206 *         <td>Called when this view should assign a size and position to all
207 *         of its children.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
212 *         <td>Called when the size of this view has changed.
213 *         </td>
214 *     </tr>
215 *
216 *     <tr>
217 *         <td>Drawing</td>
218 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
219 *         <td>Called when the view should render its content.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="4">Event processing</td>
225 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
226 *         <td>Called when a new hardware key event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
231 *         <td>Called when a hardware key up event occurs.
232 *         </td>
233 *     </tr>
234 *     <tr>
235 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
236 *         <td>Called when a trackball motion event occurs.
237 *         </td>
238 *     </tr>
239 *     <tr>
240 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
241 *         <td>Called when a touch screen motion event occurs.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="2">Focus</td>
247 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
248 *         <td>Called when the view gains or loses focus.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
254 *         <td>Called when the window containing the view gains or loses focus.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="3">Attaching</td>
260 *         <td><code>{@link #onAttachedToWindow()}</code></td>
261 *         <td>Called when the view is attached to a window.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onDetachedFromWindow}</code></td>
267 *         <td>Called when the view is detached from its window.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
273 *         <td>Called when the visibility of the window containing the view
274 *         has changed.
275 *         </td>
276 *     </tr>
277 *     </tbody>
278 *
279 * </table>
280 * </p>
281 *
282 * <a name="IDs"></a>
283 * <h3>IDs</h3>
284 * Views may have an integer id associated with them. These ids are typically
285 * assigned in the layout XML files, and are used to find specific views within
286 * the view tree. A common pattern is to:
287 * <ul>
288 * <li>Define a Button in the layout file and assign it a unique ID.
289 * <pre>
290 * &lt;Button
291 *     android:id="@+id/my_button"
292 *     android:layout_width="wrap_content"
293 *     android:layout_height="wrap_content"
294 *     android:text="@string/my_button_text"/&gt;
295 * </pre></li>
296 * <li>From the onCreate method of an Activity, find the Button
297 * <pre class="prettyprint">
298 *      Button myButton = (Button) findViewById(R.id.my_button);
299 * </pre></li>
300 * </ul>
301 * <p>
302 * View IDs need not be unique throughout the tree, but it is good practice to
303 * ensure that they are at least unique within the part of the tree you are
304 * searching.
305 * </p>
306 *
307 * <a name="Position"></a>
308 * <h3>Position</h3>
309 * <p>
310 * The geometry of a view is that of a rectangle. A view has a location,
311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
312 * two dimensions, expressed as a width and a height. The unit for location
313 * and dimensions is the pixel.
314 * </p>
315 *
316 * <p>
317 * It is possible to retrieve the location of a view by invoking the methods
318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
319 * coordinate of the rectangle representing the view. The latter returns the
320 * top, or Y, coordinate of the rectangle representing the view. These methods
321 * both return the location of the view relative to its parent. For instance,
322 * when getLeft() returns 20, that means the view is located 20 pixels to the
323 * right of the left edge of its direct parent.
324 * </p>
325 *
326 * <p>
327 * In addition, several convenience methods are offered to avoid unnecessary
328 * computations, namely {@link #getRight()} and {@link #getBottom()}.
329 * These methods return the coordinates of the right and bottom edges of the
330 * rectangle representing the view. For instance, calling {@link #getRight()}
331 * is similar to the following computation: <code>getLeft() + getWidth()</code>
332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
333 * </p>
334 *
335 * <a name="SizePaddingMargins"></a>
336 * <h3>Size, padding and margins</h3>
337 * <p>
338 * The size of a view is expressed with a width and a height. A view actually
339 * possess two pairs of width and height values.
340 * </p>
341 *
342 * <p>
343 * The first pair is known as <em>measured width</em> and
344 * <em>measured height</em>. These dimensions define how big a view wants to be
345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
347 * and {@link #getMeasuredHeight()}.
348 * </p>
349 *
350 * <p>
351 * The second pair is simply known as <em>width</em> and <em>height</em>, or
352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
353 * dimensions define the actual size of the view on screen, at drawing time and
354 * after layout. These values may, but do not have to, be different from the
355 * measured width and height. The width and height can be obtained by calling
356 * {@link #getWidth()} and {@link #getHeight()}.
357 * </p>
358 *
359 * <p>
360 * To measure its dimensions, a view takes into account its padding. The padding
361 * is expressed in pixels for the left, top, right and bottom parts of the view.
362 * Padding can be used to offset the content of the view by a specific amount of
363 * pixels. For instance, a left padding of 2 will push the view's content by
364 * 2 pixels to the right of the left edge. Padding can be set using the
365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
368 * {@link #getPaddingEnd()}.
369 * </p>
370 *
371 * <p>
372 * Even though a view can define a padding, it does not provide any support for
373 * margins. However, view groups provide such a support. Refer to
374 * {@link android.view.ViewGroup} and
375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
376 * </p>
377 *
378 * <a name="Layout"></a>
379 * <h3>Layout</h3>
380 * <p>
381 * Layout is a two pass process: a measure pass and a layout pass. The measuring
382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
383 * of the view tree. Each view pushes dimension specifications down the tree
384 * during the recursion. At the end of the measure pass, every view has stored
385 * its measurements. The second pass happens in
386 * {@link #layout(int,int,int,int)} and is also top-down. During
387 * this pass each parent is responsible for positioning all of its children
388 * using the sizes computed in the measure pass.
389 * </p>
390 *
391 * <p>
392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
393 * {@link #getMeasuredHeight()} values must be set, along with those for all of
394 * that view's descendants. A view's measured width and measured height values
395 * must respect the constraints imposed by the view's parents. This guarantees
396 * that at the end of the measure pass, all parents accept all of their
397 * children's measurements. A parent view may call measure() more than once on
398 * its children. For example, the parent may measure each child once with
399 * unspecified dimensions to find out how big they want to be, then call
400 * measure() on them again with actual numbers if the sum of all the children's
401 * unconstrained sizes is too big or too small.
402 * </p>
403 *
404 * <p>
405 * The measure pass uses two classes to communicate dimensions. The
406 * {@link MeasureSpec} class is used by views to tell their parents how they
407 * want to be measured and positioned. The base LayoutParams class just
408 * describes how big the view wants to be for both width and height. For each
409 * dimension, it can specify one of:
410 * <ul>
411 * <li> an exact number
412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
413 * (minus padding)
414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
415 * enclose its content (plus padding).
416 * </ul>
417 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
419 * an X and Y value.
420 * </p>
421 *
422 * <p>
423 * MeasureSpecs are used to push requirements down the tree from parent to
424 * child. A MeasureSpec can be in one of three modes:
425 * <ul>
426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
427 * of a child view. For example, a LinearLayout may call measure() on its child
428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
429 * tall the child view wants to be given a width of 240 pixels.
430 * <li>EXACTLY: This is used by the parent to impose an exact size on the
431 * child. The child must use this size, and guarantee that all of its
432 * descendants will fit within this size.
433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
434 * child. The child must guarantee that it and all of its descendants will fit
435 * within this size.
436 * </ul>
437 * </p>
438 *
439 * <p>
440 * To intiate a layout, call {@link #requestLayout}. This method is typically
441 * called by a view on itself when it believes that is can no longer fit within
442 * its current bounds.
443 * </p>
444 *
445 * <a name="Drawing"></a>
446 * <h3>Drawing</h3>
447 * <p>
448 * Drawing is handled by walking the tree and rendering each view that
449 * intersects the invalid region. Because the tree is traversed in-order,
450 * this means that parents will draw before (i.e., behind) their children, with
451 * siblings drawn in the order they appear in the tree.
452 * If you set a background drawable for a View, then the View will draw it for you
453 * before calling back to its <code>onDraw()</code> method.
454 * </p>
455 *
456 * <p>
457 * Note that the framework will not draw views that are not in the invalid region.
458 * </p>
459 *
460 * <p>
461 * To force a view to draw, call {@link #invalidate()}.
462 * </p>
463 *
464 * <a name="EventHandlingThreading"></a>
465 * <h3>Event Handling and Threading</h3>
466 * <p>
467 * The basic cycle of a view is as follows:
468 * <ol>
469 * <li>An event comes in and is dispatched to the appropriate view. The view
470 * handles the event and notifies any listeners.</li>
471 * <li>If in the course of processing the event, the view's bounds may need
472 * to be changed, the view will call {@link #requestLayout()}.</li>
473 * <li>Similarly, if in the course of processing the event the view's appearance
474 * may need to be changed, the view will call {@link #invalidate()}.</li>
475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
476 * the framework will take care of measuring, laying out, and drawing the tree
477 * as appropriate.</li>
478 * </ol>
479 * </p>
480 *
481 * <p><em>Note: The entire view tree is single threaded. You must always be on
482 * the UI thread when calling any method on any view.</em>
483 * If you are doing work on other threads and want to update the state of a view
484 * from that thread, you should use a {@link Handler}.
485 * </p>
486 *
487 * <a name="FocusHandling"></a>
488 * <h3>Focus Handling</h3>
489 * <p>
490 * The framework will handle routine focus movement in response to user input.
491 * This includes changing the focus as views are removed or hidden, or as new
492 * views become available. Views indicate their willingness to take focus
493 * through the {@link #isFocusable} method. To change whether a view can take
494 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
496 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
497 * </p>
498 * <p>
499 * Focus movement is based on an algorithm which finds the nearest neighbor in a
500 * given direction. In rare cases, the default algorithm may not match the
501 * intended behavior of the developer. In these situations, you can provide
502 * explicit overrides by using these XML attributes in the layout file:
503 * <pre>
504 * nextFocusDown
505 * nextFocusLeft
506 * nextFocusRight
507 * nextFocusUp
508 * </pre>
509 * </p>
510 *
511 *
512 * <p>
513 * To get a particular view to take focus, call {@link #requestFocus()}.
514 * </p>
515 *
516 * <a name="TouchMode"></a>
517 * <h3>Touch Mode</h3>
518 * <p>
519 * When a user is navigating a user interface via directional keys such as a D-pad, it is
520 * necessary to give focus to actionable items such as buttons so the user can see
521 * what will take input.  If the device has touch capabilities, however, and the user
522 * begins interacting with the interface by touching it, it is no longer necessary to
523 * always highlight, or give focus to, a particular view.  This motivates a mode
524 * for interaction named 'touch mode'.
525 * </p>
526 * <p>
527 * For a touch capable device, once the user touches the screen, the device
528 * will enter touch mode.  From this point onward, only views for which
529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
530 * Other views that are touchable, like buttons, will not take focus when touched; they will
531 * only fire the on click listeners.
532 * </p>
533 * <p>
534 * Any time a user hits a directional key, such as a D-pad direction, the view device will
535 * exit touch mode, and find a view to take focus, so that the user may resume interacting
536 * with the user interface without touching the screen again.
537 * </p>
538 * <p>
539 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
540 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
541 * </p>
542 *
543 * <a name="Scrolling"></a>
544 * <h3>Scrolling</h3>
545 * <p>
546 * The framework provides basic support for views that wish to internally
547 * scroll their content. This includes keeping track of the X and Y scroll
548 * offset as well as mechanisms for drawing scrollbars. See
549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
550 * {@link #awakenScrollBars()} for more details.
551 * </p>
552 *
553 * <a name="Tags"></a>
554 * <h3>Tags</h3>
555 * <p>
556 * Unlike IDs, tags are not used to identify views. Tags are essentially an
557 * extra piece of information that can be associated with a view. They are most
558 * often used as a convenience to store data related to views in the views
559 * themselves rather than by putting them in a separate structure.
560 * </p>
561 *
562 * <a name="Properties"></a>
563 * <h3>Properties</h3>
564 * <p>
565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
567 * available both in the {@link Property} form as well as in similarly-named setter/getter
568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
569 * be used to set persistent state associated with these rendering-related properties on the view.
570 * The properties and methods can also be used in conjunction with
571 * {@link android.animation.Animator Animator}-based animations, described more in the
572 * <a href="#Animation">Animation</a> section.
573 * </p>
574 *
575 * <a name="Animation"></a>
576 * <h3>Animation</h3>
577 * <p>
578 * Starting with Android 3.0, the preferred way of animating views is to use the
579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
584 * makes animating these View properties particularly easy and efficient.
585 * </p>
586 * <p>
587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
588 * You can attach an {@link Animation} object to a view using
589 * {@link #setAnimation(Animation)} or
590 * {@link #startAnimation(Animation)}. The animation can alter the scale,
591 * rotation, translation and alpha of a view over time. If the animation is
592 * attached to a view that has children, the animation will affect the entire
593 * subtree rooted by that node. When an animation is started, the framework will
594 * take care of redrawing the appropriate views until the animation completes.
595 * </p>
596 *
597 * <a name="Security"></a>
598 * <h3>Security</h3>
599 * <p>
600 * Sometimes it is essential that an application be able to verify that an action
601 * is being performed with the full knowledge and consent of the user, such as
602 * granting a permission request, making a purchase or clicking on an advertisement.
603 * Unfortunately, a malicious application could try to spoof the user into
604 * performing these actions, unaware, by concealing the intended purpose of the view.
605 * As a remedy, the framework offers a touch filtering mechanism that can be used to
606 * improve the security of views that provide access to sensitive functionality.
607 * </p><p>
608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
609 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
610 * will discard touches that are received whenever the view's window is obscured by
611 * another visible window.  As a result, the view will not receive touches whenever a
612 * toast, dialog or other window appears above the view's window.
613 * </p><p>
614 * For more fine-grained control over security, consider overriding the
615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
617 * </p>
618 *
619 * @attr ref android.R.styleable#View_alpha
620 * @attr ref android.R.styleable#View_background
621 * @attr ref android.R.styleable#View_clickable
622 * @attr ref android.R.styleable#View_contentDescription
623 * @attr ref android.R.styleable#View_drawingCacheQuality
624 * @attr ref android.R.styleable#View_duplicateParentState
625 * @attr ref android.R.styleable#View_id
626 * @attr ref android.R.styleable#View_requiresFadingEdge
627 * @attr ref android.R.styleable#View_fadeScrollbars
628 * @attr ref android.R.styleable#View_fadingEdgeLength
629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
630 * @attr ref android.R.styleable#View_fitsSystemWindows
631 * @attr ref android.R.styleable#View_isScrollContainer
632 * @attr ref android.R.styleable#View_focusable
633 * @attr ref android.R.styleable#View_focusableInTouchMode
634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
635 * @attr ref android.R.styleable#View_keepScreenOn
636 * @attr ref android.R.styleable#View_layerType
637 * @attr ref android.R.styleable#View_layoutDirection
638 * @attr ref android.R.styleable#View_longClickable
639 * @attr ref android.R.styleable#View_minHeight
640 * @attr ref android.R.styleable#View_minWidth
641 * @attr ref android.R.styleable#View_nextFocusDown
642 * @attr ref android.R.styleable#View_nextFocusLeft
643 * @attr ref android.R.styleable#View_nextFocusRight
644 * @attr ref android.R.styleable#View_nextFocusUp
645 * @attr ref android.R.styleable#View_onClick
646 * @attr ref android.R.styleable#View_padding
647 * @attr ref android.R.styleable#View_paddingBottom
648 * @attr ref android.R.styleable#View_paddingLeft
649 * @attr ref android.R.styleable#View_paddingRight
650 * @attr ref android.R.styleable#View_paddingTop
651 * @attr ref android.R.styleable#View_paddingStart
652 * @attr ref android.R.styleable#View_paddingEnd
653 * @attr ref android.R.styleable#View_saveEnabled
654 * @attr ref android.R.styleable#View_rotation
655 * @attr ref android.R.styleable#View_rotationX
656 * @attr ref android.R.styleable#View_rotationY
657 * @attr ref android.R.styleable#View_scaleX
658 * @attr ref android.R.styleable#View_scaleY
659 * @attr ref android.R.styleable#View_scrollX
660 * @attr ref android.R.styleable#View_scrollY
661 * @attr ref android.R.styleable#View_scrollbarSize
662 * @attr ref android.R.styleable#View_scrollbarStyle
663 * @attr ref android.R.styleable#View_scrollbars
664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
665 * @attr ref android.R.styleable#View_scrollbarFadeDuration
666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
668 * @attr ref android.R.styleable#View_scrollbarThumbVertical
669 * @attr ref android.R.styleable#View_scrollbarTrackVertical
670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
672 * @attr ref android.R.styleable#View_stateListAnimator
673 * @attr ref android.R.styleable#View_viewName
674 * @attr ref android.R.styleable#View_soundEffectsEnabled
675 * @attr ref android.R.styleable#View_tag
676 * @attr ref android.R.styleable#View_textAlignment
677 * @attr ref android.R.styleable#View_textDirection
678 * @attr ref android.R.styleable#View_transformPivotX
679 * @attr ref android.R.styleable#View_transformPivotY
680 * @attr ref android.R.styleable#View_translationX
681 * @attr ref android.R.styleable#View_translationY
682 * @attr ref android.R.styleable#View_translationZ
683 * @attr ref android.R.styleable#View_visibility
684 *
685 * @see android.view.ViewGroup
686 */
687public class View implements Drawable.Callback, KeyEvent.Callback,
688        AccessibilityEventSource {
689    private static final boolean DBG = false;
690
691    /**
692     * The logging tag used by this class with android.util.Log.
693     */
694    protected static final String VIEW_LOG_TAG = "View";
695
696    /**
697     * When set to true, apps will draw debugging information about their layouts.
698     *
699     * @hide
700     */
701    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
702
703    /**
704     * Used to mark a View that has no ID.
705     */
706    public static final int NO_ID = -1;
707
708    /**
709     * Signals that compatibility booleans have been initialized according to
710     * target SDK versions.
711     */
712    private static boolean sCompatibilityDone = false;
713
714    /**
715     * Use the old (broken) way of building MeasureSpecs.
716     */
717    private static boolean sUseBrokenMakeMeasureSpec = false;
718
719    /**
720     * Ignore any optimizations using the measure cache.
721     */
722    private static boolean sIgnoreMeasureCache = false;
723
724    /**
725     * Ignore the clipBounds of this view for the children.
726     */
727    static boolean sIgnoreClipBoundsForChildren = false;
728
729    /**
730     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
731     * calling setFlags.
732     */
733    private static final int NOT_FOCUSABLE = 0x00000000;
734
735    /**
736     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
737     * setFlags.
738     */
739    private static final int FOCUSABLE = 0x00000001;
740
741    /**
742     * Mask for use with setFlags indicating bits used for focus.
743     */
744    private static final int FOCUSABLE_MASK = 0x00000001;
745
746    /**
747     * This view will adjust its padding to fit sytem windows (e.g. status bar)
748     */
749    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
750
751    /** @hide */
752    @IntDef({VISIBLE, INVISIBLE, GONE})
753    @Retention(RetentionPolicy.SOURCE)
754    public @interface Visibility {}
755
756    /**
757     * This view is visible.
758     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
759     * android:visibility}.
760     */
761    public static final int VISIBLE = 0x00000000;
762
763    /**
764     * This view is invisible, but it still takes up space for layout purposes.
765     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
766     * android:visibility}.
767     */
768    public static final int INVISIBLE = 0x00000004;
769
770    /**
771     * This view is invisible, and it doesn't take any space for layout
772     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
773     * android:visibility}.
774     */
775    public static final int GONE = 0x00000008;
776
777    /**
778     * Mask for use with setFlags indicating bits used for visibility.
779     * {@hide}
780     */
781    static final int VISIBILITY_MASK = 0x0000000C;
782
783    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
784
785    /**
786     * This view is enabled. Interpretation varies by subclass.
787     * Use with ENABLED_MASK when calling setFlags.
788     * {@hide}
789     */
790    static final int ENABLED = 0x00000000;
791
792    /**
793     * This view is disabled. Interpretation varies by subclass.
794     * Use with ENABLED_MASK when calling setFlags.
795     * {@hide}
796     */
797    static final int DISABLED = 0x00000020;
798
799   /**
800    * Mask for use with setFlags indicating bits used for indicating whether
801    * this view is enabled
802    * {@hide}
803    */
804    static final int ENABLED_MASK = 0x00000020;
805
806    /**
807     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
808     * called and further optimizations will be performed. It is okay to have
809     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
810     * {@hide}
811     */
812    static final int WILL_NOT_DRAW = 0x00000080;
813
814    /**
815     * Mask for use with setFlags indicating bits used for indicating whether
816     * this view is will draw
817     * {@hide}
818     */
819    static final int DRAW_MASK = 0x00000080;
820
821    /**
822     * <p>This view doesn't show scrollbars.</p>
823     * {@hide}
824     */
825    static final int SCROLLBARS_NONE = 0x00000000;
826
827    /**
828     * <p>This view shows horizontal scrollbars.</p>
829     * {@hide}
830     */
831    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
832
833    /**
834     * <p>This view shows vertical scrollbars.</p>
835     * {@hide}
836     */
837    static final int SCROLLBARS_VERTICAL = 0x00000200;
838
839    /**
840     * <p>Mask for use with setFlags indicating bits used for indicating which
841     * scrollbars are enabled.</p>
842     * {@hide}
843     */
844    static final int SCROLLBARS_MASK = 0x00000300;
845
846    /**
847     * Indicates that the view should filter touches when its window is obscured.
848     * Refer to the class comments for more information about this security feature.
849     * {@hide}
850     */
851    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
852
853    /**
854     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
855     * that they are optional and should be skipped if the window has
856     * requested system UI flags that ignore those insets for layout.
857     */
858    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
859
860    /**
861     * <p>This view doesn't show fading edges.</p>
862     * {@hide}
863     */
864    static final int FADING_EDGE_NONE = 0x00000000;
865
866    /**
867     * <p>This view shows horizontal fading edges.</p>
868     * {@hide}
869     */
870    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
871
872    /**
873     * <p>This view shows vertical fading edges.</p>
874     * {@hide}
875     */
876    static final int FADING_EDGE_VERTICAL = 0x00002000;
877
878    /**
879     * <p>Mask for use with setFlags indicating bits used for indicating which
880     * fading edges are enabled.</p>
881     * {@hide}
882     */
883    static final int FADING_EDGE_MASK = 0x00003000;
884
885    /**
886     * <p>Indicates this view can be clicked. When clickable, a View reacts
887     * to clicks by notifying the OnClickListener.<p>
888     * {@hide}
889     */
890    static final int CLICKABLE = 0x00004000;
891
892    /**
893     * <p>Indicates this view is caching its drawing into a bitmap.</p>
894     * {@hide}
895     */
896    static final int DRAWING_CACHE_ENABLED = 0x00008000;
897
898    /**
899     * <p>Indicates that no icicle should be saved for this view.<p>
900     * {@hide}
901     */
902    static final int SAVE_DISABLED = 0x000010000;
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
906     * property.</p>
907     * {@hide}
908     */
909    static final int SAVE_DISABLED_MASK = 0x000010000;
910
911    /**
912     * <p>Indicates that no drawing cache should ever be created for this view.<p>
913     * {@hide}
914     */
915    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
916
917    /**
918     * <p>Indicates this view can take / keep focus when int touch mode.</p>
919     * {@hide}
920     */
921    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
922
923    /** @hide */
924    @Retention(RetentionPolicy.SOURCE)
925    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
926    public @interface DrawingCacheQuality {}
927
928    /**
929     * <p>Enables low quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
932
933    /**
934     * <p>Enables high quality mode for the drawing cache.</p>
935     */
936    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
937
938    /**
939     * <p>Enables automatic quality mode for the drawing cache.</p>
940     */
941    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
942
943    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
944            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
945    };
946
947    /**
948     * <p>Mask for use with setFlags indicating bits used for the cache
949     * quality property.</p>
950     * {@hide}
951     */
952    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
953
954    /**
955     * <p>
956     * Indicates this view can be long clicked. When long clickable, a View
957     * reacts to long clicks by notifying the OnLongClickListener or showing a
958     * context menu.
959     * </p>
960     * {@hide}
961     */
962    static final int LONG_CLICKABLE = 0x00200000;
963
964    /**
965     * <p>Indicates that this view gets its drawable states from its direct parent
966     * and ignores its original internal states.</p>
967     *
968     * @hide
969     */
970    static final int DUPLICATE_PARENT_STATE = 0x00400000;
971
972    /** @hide */
973    @IntDef({
974        SCROLLBARS_INSIDE_OVERLAY,
975        SCROLLBARS_INSIDE_INSET,
976        SCROLLBARS_OUTSIDE_OVERLAY,
977        SCROLLBARS_OUTSIDE_INSET
978    })
979    @Retention(RetentionPolicy.SOURCE)
980    public @interface ScrollBarStyle {}
981
982    /**
983     * The scrollbar style to display the scrollbars inside the content area,
984     * without increasing the padding. The scrollbars will be overlaid with
985     * translucency on the view's content.
986     */
987    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
988
989    /**
990     * The scrollbar style to display the scrollbars inside the padded area,
991     * increasing the padding of the view. The scrollbars will not overlap the
992     * content area of the view.
993     */
994    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
995
996    /**
997     * The scrollbar style to display the scrollbars at the edge of the view,
998     * without increasing the padding. The scrollbars will be overlaid with
999     * translucency.
1000     */
1001    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1002
1003    /**
1004     * The scrollbar style to display the scrollbars at the edge of the view,
1005     * increasing the padding of the view. The scrollbars will only overlap the
1006     * background, if any.
1007     */
1008    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1009
1010    /**
1011     * Mask to check if the scrollbar style is overlay or inset.
1012     * {@hide}
1013     */
1014    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1015
1016    /**
1017     * Mask to check if the scrollbar style is inside or outside.
1018     * {@hide}
1019     */
1020    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1021
1022    /**
1023     * Mask for scrollbar style.
1024     * {@hide}
1025     */
1026    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1027
1028    /**
1029     * View flag indicating that the screen should remain on while the
1030     * window containing this view is visible to the user.  This effectively
1031     * takes care of automatically setting the WindowManager's
1032     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1033     */
1034    public static final int KEEP_SCREEN_ON = 0x04000000;
1035
1036    /**
1037     * View flag indicating whether this view should have sound effects enabled
1038     * for events such as clicking and touching.
1039     */
1040    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1041
1042    /**
1043     * View flag indicating whether this view should have haptic feedback
1044     * enabled for events such as long presses.
1045     */
1046    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1047
1048    /**
1049     * <p>Indicates that the view hierarchy should stop saving state when
1050     * it reaches this view.  If state saving is initiated immediately at
1051     * the view, it will be allowed.
1052     * {@hide}
1053     */
1054    static final int PARENT_SAVE_DISABLED = 0x20000000;
1055
1056    /**
1057     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1058     * {@hide}
1059     */
1060    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1061
1062    /** @hide */
1063    @IntDef(flag = true,
1064            value = {
1065                FOCUSABLES_ALL,
1066                FOCUSABLES_TOUCH_MODE
1067            })
1068    @Retention(RetentionPolicy.SOURCE)
1069    public @interface FocusableMode {}
1070
1071    /**
1072     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1073     * should add all focusable Views regardless if they are focusable in touch mode.
1074     */
1075    public static final int FOCUSABLES_ALL = 0x00000000;
1076
1077    /**
1078     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1079     * should add only Views focusable in touch mode.
1080     */
1081    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1082
1083    /** @hide */
1084    @IntDef({
1085            FOCUS_BACKWARD,
1086            FOCUS_FORWARD,
1087            FOCUS_LEFT,
1088            FOCUS_UP,
1089            FOCUS_RIGHT,
1090            FOCUS_DOWN
1091    })
1092    @Retention(RetentionPolicy.SOURCE)
1093    public @interface FocusDirection {}
1094
1095    /** @hide */
1096    @IntDef({
1097            FOCUS_LEFT,
1098            FOCUS_UP,
1099            FOCUS_RIGHT,
1100            FOCUS_DOWN
1101    })
1102    @Retention(RetentionPolicy.SOURCE)
1103    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1104
1105    /**
1106     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1107     * item.
1108     */
1109    public static final int FOCUS_BACKWARD = 0x00000001;
1110
1111    /**
1112     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1113     * item.
1114     */
1115    public static final int FOCUS_FORWARD = 0x00000002;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus to the left.
1119     */
1120    public static final int FOCUS_LEFT = 0x00000011;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus up.
1124     */
1125    public static final int FOCUS_UP = 0x00000021;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus to the right.
1129     */
1130    public static final int FOCUS_RIGHT = 0x00000042;
1131
1132    /**
1133     * Use with {@link #focusSearch(int)}. Move focus down.
1134     */
1135    public static final int FOCUS_DOWN = 0x00000082;
1136
1137    /**
1138     * Bits of {@link #getMeasuredWidthAndState()} and
1139     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1140     */
1141    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1142
1143    /**
1144     * Bits of {@link #getMeasuredWidthAndState()} and
1145     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1146     */
1147    public static final int MEASURED_STATE_MASK = 0xff000000;
1148
1149    /**
1150     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1151     * for functions that combine both width and height into a single int,
1152     * such as {@link #getMeasuredState()} and the childState argument of
1153     * {@link #resolveSizeAndState(int, int, int)}.
1154     */
1155    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1156
1157    /**
1158     * Bit of {@link #getMeasuredWidthAndState()} and
1159     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1160     * is smaller that the space the view would like to have.
1161     */
1162    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1163
1164    /**
1165     * Base View state sets
1166     */
1167    // Singles
1168    /**
1169     * Indicates the view has no states set. States are used with
1170     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1171     * view depending on its state.
1172     *
1173     * @see android.graphics.drawable.Drawable
1174     * @see #getDrawableState()
1175     */
1176    protected static final int[] EMPTY_STATE_SET;
1177    /**
1178     * Indicates the view is enabled. States are used with
1179     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1180     * view depending on its state.
1181     *
1182     * @see android.graphics.drawable.Drawable
1183     * @see #getDrawableState()
1184     */
1185    protected static final int[] ENABLED_STATE_SET;
1186    /**
1187     * Indicates the view is focused. States are used with
1188     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1189     * view depending on its state.
1190     *
1191     * @see android.graphics.drawable.Drawable
1192     * @see #getDrawableState()
1193     */
1194    protected static final int[] FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is selected. States are used with
1197     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1198     * view depending on its state.
1199     *
1200     * @see android.graphics.drawable.Drawable
1201     * @see #getDrawableState()
1202     */
1203    protected static final int[] SELECTED_STATE_SET;
1204    /**
1205     * Indicates the view is pressed. States are used with
1206     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1207     * view depending on its state.
1208     *
1209     * @see android.graphics.drawable.Drawable
1210     * @see #getDrawableState()
1211     */
1212    protected static final int[] PRESSED_STATE_SET;
1213    /**
1214     * Indicates the view's window has focus. States are used with
1215     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1216     * view depending on its state.
1217     *
1218     * @see android.graphics.drawable.Drawable
1219     * @see #getDrawableState()
1220     */
1221    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1222    // Doubles
1223    /**
1224     * Indicates the view is enabled and has the focus.
1225     *
1226     * @see #ENABLED_STATE_SET
1227     * @see #FOCUSED_STATE_SET
1228     */
1229    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is enabled and selected.
1232     *
1233     * @see #ENABLED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is enabled and that its window has focus.
1239     *
1240     * @see #ENABLED_STATE_SET
1241     * @see #WINDOW_FOCUSED_STATE_SET
1242     */
1243    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1244    /**
1245     * Indicates the view is focused and selected.
1246     *
1247     * @see #FOCUSED_STATE_SET
1248     * @see #SELECTED_STATE_SET
1249     */
1250    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1251    /**
1252     * Indicates the view has the focus and that its window has the focus.
1253     *
1254     * @see #FOCUSED_STATE_SET
1255     * @see #WINDOW_FOCUSED_STATE_SET
1256     */
1257    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1258    /**
1259     * Indicates the view is selected and that its window has the focus.
1260     *
1261     * @see #SELECTED_STATE_SET
1262     * @see #WINDOW_FOCUSED_STATE_SET
1263     */
1264    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1265    // Triples
1266    /**
1267     * Indicates the view is enabled, focused and selected.
1268     *
1269     * @see #ENABLED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #SELECTED_STATE_SET
1272     */
1273    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1274    /**
1275     * Indicates the view is enabled, focused and its window has the focus.
1276     *
1277     * @see #ENABLED_STATE_SET
1278     * @see #FOCUSED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1282    /**
1283     * Indicates the view is enabled, selected and its window has the focus.
1284     *
1285     * @see #ENABLED_STATE_SET
1286     * @see #SELECTED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is focused, selected and its window has the focus.
1292     *
1293     * @see #FOCUSED_STATE_SET
1294     * @see #SELECTED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is enabled, focused, selected and its window
1300     * has the focus.
1301     *
1302     * @see #ENABLED_STATE_SET
1303     * @see #FOCUSED_STATE_SET
1304     * @see #SELECTED_STATE_SET
1305     * @see #WINDOW_FOCUSED_STATE_SET
1306     */
1307    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed and its window has the focus.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #WINDOW_FOCUSED_STATE_SET
1313     */
1314    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1315    /**
1316     * Indicates the view is pressed and selected.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #SELECTED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_SELECTED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, selected and its window has the focus.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     * @see #WINDOW_FOCUSED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed and focused.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, focused and its window has the focus.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     * @see #WINDOW_FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, focused and selected.
1347     *
1348     * @see #PRESSED_STATE_SET
1349     * @see #SELECTED_STATE_SET
1350     * @see #FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, focused, selected and its window has the focus.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #FOCUSED_STATE_SET
1358     * @see #SELECTED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is pressed and enabled.
1364     *
1365     * @see #PRESSED_STATE_SET
1366     * @see #ENABLED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled and its window has the focus.
1371     *
1372     * @see #PRESSED_STATE_SET
1373     * @see #ENABLED_STATE_SET
1374     * @see #WINDOW_FOCUSED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1377    /**
1378     * Indicates the view is pressed, enabled and selected.
1379     *
1380     * @see #PRESSED_STATE_SET
1381     * @see #ENABLED_STATE_SET
1382     * @see #SELECTED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled, selected and its window has the
1387     * focus.
1388     *
1389     * @see #PRESSED_STATE_SET
1390     * @see #ENABLED_STATE_SET
1391     * @see #SELECTED_STATE_SET
1392     * @see #WINDOW_FOCUSED_STATE_SET
1393     */
1394    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1395    /**
1396     * Indicates the view is pressed, enabled and focused.
1397     *
1398     * @see #PRESSED_STATE_SET
1399     * @see #ENABLED_STATE_SET
1400     * @see #FOCUSED_STATE_SET
1401     */
1402    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is pressed, enabled, focused and its window has the
1405     * focus.
1406     *
1407     * @see #PRESSED_STATE_SET
1408     * @see #ENABLED_STATE_SET
1409     * @see #FOCUSED_STATE_SET
1410     * @see #WINDOW_FOCUSED_STATE_SET
1411     */
1412    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1413    /**
1414     * Indicates the view is pressed, enabled, focused and selected.
1415     *
1416     * @see #PRESSED_STATE_SET
1417     * @see #ENABLED_STATE_SET
1418     * @see #SELECTED_STATE_SET
1419     * @see #FOCUSED_STATE_SET
1420     */
1421    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1422    /**
1423     * Indicates the view is pressed, enabled, focused, selected and its window
1424     * has the focus.
1425     *
1426     * @see #PRESSED_STATE_SET
1427     * @see #ENABLED_STATE_SET
1428     * @see #SELECTED_STATE_SET
1429     * @see #FOCUSED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1433
1434    /**
1435     * The order here is very important to {@link #getDrawableState()}
1436     */
1437    private static final int[][] VIEW_STATE_SETS;
1438
1439    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1440    static final int VIEW_STATE_SELECTED = 1 << 1;
1441    static final int VIEW_STATE_FOCUSED = 1 << 2;
1442    static final int VIEW_STATE_ENABLED = 1 << 3;
1443    static final int VIEW_STATE_PRESSED = 1 << 4;
1444    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1445    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1446    static final int VIEW_STATE_HOVERED = 1 << 7;
1447    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1448    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1449
1450    static final int[] VIEW_STATE_IDS = new int[] {
1451        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1452        R.attr.state_selected,          VIEW_STATE_SELECTED,
1453        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1454        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1455        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1456        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1457        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1458        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1459        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1460        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1461    };
1462
1463    static {
1464        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1465            throw new IllegalStateException(
1466                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1467        }
1468        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1469        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1470            int viewState = R.styleable.ViewDrawableStates[i];
1471            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1472                if (VIEW_STATE_IDS[j] == viewState) {
1473                    orderedIds[i * 2] = viewState;
1474                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1475                }
1476            }
1477        }
1478        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1479        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1480        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1481            int numBits = Integer.bitCount(i);
1482            int[] set = new int[numBits];
1483            int pos = 0;
1484            for (int j = 0; j < orderedIds.length; j += 2) {
1485                if ((i & orderedIds[j+1]) != 0) {
1486                    set[pos++] = orderedIds[j];
1487                }
1488            }
1489            VIEW_STATE_SETS[i] = set;
1490        }
1491
1492        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1493        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1494        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1495        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1497        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1498        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1499                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1500        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1502        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1504                | VIEW_STATE_FOCUSED];
1505        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1506        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1508        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1510        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1515        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1517                | VIEW_STATE_ENABLED];
1518        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1519                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1520                | VIEW_STATE_ENABLED];
1521        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1523                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1524
1525        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1526        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1527                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1528        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1530        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1535        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1537                | VIEW_STATE_PRESSED];
1538        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1539                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1540                | VIEW_STATE_PRESSED];
1541        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1543                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1546        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1547                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1548                | VIEW_STATE_PRESSED];
1549        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1550                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1551                | VIEW_STATE_PRESSED];
1552        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1553                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1554                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1555        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1556                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1557                | VIEW_STATE_PRESSED];
1558        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1559                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1560                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1561        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1562                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1563                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1564        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1565                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1566                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1567                | VIEW_STATE_PRESSED];
1568    }
1569
1570    /**
1571     * Accessibility event types that are dispatched for text population.
1572     */
1573    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1574            AccessibilityEvent.TYPE_VIEW_CLICKED
1575            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1576            | AccessibilityEvent.TYPE_VIEW_SELECTED
1577            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1578            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1579            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1580            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1581            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1582            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1583            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1584            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1585
1586    /**
1587     * Temporary Rect currently for use in setBackground().  This will probably
1588     * be extended in the future to hold our own class with more than just
1589     * a Rect. :)
1590     */
1591    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1592
1593    /**
1594     * Map used to store views' tags.
1595     */
1596    private SparseArray<Object> mKeyedTags;
1597
1598    /**
1599     * The next available accessibility id.
1600     */
1601    private static int sNextAccessibilityViewId;
1602
1603    /**
1604     * The animation currently associated with this view.
1605     * @hide
1606     */
1607    protected Animation mCurrentAnimation = null;
1608
1609    /**
1610     * Width as measured during measure pass.
1611     * {@hide}
1612     */
1613    @ViewDebug.ExportedProperty(category = "measurement")
1614    int mMeasuredWidth;
1615
1616    /**
1617     * Height as measured during measure pass.
1618     * {@hide}
1619     */
1620    @ViewDebug.ExportedProperty(category = "measurement")
1621    int mMeasuredHeight;
1622
1623    /**
1624     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1625     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1626     * its display list. This flag, used only when hw accelerated, allows us to clear the
1627     * flag while retaining this information until it's needed (at getDisplayList() time and
1628     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1629     *
1630     * {@hide}
1631     */
1632    boolean mRecreateDisplayList = false;
1633
1634    /**
1635     * The view's identifier.
1636     * {@hide}
1637     *
1638     * @see #setId(int)
1639     * @see #getId()
1640     */
1641    @ViewDebug.ExportedProperty(resolveId = true)
1642    int mID = NO_ID;
1643
1644    /**
1645     * The stable ID of this view for accessibility purposes.
1646     */
1647    int mAccessibilityViewId = NO_ID;
1648
1649    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1650
1651    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1652
1653    /**
1654     * The view's tag.
1655     * {@hide}
1656     *
1657     * @see #setTag(Object)
1658     * @see #getTag()
1659     */
1660    protected Object mTag = null;
1661
1662    // for mPrivateFlags:
1663    /** {@hide} */
1664    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1665    /** {@hide} */
1666    static final int PFLAG_FOCUSED                     = 0x00000002;
1667    /** {@hide} */
1668    static final int PFLAG_SELECTED                    = 0x00000004;
1669    /** {@hide} */
1670    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1671    /** {@hide} */
1672    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1673    /** {@hide} */
1674    static final int PFLAG_DRAWN                       = 0x00000020;
1675    /**
1676     * When this flag is set, this view is running an animation on behalf of its
1677     * children and should therefore not cancel invalidate requests, even if they
1678     * lie outside of this view's bounds.
1679     *
1680     * {@hide}
1681     */
1682    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1683    /** {@hide} */
1684    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1685    /** {@hide} */
1686    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1687    /** {@hide} */
1688    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1689    /** {@hide} */
1690    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1691    /** {@hide} */
1692    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1693    /** {@hide} */
1694    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1695    /** {@hide} */
1696    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1697
1698    private static final int PFLAG_PRESSED             = 0x00004000;
1699
1700    /** {@hide} */
1701    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1702    /**
1703     * Flag used to indicate that this view should be drawn once more (and only once
1704     * more) after its animation has completed.
1705     * {@hide}
1706     */
1707    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1708
1709    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1710
1711    /**
1712     * Indicates that the View returned true when onSetAlpha() was called and that
1713     * the alpha must be restored.
1714     * {@hide}
1715     */
1716    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1717
1718    /**
1719     * Set by {@link #setScrollContainer(boolean)}.
1720     */
1721    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1722
1723    /**
1724     * Set by {@link #setScrollContainer(boolean)}.
1725     */
1726    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1727
1728    /**
1729     * View flag indicating whether this view was invalidated (fully or partially.)
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_DIRTY                       = 0x00200000;
1734
1735    /**
1736     * View flag indicating whether this view was invalidated by an opaque
1737     * invalidate request.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1742
1743    /**
1744     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1745     *
1746     * @hide
1747     */
1748    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1749
1750    /**
1751     * Indicates whether the background is opaque.
1752     *
1753     * @hide
1754     */
1755    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1756
1757    /**
1758     * Indicates whether the scrollbars are opaque.
1759     *
1760     * @hide
1761     */
1762    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1763
1764    /**
1765     * Indicates whether the view is opaque.
1766     *
1767     * @hide
1768     */
1769    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1770
1771    /**
1772     * Indicates a prepressed state;
1773     * the short time between ACTION_DOWN and recognizing
1774     * a 'real' press. Prepressed is used to recognize quick taps
1775     * even when they are shorter than ViewConfiguration.getTapTimeout().
1776     *
1777     * @hide
1778     */
1779    private static final int PFLAG_PREPRESSED          = 0x02000000;
1780
1781    /**
1782     * Indicates whether the view is temporarily detached.
1783     *
1784     * @hide
1785     */
1786    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1787
1788    /**
1789     * Indicates that we should awaken scroll bars once attached
1790     *
1791     * @hide
1792     */
1793    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1794
1795    /**
1796     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1797     * @hide
1798     */
1799    private static final int PFLAG_HOVERED             = 0x10000000;
1800
1801    /**
1802     * no longer needed, should be reused
1803     */
1804    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1805
1806    /** {@hide} */
1807    static final int PFLAG_ACTIVATED                   = 0x40000000;
1808
1809    /**
1810     * Indicates that this view was specifically invalidated, not just dirtied because some
1811     * child view was invalidated. The flag is used to determine when we need to recreate
1812     * a view's display list (as opposed to just returning a reference to its existing
1813     * display list).
1814     *
1815     * @hide
1816     */
1817    static final int PFLAG_INVALIDATED                 = 0x80000000;
1818
1819    /**
1820     * Masks for mPrivateFlags2, as generated by dumpFlags():
1821     *
1822     * |-------|-------|-------|-------|
1823     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1824     *                                1  PFLAG2_DRAG_HOVERED
1825     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1826     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1827     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1828     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1829     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1830     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1831     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1832     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1833     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1834     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1835     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1836     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1837     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1838     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1839     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1840     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1841     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1842     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1843     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1844     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1845     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1846     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1847     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1848     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1849     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1850     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1851     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1852     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1853     *    1                              PFLAG2_PADDING_RESOLVED
1854     *   1                               PFLAG2_DRAWABLE_RESOLVED
1855     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1856     * |-------|-------|-------|-------|
1857     */
1858
1859    /**
1860     * Indicates that this view has reported that it can accept the current drag's content.
1861     * Cleared when the drag operation concludes.
1862     * @hide
1863     */
1864    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1865
1866    /**
1867     * Indicates that this view is currently directly under the drag location in a
1868     * drag-and-drop operation involving content that it can accept.  Cleared when
1869     * the drag exits the view, or when the drag operation concludes.
1870     * @hide
1871     */
1872    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1873
1874    /** @hide */
1875    @IntDef({
1876        LAYOUT_DIRECTION_LTR,
1877        LAYOUT_DIRECTION_RTL,
1878        LAYOUT_DIRECTION_INHERIT,
1879        LAYOUT_DIRECTION_LOCALE
1880    })
1881    @Retention(RetentionPolicy.SOURCE)
1882    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1883    public @interface LayoutDir {}
1884
1885    /** @hide */
1886    @IntDef({
1887        LAYOUT_DIRECTION_LTR,
1888        LAYOUT_DIRECTION_RTL
1889    })
1890    @Retention(RetentionPolicy.SOURCE)
1891    public @interface ResolvedLayoutDir {}
1892
1893    /**
1894     * Horizontal layout direction of this view is from Left to Right.
1895     * Use with {@link #setLayoutDirection}.
1896     */
1897    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1898
1899    /**
1900     * Horizontal layout direction of this view is from Right to Left.
1901     * Use with {@link #setLayoutDirection}.
1902     */
1903    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1904
1905    /**
1906     * Horizontal layout direction of this view is inherited from its parent.
1907     * Use with {@link #setLayoutDirection}.
1908     */
1909    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1910
1911    /**
1912     * Horizontal layout direction of this view is from deduced from the default language
1913     * script for the locale. Use with {@link #setLayoutDirection}.
1914     */
1915    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1916
1917    /**
1918     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1919     * @hide
1920     */
1921    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1922
1923    /**
1924     * Mask for use with private flags indicating bits used for horizontal layout direction.
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1928
1929    /**
1930     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1931     * right-to-left direction.
1932     * @hide
1933     */
1934    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1935
1936    /**
1937     * Indicates whether the view horizontal layout direction has been resolved.
1938     * @hide
1939     */
1940    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1944     * @hide
1945     */
1946    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1947            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1948
1949    /*
1950     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1951     * flag value.
1952     * @hide
1953     */
1954    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1955            LAYOUT_DIRECTION_LTR,
1956            LAYOUT_DIRECTION_RTL,
1957            LAYOUT_DIRECTION_INHERIT,
1958            LAYOUT_DIRECTION_LOCALE
1959    };
1960
1961    /**
1962     * Default horizontal layout direction.
1963     */
1964    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1965
1966    /**
1967     * Default horizontal layout direction.
1968     * @hide
1969     */
1970    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1971
1972    /**
1973     * Text direction is inherited thru {@link ViewGroup}
1974     */
1975    public static final int TEXT_DIRECTION_INHERIT = 0;
1976
1977    /**
1978     * Text direction is using "first strong algorithm". The first strong directional character
1979     * determines the paragraph direction. If there is no strong directional character, the
1980     * paragraph direction is the view's resolved layout direction.
1981     */
1982    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1983
1984    /**
1985     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1986     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1987     * If there are neither, the paragraph direction is the view's resolved layout direction.
1988     */
1989    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1990
1991    /**
1992     * Text direction is forced to LTR.
1993     */
1994    public static final int TEXT_DIRECTION_LTR = 3;
1995
1996    /**
1997     * Text direction is forced to RTL.
1998     */
1999    public static final int TEXT_DIRECTION_RTL = 4;
2000
2001    /**
2002     * Text direction is coming from the system Locale.
2003     */
2004    public static final int TEXT_DIRECTION_LOCALE = 5;
2005
2006    /**
2007     * Default text direction is inherited
2008     */
2009    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2010
2011    /**
2012     * Default resolved text direction
2013     * @hide
2014     */
2015    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2016
2017    /**
2018     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2019     * @hide
2020     */
2021    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2022
2023    /**
2024     * Mask for use with private flags indicating bits used for text direction.
2025     * @hide
2026     */
2027    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2028            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2029
2030    /**
2031     * Array of text direction flags for mapping attribute "textDirection" to correct
2032     * flag value.
2033     * @hide
2034     */
2035    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2036            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2037            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2038            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2039            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2040            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2041            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2042    };
2043
2044    /**
2045     * Indicates whether the view text direction has been resolved.
2046     * @hide
2047     */
2048    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2049            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2050
2051    /**
2052     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2053     * @hide
2054     */
2055    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2056
2057    /**
2058     * Mask for use with private flags indicating bits used for resolved text direction.
2059     * @hide
2060     */
2061    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2062            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2063
2064    /**
2065     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2066     * @hide
2067     */
2068    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2069            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2070
2071    /** @hide */
2072    @IntDef({
2073        TEXT_ALIGNMENT_INHERIT,
2074        TEXT_ALIGNMENT_GRAVITY,
2075        TEXT_ALIGNMENT_CENTER,
2076        TEXT_ALIGNMENT_TEXT_START,
2077        TEXT_ALIGNMENT_TEXT_END,
2078        TEXT_ALIGNMENT_VIEW_START,
2079        TEXT_ALIGNMENT_VIEW_END
2080    })
2081    @Retention(RetentionPolicy.SOURCE)
2082    public @interface TextAlignment {}
2083
2084    /**
2085     * Default text alignment. The text alignment of this View is inherited from its parent.
2086     * Use with {@link #setTextAlignment(int)}
2087     */
2088    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2089
2090    /**
2091     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2092     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2093     *
2094     * Use with {@link #setTextAlignment(int)}
2095     */
2096    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2097
2098    /**
2099     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2100     *
2101     * Use with {@link #setTextAlignment(int)}
2102     */
2103    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2104
2105    /**
2106     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2107     *
2108     * Use with {@link #setTextAlignment(int)}
2109     */
2110    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2111
2112    /**
2113     * Center the paragraph, e.g. ALIGN_CENTER.
2114     *
2115     * Use with {@link #setTextAlignment(int)}
2116     */
2117    public static final int TEXT_ALIGNMENT_CENTER = 4;
2118
2119    /**
2120     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2121     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2122     *
2123     * Use with {@link #setTextAlignment(int)}
2124     */
2125    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2126
2127    /**
2128     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2129     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2130     *
2131     * Use with {@link #setTextAlignment(int)}
2132     */
2133    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2134
2135    /**
2136     * Default text alignment is inherited
2137     */
2138    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2139
2140    /**
2141     * Default resolved text alignment
2142     * @hide
2143     */
2144    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2145
2146    /**
2147      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2148      * @hide
2149      */
2150    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2151
2152    /**
2153      * Mask for use with private flags indicating bits used for text alignment.
2154      * @hide
2155      */
2156    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2157
2158    /**
2159     * Array of text direction flags for mapping attribute "textAlignment" to correct
2160     * flag value.
2161     * @hide
2162     */
2163    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2164            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2166            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2168            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2169            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2170            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2171    };
2172
2173    /**
2174     * Indicates whether the view text alignment has been resolved.
2175     * @hide
2176     */
2177    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2178
2179    /**
2180     * Bit shift to get the resolved text alignment.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2184
2185    /**
2186     * Mask for use with private flags indicating bits used for text alignment.
2187     * @hide
2188     */
2189    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2190            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2191
2192    /**
2193     * Indicates whether if the view text alignment has been resolved to gravity
2194     */
2195    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2196            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2197
2198    // Accessiblity constants for mPrivateFlags2
2199
2200    /**
2201     * Shift for the bits in {@link #mPrivateFlags2} related to the
2202     * "importantForAccessibility" attribute.
2203     */
2204    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2205
2206    /**
2207     * Automatically determine whether a view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2210
2211    /**
2212     * The view is important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2215
2216    /**
2217     * The view is not important for accessibility.
2218     */
2219    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2220
2221    /**
2222     * The view is not important for accessibility, nor are any of its
2223     * descendant views.
2224     */
2225    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2226
2227    /**
2228     * The default whether the view is important for accessibility.
2229     */
2230    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2231
2232    /**
2233     * Mask for obtainig the bits which specify how to determine
2234     * whether a view is important for accessibility.
2235     */
2236    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2237        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2238        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2239        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2240
2241    /**
2242     * Shift for the bits in {@link #mPrivateFlags2} related to the
2243     * "accessibilityLiveRegion" attribute.
2244     */
2245    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2246
2247    /**
2248     * Live region mode specifying that accessibility services should not
2249     * automatically announce changes to this view. This is the default live
2250     * region mode for most views.
2251     * <p>
2252     * Use with {@link #setAccessibilityLiveRegion(int)}.
2253     */
2254    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2255
2256    /**
2257     * Live region mode specifying that accessibility services should announce
2258     * changes to this view.
2259     * <p>
2260     * Use with {@link #setAccessibilityLiveRegion(int)}.
2261     */
2262    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2263
2264    /**
2265     * Live region mode specifying that accessibility services should interrupt
2266     * ongoing speech to immediately announce changes to this view.
2267     * <p>
2268     * Use with {@link #setAccessibilityLiveRegion(int)}.
2269     */
2270    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2271
2272    /**
2273     * The default whether the view is important for accessibility.
2274     */
2275    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2276
2277    /**
2278     * Mask for obtaining the bits which specify a view's accessibility live
2279     * region mode.
2280     */
2281    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2282            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2283            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2284
2285    /**
2286     * Flag indicating whether a view has accessibility focus.
2287     */
2288    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2289
2290    /**
2291     * Flag whether the accessibility state of the subtree rooted at this view changed.
2292     */
2293    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2294
2295    /**
2296     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2297     * is used to check whether later changes to the view's transform should invalidate the
2298     * view to force the quickReject test to run again.
2299     */
2300    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2301
2302    /**
2303     * Flag indicating that start/end padding has been resolved into left/right padding
2304     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2305     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2306     * during measurement. In some special cases this is required such as when an adapter-based
2307     * view measures prospective children without attaching them to a window.
2308     */
2309    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2310
2311    /**
2312     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2313     */
2314    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2315
2316    /**
2317     * Indicates that the view is tracking some sort of transient state
2318     * that the app should not need to be aware of, but that the framework
2319     * should take special care to preserve.
2320     */
2321    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2322
2323    /**
2324     * Group of bits indicating that RTL properties resolution is done.
2325     */
2326    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2327            PFLAG2_TEXT_DIRECTION_RESOLVED |
2328            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2329            PFLAG2_PADDING_RESOLVED |
2330            PFLAG2_DRAWABLE_RESOLVED;
2331
2332    // There are a couple of flags left in mPrivateFlags2
2333
2334    /* End of masks for mPrivateFlags2 */
2335
2336    /**
2337     * Masks for mPrivateFlags3, as generated by dumpFlags():
2338     *
2339     * |-------|-------|-------|-------|
2340     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2341     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2342     *                               1   PFLAG3_IS_LAID_OUT
2343     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2344     *                             1     PFLAG3_CALLED_SUPER
2345     * |-------|-------|-------|-------|
2346     */
2347
2348    /**
2349     * Flag indicating that view has a transform animation set on it. This is used to track whether
2350     * an animation is cleared between successive frames, in order to tell the associated
2351     * DisplayList to clear its animation matrix.
2352     */
2353    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2354
2355    /**
2356     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2357     * animation is cleared between successive frames, in order to tell the associated
2358     * DisplayList to restore its alpha value.
2359     */
2360    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2361
2362    /**
2363     * Flag indicating that the view has been through at least one layout since it
2364     * was last attached to a window.
2365     */
2366    static final int PFLAG3_IS_LAID_OUT = 0x4;
2367
2368    /**
2369     * Flag indicating that a call to measure() was skipped and should be done
2370     * instead when layout() is invoked.
2371     */
2372    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2373
2374    /**
2375     * Flag indicating that an overridden method correctly  called down to
2376     * the superclass implementation as required by the API spec.
2377     */
2378    static final int PFLAG3_CALLED_SUPER = 0x10;
2379
2380    /**
2381     * Flag indicating that a view's outline has been specifically defined.
2382     */
2383    static final int PFLAG3_OUTLINE_DEFINED = 0x20;
2384
2385    /**
2386     * Flag indicating that we're in the process of applying window insets.
2387     */
2388    static final int PFLAG3_APPLYING_INSETS = 0x40;
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 = 0x80;
2394
2395    /**
2396     * Flag indicating that nested scrolling is enabled for this view.
2397     * The view will optionally cooperate with views up its parent chain to allow for
2398     * integrated nested scrolling along the same axis.
2399     */
2400    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200;
2401
2402    /* End of masks for mPrivateFlags3 */
2403
2404    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2405
2406    /**
2407     * Always allow a user to over-scroll this view, provided it is a
2408     * view that can scroll.
2409     *
2410     * @see #getOverScrollMode()
2411     * @see #setOverScrollMode(int)
2412     */
2413    public static final int OVER_SCROLL_ALWAYS = 0;
2414
2415    /**
2416     * Allow a user to over-scroll this view only if the content is large
2417     * enough to meaningfully scroll, provided it is a view that can scroll.
2418     *
2419     * @see #getOverScrollMode()
2420     * @see #setOverScrollMode(int)
2421     */
2422    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2423
2424    /**
2425     * Never allow a user to over-scroll this view.
2426     *
2427     * @see #getOverScrollMode()
2428     * @see #setOverScrollMode(int)
2429     */
2430    public static final int OVER_SCROLL_NEVER = 2;
2431
2432    /**
2433     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2434     * requested the system UI (status bar) to be visible (the default).
2435     *
2436     * @see #setSystemUiVisibility(int)
2437     */
2438    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2439
2440    /**
2441     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2442     * system UI to enter an unobtrusive "low profile" mode.
2443     *
2444     * <p>This is for use in games, book readers, video players, or any other
2445     * "immersive" application where the usual system chrome is deemed too distracting.
2446     *
2447     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2448     *
2449     * @see #setSystemUiVisibility(int)
2450     */
2451    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2452
2453    /**
2454     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2455     * system navigation be temporarily hidden.
2456     *
2457     * <p>This is an even less obtrusive state than that called for by
2458     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2459     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2460     * those to disappear. This is useful (in conjunction with the
2461     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2462     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2463     * window flags) for displaying content using every last pixel on the display.
2464     *
2465     * <p>There is a limitation: because navigation controls are so important, the least user
2466     * interaction will cause them to reappear immediately.  When this happens, both
2467     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2468     * so that both elements reappear at the same time.
2469     *
2470     * @see #setSystemUiVisibility(int)
2471     */
2472    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2473
2474    /**
2475     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2476     * into the normal fullscreen mode so that its content can take over the screen
2477     * while still allowing the user to interact with the application.
2478     *
2479     * <p>This has the same visual effect as
2480     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2481     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2482     * meaning that non-critical screen decorations (such as the status bar) will be
2483     * hidden while the user is in the View's window, focusing the experience on
2484     * that content.  Unlike the window flag, if you are using ActionBar in
2485     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2486     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2487     * hide the action bar.
2488     *
2489     * <p>This approach to going fullscreen is best used over the window flag when
2490     * it is a transient state -- that is, the application does this at certain
2491     * points in its user interaction where it wants to allow the user to focus
2492     * on content, but not as a continuous state.  For situations where the application
2493     * would like to simply stay full screen the entire time (such as a game that
2494     * wants to take over the screen), the
2495     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2496     * is usually a better approach.  The state set here will be removed by the system
2497     * in various situations (such as the user moving to another application) like
2498     * the other system UI states.
2499     *
2500     * <p>When using this flag, the application should provide some easy facility
2501     * for the user to go out of it.  A common example would be in an e-book
2502     * reader, where tapping on the screen brings back whatever screen and UI
2503     * decorations that had been hidden while the user was immersed in reading
2504     * the book.
2505     *
2506     * @see #setSystemUiVisibility(int)
2507     */
2508    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2509
2510    /**
2511     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2512     * flags, we would like a stable view of the content insets given to
2513     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2514     * will always represent the worst case that the application can expect
2515     * as a continuous state.  In the stock Android UI this is the space for
2516     * the system bar, nav bar, and status bar, but not more transient elements
2517     * such as an input method.
2518     *
2519     * The stable layout your UI sees is based on the system UI modes you can
2520     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2521     * then you will get a stable layout for changes of the
2522     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2523     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2524     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2525     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2526     * with a stable layout.  (Note that you should avoid using
2527     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2528     *
2529     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2530     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2531     * then a hidden status bar will be considered a "stable" state for purposes
2532     * here.  This allows your UI to continually hide the status bar, while still
2533     * using the system UI flags to hide the action bar while still retaining
2534     * a stable layout.  Note that changing the window fullscreen flag will never
2535     * provide a stable layout for a clean transition.
2536     *
2537     * <p>If you are using ActionBar in
2538     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2539     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2540     * insets it adds to those given to the application.
2541     */
2542    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2543
2544    /**
2545     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2546     * to be layed out as if it has requested
2547     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2548     * allows it to avoid artifacts when switching in and out of that mode, at
2549     * the expense that some of its user interface may be covered by screen
2550     * decorations when they are shown.  You can perform layout of your inner
2551     * UI elements to account for the navigation system UI through the
2552     * {@link #fitSystemWindows(Rect)} method.
2553     */
2554    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2555
2556    /**
2557     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2558     * to be layed out as if it has requested
2559     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2560     * allows it to avoid artifacts when switching in and out of that mode, at
2561     * the expense that some of its user interface may be covered by screen
2562     * decorations when they are shown.  You can perform layout of your inner
2563     * UI elements to account for non-fullscreen system UI through the
2564     * {@link #fitSystemWindows(Rect)} method.
2565     */
2566    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2571     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2572     * user interaction.
2573     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2574     * has an effect when used in combination with that flag.</p>
2575     */
2576    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2577
2578    /**
2579     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2580     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2581     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2582     * experience while also hiding the system bars.  If this flag is not set,
2583     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2584     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2585     * if the user swipes from the top of the screen.
2586     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2587     * system gestures, such as swiping from the top of the screen.  These transient system bars
2588     * will overlay app’s content, may have some degree of transparency, and will automatically
2589     * hide after a short timeout.
2590     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2591     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2592     * with one or both of those flags.</p>
2593     */
2594    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2595
2596    /**
2597     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2598     */
2599    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2600
2601    /**
2602     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2603     */
2604    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2605
2606    /**
2607     * @hide
2608     *
2609     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2610     * out of the public fields to keep the undefined bits out of the developer's way.
2611     *
2612     * Flag to make the status bar not expandable.  Unless you also
2613     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2614     */
2615    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2616
2617    /**
2618     * @hide
2619     *
2620     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2621     * out of the public fields to keep the undefined bits out of the developer's way.
2622     *
2623     * Flag to hide notification icons and scrolling ticker text.
2624     */
2625    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2626
2627    /**
2628     * @hide
2629     *
2630     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2631     * out of the public fields to keep the undefined bits out of the developer's way.
2632     *
2633     * Flag to disable incoming notification alerts.  This will not block
2634     * icons, but it will block sound, vibrating and other visual or aural notifications.
2635     */
2636    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2637
2638    /**
2639     * @hide
2640     *
2641     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2642     * out of the public fields to keep the undefined bits out of the developer's way.
2643     *
2644     * Flag to hide only the scrolling ticker.  Note that
2645     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2646     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2647     */
2648    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2649
2650    /**
2651     * @hide
2652     *
2653     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2654     * out of the public fields to keep the undefined bits out of the developer's way.
2655     *
2656     * Flag to hide the center system info area.
2657     */
2658    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2659
2660    /**
2661     * @hide
2662     *
2663     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2664     * out of the public fields to keep the undefined bits out of the developer's way.
2665     *
2666     * Flag to hide only the home button.  Don't use this
2667     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2668     */
2669    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2670
2671    /**
2672     * @hide
2673     *
2674     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2675     * out of the public fields to keep the undefined bits out of the developer's way.
2676     *
2677     * Flag to hide only the back button. Don't use this
2678     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2679     */
2680    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2681
2682    /**
2683     * @hide
2684     *
2685     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2686     * out of the public fields to keep the undefined bits out of the developer's way.
2687     *
2688     * Flag to hide only the clock.  You might use this if your activity has
2689     * its own clock making the status bar's clock redundant.
2690     */
2691    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2692
2693    /**
2694     * @hide
2695     *
2696     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2697     * out of the public fields to keep the undefined bits out of the developer's way.
2698     *
2699     * Flag to hide only the recent apps button. Don't use this
2700     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2701     */
2702    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2703
2704    /**
2705     * @hide
2706     *
2707     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2708     * out of the public fields to keep the undefined bits out of the developer's way.
2709     *
2710     * Flag to disable the global search gesture. Don't use this
2711     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2712     */
2713    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2714
2715    /**
2716     * @hide
2717     *
2718     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2719     * out of the public fields to keep the undefined bits out of the developer's way.
2720     *
2721     * Flag to specify that the status bar is displayed in transient mode.
2722     */
2723    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2724
2725    /**
2726     * @hide
2727     *
2728     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2729     * out of the public fields to keep the undefined bits out of the developer's way.
2730     *
2731     * Flag to specify that the navigation bar is displayed in transient mode.
2732     */
2733    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2734
2735    /**
2736     * @hide
2737     *
2738     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2739     * out of the public fields to keep the undefined bits out of the developer's way.
2740     *
2741     * Flag to specify that the hidden status bar would like to be shown.
2742     */
2743    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2744
2745    /**
2746     * @hide
2747     *
2748     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2749     * out of the public fields to keep the undefined bits out of the developer's way.
2750     *
2751     * Flag to specify that the hidden navigation bar would like to be shown.
2752     */
2753    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2754
2755    /**
2756     * @hide
2757     *
2758     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2759     * out of the public fields to keep the undefined bits out of the developer's way.
2760     *
2761     * Flag to specify that the status bar is displayed in translucent mode.
2762     */
2763    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2769     * out of the public fields to keep the undefined bits out of the developer's way.
2770     *
2771     * Flag to specify that the navigation bar is displayed in translucent mode.
2772     */
2773    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2774
2775    /**
2776     * @hide
2777     *
2778     * Whether Recents is visible or not.
2779     */
2780    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2781
2782    /**
2783     * @hide
2784     *
2785     * Makes system ui transparent.
2786     */
2787    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2788
2789    /**
2790     * @hide
2791     */
2792    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2793
2794    /**
2795     * These are the system UI flags that can be cleared by events outside
2796     * of an application.  Currently this is just the ability to tap on the
2797     * screen while hiding the navigation bar to have it return.
2798     * @hide
2799     */
2800    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2801            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2802            | SYSTEM_UI_FLAG_FULLSCREEN;
2803
2804    /**
2805     * Flags that can impact the layout in relation to system UI.
2806     */
2807    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2808            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2809            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2810
2811    /** @hide */
2812    @IntDef(flag = true,
2813            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2814    @Retention(RetentionPolicy.SOURCE)
2815    public @interface FindViewFlags {}
2816
2817    /**
2818     * Find views that render the specified text.
2819     *
2820     * @see #findViewsWithText(ArrayList, CharSequence, int)
2821     */
2822    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2823
2824    /**
2825     * Find find views that contain the specified content description.
2826     *
2827     * @see #findViewsWithText(ArrayList, CharSequence, int)
2828     */
2829    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2830
2831    /**
2832     * Find views that contain {@link AccessibilityNodeProvider}. Such
2833     * a View is a root of virtual view hierarchy and may contain the searched
2834     * text. If this flag is set Views with providers are automatically
2835     * added and it is a responsibility of the client to call the APIs of
2836     * the provider to determine whether the virtual tree rooted at this View
2837     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2838     * representing the virtual views with this text.
2839     *
2840     * @see #findViewsWithText(ArrayList, CharSequence, int)
2841     *
2842     * @hide
2843     */
2844    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2845
2846    /**
2847     * The undefined cursor position.
2848     *
2849     * @hide
2850     */
2851    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2852
2853    /**
2854     * Indicates that the screen has changed state and is now off.
2855     *
2856     * @see #onScreenStateChanged(int)
2857     */
2858    public static final int SCREEN_STATE_OFF = 0x0;
2859
2860    /**
2861     * Indicates that the screen has changed state and is now on.
2862     *
2863     * @see #onScreenStateChanged(int)
2864     */
2865    public static final int SCREEN_STATE_ON = 0x1;
2866
2867    /**
2868     * Indicates no axis of view scrolling.
2869     */
2870    public static final int SCROLL_AXIS_NONE = 0;
2871
2872    /**
2873     * Indicates scrolling along the horizontal axis.
2874     */
2875    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2876
2877    /**
2878     * Indicates scrolling along the vertical axis.
2879     */
2880    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2881
2882    /**
2883     * Controls the over-scroll mode for this view.
2884     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2885     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2886     * and {@link #OVER_SCROLL_NEVER}.
2887     */
2888    private int mOverScrollMode;
2889
2890    /**
2891     * The parent this view is attached to.
2892     * {@hide}
2893     *
2894     * @see #getParent()
2895     */
2896    protected ViewParent mParent;
2897
2898    /**
2899     * {@hide}
2900     */
2901    AttachInfo mAttachInfo;
2902
2903    /**
2904     * {@hide}
2905     */
2906    @ViewDebug.ExportedProperty(flagMapping = {
2907        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2908                name = "FORCE_LAYOUT"),
2909        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2910                name = "LAYOUT_REQUIRED"),
2911        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2912            name = "DRAWING_CACHE_INVALID", outputIf = false),
2913        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2914        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2915        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2916        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2917    })
2918    int mPrivateFlags;
2919    int mPrivateFlags2;
2920    int mPrivateFlags3;
2921
2922    /**
2923     * This view's request for the visibility of the status bar.
2924     * @hide
2925     */
2926    @ViewDebug.ExportedProperty(flagMapping = {
2927        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2928                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2929                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2930        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2931                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2932                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2933        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2934                                equals = SYSTEM_UI_FLAG_VISIBLE,
2935                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2936    })
2937    int mSystemUiVisibility;
2938
2939    /**
2940     * Reference count for transient state.
2941     * @see #setHasTransientState(boolean)
2942     */
2943    int mTransientStateCount = 0;
2944
2945    /**
2946     * Count of how many windows this view has been attached to.
2947     */
2948    int mWindowAttachCount;
2949
2950    /**
2951     * The layout parameters associated with this view and used by the parent
2952     * {@link android.view.ViewGroup} to determine how this view should be
2953     * laid out.
2954     * {@hide}
2955     */
2956    protected ViewGroup.LayoutParams mLayoutParams;
2957
2958    /**
2959     * The view flags hold various views states.
2960     * {@hide}
2961     */
2962    @ViewDebug.ExportedProperty
2963    int mViewFlags;
2964
2965    static class TransformationInfo {
2966        /**
2967         * The transform matrix for the View. This transform is calculated internally
2968         * based on the translation, rotation, and scale properties.
2969         *
2970         * Do *not* use this variable directly; instead call getMatrix(), which will
2971         * load the value from the View's RenderNode.
2972         */
2973        private final Matrix mMatrix = new Matrix();
2974
2975        /**
2976         * The inverse transform matrix for the View. This transform is calculated
2977         * internally based on the translation, rotation, and scale properties.
2978         *
2979         * Do *not* use this variable directly; instead call getInverseMatrix(),
2980         * which will load the value from the View's RenderNode.
2981         */
2982        private Matrix mInverseMatrix;
2983
2984        /**
2985         * The opacity of the View. This is a value from 0 to 1, where 0 means
2986         * completely transparent and 1 means completely opaque.
2987         */
2988        @ViewDebug.ExportedProperty
2989        float mAlpha = 1f;
2990
2991        /**
2992         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2993         * property only used by transitions, which is composited with the other alpha
2994         * values to calculate the final visual alpha value.
2995         */
2996        float mTransitionAlpha = 1f;
2997    }
2998
2999    TransformationInfo mTransformationInfo;
3000
3001    /**
3002     * Current clip bounds. to which all drawing of this view are constrained.
3003     */
3004    Rect mClipBounds = null;
3005
3006    private boolean mLastIsOpaque;
3007
3008    /**
3009     * The distance in pixels from the left edge of this view's parent
3010     * to the left edge of this view.
3011     * {@hide}
3012     */
3013    @ViewDebug.ExportedProperty(category = "layout")
3014    protected int mLeft;
3015    /**
3016     * The distance in pixels from the left edge of this view's parent
3017     * to the right edge of this view.
3018     * {@hide}
3019     */
3020    @ViewDebug.ExportedProperty(category = "layout")
3021    protected int mRight;
3022    /**
3023     * The distance in pixels from the top edge of this view's parent
3024     * to the top edge of this view.
3025     * {@hide}
3026     */
3027    @ViewDebug.ExportedProperty(category = "layout")
3028    protected int mTop;
3029    /**
3030     * The distance in pixels from the top edge of this view's parent
3031     * to the bottom edge of this view.
3032     * {@hide}
3033     */
3034    @ViewDebug.ExportedProperty(category = "layout")
3035    protected int mBottom;
3036
3037    /**
3038     * The offset, in pixels, by which the content of this view is scrolled
3039     * horizontally.
3040     * {@hide}
3041     */
3042    @ViewDebug.ExportedProperty(category = "scrolling")
3043    protected int mScrollX;
3044    /**
3045     * The offset, in pixels, by which the content of this view is scrolled
3046     * vertically.
3047     * {@hide}
3048     */
3049    @ViewDebug.ExportedProperty(category = "scrolling")
3050    protected int mScrollY;
3051
3052    /**
3053     * The left padding in pixels, that is the distance in pixels between the
3054     * left edge of this view and the left edge of its content.
3055     * {@hide}
3056     */
3057    @ViewDebug.ExportedProperty(category = "padding")
3058    protected int mPaddingLeft = 0;
3059    /**
3060     * The right padding in pixels, that is the distance in pixels between the
3061     * right edge of this view and the right edge of its content.
3062     * {@hide}
3063     */
3064    @ViewDebug.ExportedProperty(category = "padding")
3065    protected int mPaddingRight = 0;
3066    /**
3067     * The top padding in pixels, that is the distance in pixels between the
3068     * top edge of this view and the top edge of its content.
3069     * {@hide}
3070     */
3071    @ViewDebug.ExportedProperty(category = "padding")
3072    protected int mPaddingTop;
3073    /**
3074     * The bottom padding in pixels, that is the distance in pixels between the
3075     * bottom edge of this view and the bottom edge of its content.
3076     * {@hide}
3077     */
3078    @ViewDebug.ExportedProperty(category = "padding")
3079    protected int mPaddingBottom;
3080
3081    /**
3082     * The layout insets in pixels, that is the distance in pixels between the
3083     * visible edges of this view its bounds.
3084     */
3085    private Insets mLayoutInsets;
3086
3087    /**
3088     * Briefly describes the view and is primarily used for accessibility support.
3089     */
3090    private CharSequence mContentDescription;
3091
3092    /**
3093     * Specifies the id of a view for which this view serves as a label for
3094     * accessibility purposes.
3095     */
3096    private int mLabelForId = View.NO_ID;
3097
3098    /**
3099     * Predicate for matching labeled view id with its label for
3100     * accessibility purposes.
3101     */
3102    private MatchLabelForPredicate mMatchLabelForPredicate;
3103
3104    /**
3105     * Predicate for matching a view by its id.
3106     */
3107    private MatchIdPredicate mMatchIdPredicate;
3108
3109    /**
3110     * Cache the paddingRight set by the user to append to the scrollbar's size.
3111     *
3112     * @hide
3113     */
3114    @ViewDebug.ExportedProperty(category = "padding")
3115    protected int mUserPaddingRight;
3116
3117    /**
3118     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3119     *
3120     * @hide
3121     */
3122    @ViewDebug.ExportedProperty(category = "padding")
3123    protected int mUserPaddingBottom;
3124
3125    /**
3126     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3127     *
3128     * @hide
3129     */
3130    @ViewDebug.ExportedProperty(category = "padding")
3131    protected int mUserPaddingLeft;
3132
3133    /**
3134     * Cache the paddingStart set by the user to append to the scrollbar's size.
3135     *
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    int mUserPaddingStart;
3139
3140    /**
3141     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3142     *
3143     */
3144    @ViewDebug.ExportedProperty(category = "padding")
3145    int mUserPaddingEnd;
3146
3147    /**
3148     * Cache initial left padding.
3149     *
3150     * @hide
3151     */
3152    int mUserPaddingLeftInitial;
3153
3154    /**
3155     * Cache initial right padding.
3156     *
3157     * @hide
3158     */
3159    int mUserPaddingRightInitial;
3160
3161    /**
3162     * Default undefined padding
3163     */
3164    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3165
3166    /**
3167     * Cache if a left padding has been defined
3168     */
3169    private boolean mLeftPaddingDefined = false;
3170
3171    /**
3172     * Cache if a right padding has been defined
3173     */
3174    private boolean mRightPaddingDefined = false;
3175
3176    /**
3177     * @hide
3178     */
3179    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3180    /**
3181     * @hide
3182     */
3183    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3184
3185    private LongSparseLongArray mMeasureCache;
3186
3187    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3188    private Drawable mBackground;
3189
3190    /**
3191     * Display list used for backgrounds.
3192     * <p>
3193     * When non-null and valid, this is expected to contain an up-to-date copy
3194     * of the background drawable. It is cleared on temporary detach and reset
3195     * on cleanup.
3196     */
3197    private RenderNode mBackgroundDisplayList;
3198
3199    private int mBackgroundResource;
3200    private boolean mBackgroundSizeChanged;
3201
3202    private String mViewName;
3203
3204    static class ListenerInfo {
3205        /**
3206         * Listener used to dispatch focus change events.
3207         * This field should be made private, so it is hidden from the SDK.
3208         * {@hide}
3209         */
3210        protected OnFocusChangeListener mOnFocusChangeListener;
3211
3212        /**
3213         * Listeners for layout change events.
3214         */
3215        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3216
3217        /**
3218         * Listeners for attach events.
3219         */
3220        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3221
3222        /**
3223         * Listener used to dispatch click events.
3224         * This field should be made private, so it is hidden from the SDK.
3225         * {@hide}
3226         */
3227        public OnClickListener mOnClickListener;
3228
3229        /**
3230         * Listener used to dispatch long click events.
3231         * This field should be made private, so it is hidden from the SDK.
3232         * {@hide}
3233         */
3234        protected OnLongClickListener mOnLongClickListener;
3235
3236        /**
3237         * Listener used to build the context menu.
3238         * This field should be made private, so it is hidden from the SDK.
3239         * {@hide}
3240         */
3241        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3242
3243        private OnKeyListener mOnKeyListener;
3244
3245        private OnTouchListener mOnTouchListener;
3246
3247        private OnHoverListener mOnHoverListener;
3248
3249        private OnGenericMotionListener mOnGenericMotionListener;
3250
3251        private OnDragListener mOnDragListener;
3252
3253        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3254
3255        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3256    }
3257
3258    ListenerInfo mListenerInfo;
3259
3260    /**
3261     * The application environment this view lives in.
3262     * This field should be made private, so it is hidden from the SDK.
3263     * {@hide}
3264     */
3265    protected Context mContext;
3266
3267    private final Resources mResources;
3268
3269    private ScrollabilityCache mScrollCache;
3270
3271    private int[] mDrawableState = null;
3272
3273    /**
3274     * Stores the outline of the view, passed down to the DisplayList level for
3275     * defining shadow shape.
3276     */
3277    private Outline mOutline;
3278
3279    /**
3280     * Animator that automatically runs based on state changes.
3281     */
3282    private StateListAnimator mStateListAnimator;
3283
3284    /**
3285     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3286     * the user may specify which view to go to next.
3287     */
3288    private int mNextFocusLeftId = View.NO_ID;
3289
3290    /**
3291     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3292     * the user may specify which view to go to next.
3293     */
3294    private int mNextFocusRightId = View.NO_ID;
3295
3296    /**
3297     * When this view has focus and the next focus is {@link #FOCUS_UP},
3298     * the user may specify which view to go to next.
3299     */
3300    private int mNextFocusUpId = View.NO_ID;
3301
3302    /**
3303     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3304     * the user may specify which view to go to next.
3305     */
3306    private int mNextFocusDownId = View.NO_ID;
3307
3308    /**
3309     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3310     * the user may specify which view to go to next.
3311     */
3312    int mNextFocusForwardId = View.NO_ID;
3313
3314    private CheckForLongPress mPendingCheckForLongPress;
3315    private CheckForTap mPendingCheckForTap = null;
3316    private PerformClick mPerformClick;
3317    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3318
3319    private UnsetPressedState mUnsetPressedState;
3320
3321    /**
3322     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3323     * up event while a long press is invoked as soon as the long press duration is reached, so
3324     * a long press could be performed before the tap is checked, in which case the tap's action
3325     * should not be invoked.
3326     */
3327    private boolean mHasPerformedLongPress;
3328
3329    /**
3330     * The minimum height of the view. We'll try our best to have the height
3331     * of this view to at least this amount.
3332     */
3333    @ViewDebug.ExportedProperty(category = "measurement")
3334    private int mMinHeight;
3335
3336    /**
3337     * The minimum width of the view. We'll try our best to have the width
3338     * of this view to at least this amount.
3339     */
3340    @ViewDebug.ExportedProperty(category = "measurement")
3341    private int mMinWidth;
3342
3343    /**
3344     * The delegate to handle touch events that are physically in this view
3345     * but should be handled by another view.
3346     */
3347    private TouchDelegate mTouchDelegate = null;
3348
3349    /**
3350     * Solid color to use as a background when creating the drawing cache. Enables
3351     * the cache to use 16 bit bitmaps instead of 32 bit.
3352     */
3353    private int mDrawingCacheBackgroundColor = 0;
3354
3355    /**
3356     * Special tree observer used when mAttachInfo is null.
3357     */
3358    private ViewTreeObserver mFloatingTreeObserver;
3359
3360    /**
3361     * Cache the touch slop from the context that created the view.
3362     */
3363    private int mTouchSlop;
3364
3365    /**
3366     * Object that handles automatic animation of view properties.
3367     */
3368    private ViewPropertyAnimator mAnimator = null;
3369
3370    /**
3371     * Flag indicating that a drag can cross window boundaries.  When
3372     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3373     * with this flag set, all visible applications will be able to participate
3374     * in the drag operation and receive the dragged content.
3375     *
3376     * @hide
3377     */
3378    public static final int DRAG_FLAG_GLOBAL = 1;
3379
3380    /**
3381     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3382     */
3383    private float mVerticalScrollFactor;
3384
3385    /**
3386     * Position of the vertical scroll bar.
3387     */
3388    private int mVerticalScrollbarPosition;
3389
3390    /**
3391     * Position the scroll bar at the default position as determined by the system.
3392     */
3393    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3394
3395    /**
3396     * Position the scroll bar along the left edge.
3397     */
3398    public static final int SCROLLBAR_POSITION_LEFT = 1;
3399
3400    /**
3401     * Position the scroll bar along the right edge.
3402     */
3403    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3404
3405    /**
3406     * Indicates that the view does not have a layer.
3407     *
3408     * @see #getLayerType()
3409     * @see #setLayerType(int, android.graphics.Paint)
3410     * @see #LAYER_TYPE_SOFTWARE
3411     * @see #LAYER_TYPE_HARDWARE
3412     */
3413    public static final int LAYER_TYPE_NONE = 0;
3414
3415    /**
3416     * <p>Indicates that the view has a software layer. A software layer is backed
3417     * by a bitmap and causes the view to be rendered using Android's software
3418     * rendering pipeline, even if hardware acceleration is enabled.</p>
3419     *
3420     * <p>Software layers have various usages:</p>
3421     * <p>When the application is not using hardware acceleration, a software layer
3422     * is useful to apply a specific color filter and/or blending mode and/or
3423     * translucency to a view and all its children.</p>
3424     * <p>When the application is using hardware acceleration, a software layer
3425     * is useful to render drawing primitives not supported by the hardware
3426     * accelerated pipeline. It can also be used to cache a complex view tree
3427     * into a texture and reduce the complexity of drawing operations. For instance,
3428     * when animating a complex view tree with a translation, a software layer can
3429     * be used to render the view tree only once.</p>
3430     * <p>Software layers should be avoided when the affected view tree updates
3431     * often. Every update will require to re-render the software layer, which can
3432     * potentially be slow (particularly when hardware acceleration is turned on
3433     * since the layer will have to be uploaded into a hardware texture after every
3434     * update.)</p>
3435     *
3436     * @see #getLayerType()
3437     * @see #setLayerType(int, android.graphics.Paint)
3438     * @see #LAYER_TYPE_NONE
3439     * @see #LAYER_TYPE_HARDWARE
3440     */
3441    public static final int LAYER_TYPE_SOFTWARE = 1;
3442
3443    /**
3444     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3445     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3446     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3447     * rendering pipeline, but only if hardware acceleration is turned on for the
3448     * view hierarchy. When hardware acceleration is turned off, hardware layers
3449     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3450     *
3451     * <p>A hardware layer is useful to apply a specific color filter and/or
3452     * blending mode and/or translucency to a view and all its children.</p>
3453     * <p>A hardware layer can be used to cache a complex view tree into a
3454     * texture and reduce the complexity of drawing operations. For instance,
3455     * when animating a complex view tree with a translation, a hardware layer can
3456     * be used to render the view tree only once.</p>
3457     * <p>A hardware layer can also be used to increase the rendering quality when
3458     * rotation transformations are applied on a view. It can also be used to
3459     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3460     *
3461     * @see #getLayerType()
3462     * @see #setLayerType(int, android.graphics.Paint)
3463     * @see #LAYER_TYPE_NONE
3464     * @see #LAYER_TYPE_SOFTWARE
3465     */
3466    public static final int LAYER_TYPE_HARDWARE = 2;
3467
3468    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3469            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3470            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3471            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3472    })
3473    int mLayerType = LAYER_TYPE_NONE;
3474    Paint mLayerPaint;
3475
3476    /**
3477     * Set to true when drawing cache is enabled and cannot be created.
3478     *
3479     * @hide
3480     */
3481    public boolean mCachingFailed;
3482    private Bitmap mDrawingCache;
3483    private Bitmap mUnscaledDrawingCache;
3484
3485    /**
3486     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3487     * <p>
3488     * When non-null and valid, this is expected to contain an up-to-date copy
3489     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3490     * cleanup.
3491     */
3492    final RenderNode mRenderNode;
3493
3494    /**
3495     * Set to true when the view is sending hover accessibility events because it
3496     * is the innermost hovered view.
3497     */
3498    private boolean mSendingHoverAccessibilityEvents;
3499
3500    /**
3501     * Delegate for injecting accessibility functionality.
3502     */
3503    AccessibilityDelegate mAccessibilityDelegate;
3504
3505    /**
3506     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3507     * and add/remove objects to/from the overlay directly through the Overlay methods.
3508     */
3509    ViewOverlay mOverlay;
3510
3511    /**
3512     * The currently active parent view for receiving delegated nested scrolling events.
3513     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3514     * by {@link #stopNestedScroll()} at the same point where we clear
3515     * requestDisallowInterceptTouchEvent.
3516     */
3517    private ViewParent mNestedScrollingParent;
3518
3519    /**
3520     * Consistency verifier for debugging purposes.
3521     * @hide
3522     */
3523    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3524            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3525                    new InputEventConsistencyVerifier(this, 0) : null;
3526
3527    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3528
3529    private int[] mTempNestedScrollConsumed;
3530
3531    /**
3532     * Simple constructor to use when creating a view from code.
3533     *
3534     * @param context The Context the view is running in, through which it can
3535     *        access the current theme, resources, etc.
3536     */
3537    public View(Context context) {
3538        mContext = context;
3539        mResources = context != null ? context.getResources() : null;
3540        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3541        // Set some flags defaults
3542        mPrivateFlags2 =
3543                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3544                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3545                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3546                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3547                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3548                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3549        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3550        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3551        mUserPaddingStart = UNDEFINED_PADDING;
3552        mUserPaddingEnd = UNDEFINED_PADDING;
3553        mRenderNode = RenderNode.create(getClass().getName());
3554
3555        if (!sCompatibilityDone && context != null) {
3556            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3557
3558            // Older apps may need this compatibility hack for measurement.
3559            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3560
3561            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3562            // of whether a layout was requested on that View.
3563            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3564
3565            // Older apps may need this to ignore the clip bounds
3566            sIgnoreClipBoundsForChildren = targetSdkVersion < L;
3567
3568            sCompatibilityDone = true;
3569        }
3570    }
3571
3572    /**
3573     * Constructor that is called when inflating a view from XML. This is called
3574     * when a view is being constructed from an XML file, supplying attributes
3575     * that were specified in the XML file. This version uses a default style of
3576     * 0, so the only attribute values applied are those in the Context's Theme
3577     * and the given AttributeSet.
3578     *
3579     * <p>
3580     * The method onFinishInflate() will be called after all children have been
3581     * added.
3582     *
3583     * @param context The Context the view is running in, through which it can
3584     *        access the current theme, resources, etc.
3585     * @param attrs The attributes of the XML tag that is inflating the view.
3586     * @see #View(Context, AttributeSet, int)
3587     */
3588    public View(Context context, AttributeSet attrs) {
3589        this(context, attrs, 0);
3590    }
3591
3592    /**
3593     * Perform inflation from XML and apply a class-specific base style from a
3594     * theme attribute. This constructor of View allows subclasses to use their
3595     * own base style when they are inflating. For example, a Button class's
3596     * constructor would call this version of the super class constructor and
3597     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3598     * allows the theme's button style to modify all of the base view attributes
3599     * (in particular its background) as well as the Button class's attributes.
3600     *
3601     * @param context The Context the view is running in, through which it can
3602     *        access the current theme, resources, etc.
3603     * @param attrs The attributes of the XML tag that is inflating the view.
3604     * @param defStyleAttr An attribute in the current theme that contains a
3605     *        reference to a style resource that supplies default values for
3606     *        the view. Can be 0 to not look for defaults.
3607     * @see #View(Context, AttributeSet)
3608     */
3609    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3610        this(context, attrs, defStyleAttr, 0);
3611    }
3612
3613    /**
3614     * Perform inflation from XML and apply a class-specific base style from a
3615     * theme attribute or style resource. This constructor of View allows
3616     * subclasses to use their own base style when they are inflating.
3617     * <p>
3618     * When determining the final value of a particular attribute, there are
3619     * four inputs that come into play:
3620     * <ol>
3621     * <li>Any attribute values in the given AttributeSet.
3622     * <li>The style resource specified in the AttributeSet (named "style").
3623     * <li>The default style specified by <var>defStyleAttr</var>.
3624     * <li>The default style specified by <var>defStyleRes</var>.
3625     * <li>The base values in this theme.
3626     * </ol>
3627     * <p>
3628     * Each of these inputs is considered in-order, with the first listed taking
3629     * precedence over the following ones. In other words, if in the
3630     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3631     * , then the button's text will <em>always</em> be black, regardless of
3632     * what is specified in any of the styles.
3633     *
3634     * @param context The Context the view is running in, through which it can
3635     *        access the current theme, resources, etc.
3636     * @param attrs The attributes of the XML tag that is inflating the view.
3637     * @param defStyleAttr An attribute in the current theme that contains a
3638     *        reference to a style resource that supplies default values for
3639     *        the view. Can be 0 to not look for defaults.
3640     * @param defStyleRes A resource identifier of a style resource that
3641     *        supplies default values for the view, used only if
3642     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3643     *        to not look for defaults.
3644     * @see #View(Context, AttributeSet, int)
3645     */
3646    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3647        this(context);
3648
3649        final TypedArray a = context.obtainStyledAttributes(
3650                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3651
3652        Drawable background = null;
3653
3654        int leftPadding = -1;
3655        int topPadding = -1;
3656        int rightPadding = -1;
3657        int bottomPadding = -1;
3658        int startPadding = UNDEFINED_PADDING;
3659        int endPadding = UNDEFINED_PADDING;
3660
3661        int padding = -1;
3662
3663        int viewFlagValues = 0;
3664        int viewFlagMasks = 0;
3665
3666        boolean setScrollContainer = false;
3667
3668        int x = 0;
3669        int y = 0;
3670
3671        float tx = 0;
3672        float ty = 0;
3673        float tz = 0;
3674        float elevation = 0;
3675        float rotation = 0;
3676        float rotationX = 0;
3677        float rotationY = 0;
3678        float sx = 1f;
3679        float sy = 1f;
3680        boolean transformSet = false;
3681
3682        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3683        int overScrollMode = mOverScrollMode;
3684        boolean initializeScrollbars = false;
3685
3686        boolean startPaddingDefined = false;
3687        boolean endPaddingDefined = false;
3688        boolean leftPaddingDefined = false;
3689        boolean rightPaddingDefined = false;
3690
3691        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3692
3693        final int N = a.getIndexCount();
3694        for (int i = 0; i < N; i++) {
3695            int attr = a.getIndex(i);
3696            switch (attr) {
3697                case com.android.internal.R.styleable.View_background:
3698                    background = a.getDrawable(attr);
3699                    break;
3700                case com.android.internal.R.styleable.View_padding:
3701                    padding = a.getDimensionPixelSize(attr, -1);
3702                    mUserPaddingLeftInitial = padding;
3703                    mUserPaddingRightInitial = padding;
3704                    leftPaddingDefined = true;
3705                    rightPaddingDefined = true;
3706                    break;
3707                 case com.android.internal.R.styleable.View_paddingLeft:
3708                    leftPadding = a.getDimensionPixelSize(attr, -1);
3709                    mUserPaddingLeftInitial = leftPadding;
3710                    leftPaddingDefined = true;
3711                    break;
3712                case com.android.internal.R.styleable.View_paddingTop:
3713                    topPadding = a.getDimensionPixelSize(attr, -1);
3714                    break;
3715                case com.android.internal.R.styleable.View_paddingRight:
3716                    rightPadding = a.getDimensionPixelSize(attr, -1);
3717                    mUserPaddingRightInitial = rightPadding;
3718                    rightPaddingDefined = true;
3719                    break;
3720                case com.android.internal.R.styleable.View_paddingBottom:
3721                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3722                    break;
3723                case com.android.internal.R.styleable.View_paddingStart:
3724                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3725                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3726                    break;
3727                case com.android.internal.R.styleable.View_paddingEnd:
3728                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3729                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3730                    break;
3731                case com.android.internal.R.styleable.View_scrollX:
3732                    x = a.getDimensionPixelOffset(attr, 0);
3733                    break;
3734                case com.android.internal.R.styleable.View_scrollY:
3735                    y = a.getDimensionPixelOffset(attr, 0);
3736                    break;
3737                case com.android.internal.R.styleable.View_alpha:
3738                    setAlpha(a.getFloat(attr, 1f));
3739                    break;
3740                case com.android.internal.R.styleable.View_transformPivotX:
3741                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3742                    break;
3743                case com.android.internal.R.styleable.View_transformPivotY:
3744                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3745                    break;
3746                case com.android.internal.R.styleable.View_translationX:
3747                    tx = a.getDimensionPixelOffset(attr, 0);
3748                    transformSet = true;
3749                    break;
3750                case com.android.internal.R.styleable.View_translationY:
3751                    ty = a.getDimensionPixelOffset(attr, 0);
3752                    transformSet = true;
3753                    break;
3754                case com.android.internal.R.styleable.View_translationZ:
3755                    tz = a.getDimensionPixelOffset(attr, 0);
3756                    transformSet = true;
3757                    break;
3758                case com.android.internal.R.styleable.View_elevation:
3759                    elevation = a.getDimensionPixelOffset(attr, 0);
3760                    transformSet = true;
3761                    break;
3762                case com.android.internal.R.styleable.View_rotation:
3763                    rotation = a.getFloat(attr, 0);
3764                    transformSet = true;
3765                    break;
3766                case com.android.internal.R.styleable.View_rotationX:
3767                    rotationX = a.getFloat(attr, 0);
3768                    transformSet = true;
3769                    break;
3770                case com.android.internal.R.styleable.View_rotationY:
3771                    rotationY = a.getFloat(attr, 0);
3772                    transformSet = true;
3773                    break;
3774                case com.android.internal.R.styleable.View_scaleX:
3775                    sx = a.getFloat(attr, 1f);
3776                    transformSet = true;
3777                    break;
3778                case com.android.internal.R.styleable.View_scaleY:
3779                    sy = a.getFloat(attr, 1f);
3780                    transformSet = true;
3781                    break;
3782                case com.android.internal.R.styleable.View_id:
3783                    mID = a.getResourceId(attr, NO_ID);
3784                    break;
3785                case com.android.internal.R.styleable.View_tag:
3786                    mTag = a.getText(attr);
3787                    break;
3788                case com.android.internal.R.styleable.View_fitsSystemWindows:
3789                    if (a.getBoolean(attr, false)) {
3790                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3791                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3792                    }
3793                    break;
3794                case com.android.internal.R.styleable.View_focusable:
3795                    if (a.getBoolean(attr, false)) {
3796                        viewFlagValues |= FOCUSABLE;
3797                        viewFlagMasks |= FOCUSABLE_MASK;
3798                    }
3799                    break;
3800                case com.android.internal.R.styleable.View_focusableInTouchMode:
3801                    if (a.getBoolean(attr, false)) {
3802                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3803                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3804                    }
3805                    break;
3806                case com.android.internal.R.styleable.View_clickable:
3807                    if (a.getBoolean(attr, false)) {
3808                        viewFlagValues |= CLICKABLE;
3809                        viewFlagMasks |= CLICKABLE;
3810                    }
3811                    break;
3812                case com.android.internal.R.styleable.View_longClickable:
3813                    if (a.getBoolean(attr, false)) {
3814                        viewFlagValues |= LONG_CLICKABLE;
3815                        viewFlagMasks |= LONG_CLICKABLE;
3816                    }
3817                    break;
3818                case com.android.internal.R.styleable.View_saveEnabled:
3819                    if (!a.getBoolean(attr, true)) {
3820                        viewFlagValues |= SAVE_DISABLED;
3821                        viewFlagMasks |= SAVE_DISABLED_MASK;
3822                    }
3823                    break;
3824                case com.android.internal.R.styleable.View_duplicateParentState:
3825                    if (a.getBoolean(attr, false)) {
3826                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3827                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3828                    }
3829                    break;
3830                case com.android.internal.R.styleable.View_visibility:
3831                    final int visibility = a.getInt(attr, 0);
3832                    if (visibility != 0) {
3833                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3834                        viewFlagMasks |= VISIBILITY_MASK;
3835                    }
3836                    break;
3837                case com.android.internal.R.styleable.View_layoutDirection:
3838                    // Clear any layout direction flags (included resolved bits) already set
3839                    mPrivateFlags2 &=
3840                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3841                    // Set the layout direction flags depending on the value of the attribute
3842                    final int layoutDirection = a.getInt(attr, -1);
3843                    final int value = (layoutDirection != -1) ?
3844                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3845                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3846                    break;
3847                case com.android.internal.R.styleable.View_drawingCacheQuality:
3848                    final int cacheQuality = a.getInt(attr, 0);
3849                    if (cacheQuality != 0) {
3850                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3851                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3852                    }
3853                    break;
3854                case com.android.internal.R.styleable.View_contentDescription:
3855                    setContentDescription(a.getString(attr));
3856                    break;
3857                case com.android.internal.R.styleable.View_labelFor:
3858                    setLabelFor(a.getResourceId(attr, NO_ID));
3859                    break;
3860                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3861                    if (!a.getBoolean(attr, true)) {
3862                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3863                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3864                    }
3865                    break;
3866                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3867                    if (!a.getBoolean(attr, true)) {
3868                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3869                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3870                    }
3871                    break;
3872                case R.styleable.View_scrollbars:
3873                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3874                    if (scrollbars != SCROLLBARS_NONE) {
3875                        viewFlagValues |= scrollbars;
3876                        viewFlagMasks |= SCROLLBARS_MASK;
3877                        initializeScrollbars = true;
3878                    }
3879                    break;
3880                //noinspection deprecation
3881                case R.styleable.View_fadingEdge:
3882                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3883                        // Ignore the attribute starting with ICS
3884                        break;
3885                    }
3886                    // With builds < ICS, fall through and apply fading edges
3887                case R.styleable.View_requiresFadingEdge:
3888                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3889                    if (fadingEdge != FADING_EDGE_NONE) {
3890                        viewFlagValues |= fadingEdge;
3891                        viewFlagMasks |= FADING_EDGE_MASK;
3892                        initializeFadingEdge(a);
3893                    }
3894                    break;
3895                case R.styleable.View_scrollbarStyle:
3896                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3897                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3898                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3899                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3900                    }
3901                    break;
3902                case R.styleable.View_isScrollContainer:
3903                    setScrollContainer = true;
3904                    if (a.getBoolean(attr, false)) {
3905                        setScrollContainer(true);
3906                    }
3907                    break;
3908                case com.android.internal.R.styleable.View_keepScreenOn:
3909                    if (a.getBoolean(attr, false)) {
3910                        viewFlagValues |= KEEP_SCREEN_ON;
3911                        viewFlagMasks |= KEEP_SCREEN_ON;
3912                    }
3913                    break;
3914                case R.styleable.View_filterTouchesWhenObscured:
3915                    if (a.getBoolean(attr, false)) {
3916                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3917                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3918                    }
3919                    break;
3920                case R.styleable.View_nextFocusLeft:
3921                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3922                    break;
3923                case R.styleable.View_nextFocusRight:
3924                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3925                    break;
3926                case R.styleable.View_nextFocusUp:
3927                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3928                    break;
3929                case R.styleable.View_nextFocusDown:
3930                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3931                    break;
3932                case R.styleable.View_nextFocusForward:
3933                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3934                    break;
3935                case R.styleable.View_minWidth:
3936                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3937                    break;
3938                case R.styleable.View_minHeight:
3939                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3940                    break;
3941                case R.styleable.View_onClick:
3942                    if (context.isRestricted()) {
3943                        throw new IllegalStateException("The android:onClick attribute cannot "
3944                                + "be used within a restricted context");
3945                    }
3946
3947                    final String handlerName = a.getString(attr);
3948                    if (handlerName != null) {
3949                        setOnClickListener(new OnClickListener() {
3950                            private Method mHandler;
3951
3952                            public void onClick(View v) {
3953                                if (mHandler == null) {
3954                                    try {
3955                                        mHandler = getContext().getClass().getMethod(handlerName,
3956                                                View.class);
3957                                    } catch (NoSuchMethodException e) {
3958                                        int id = getId();
3959                                        String idText = id == NO_ID ? "" : " with id '"
3960                                                + getContext().getResources().getResourceEntryName(
3961                                                    id) + "'";
3962                                        throw new IllegalStateException("Could not find a method " +
3963                                                handlerName + "(View) in the activity "
3964                                                + getContext().getClass() + " for onClick handler"
3965                                                + " on view " + View.this.getClass() + idText, e);
3966                                    }
3967                                }
3968
3969                                try {
3970                                    mHandler.invoke(getContext(), View.this);
3971                                } catch (IllegalAccessException e) {
3972                                    throw new IllegalStateException("Could not execute non "
3973                                            + "public method of the activity", e);
3974                                } catch (InvocationTargetException e) {
3975                                    throw new IllegalStateException("Could not execute "
3976                                            + "method of the activity", e);
3977                                }
3978                            }
3979                        });
3980                    }
3981                    break;
3982                case R.styleable.View_overScrollMode:
3983                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3984                    break;
3985                case R.styleable.View_verticalScrollbarPosition:
3986                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3987                    break;
3988                case R.styleable.View_layerType:
3989                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3990                    break;
3991                case R.styleable.View_textDirection:
3992                    // Clear any text direction flag already set
3993                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3994                    // Set the text direction flags depending on the value of the attribute
3995                    final int textDirection = a.getInt(attr, -1);
3996                    if (textDirection != -1) {
3997                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3998                    }
3999                    break;
4000                case R.styleable.View_textAlignment:
4001                    // Clear any text alignment flag already set
4002                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4003                    // Set the text alignment flag depending on the value of the attribute
4004                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4005                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4006                    break;
4007                case R.styleable.View_importantForAccessibility:
4008                    setImportantForAccessibility(a.getInt(attr,
4009                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4010                    break;
4011                case R.styleable.View_accessibilityLiveRegion:
4012                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4013                    break;
4014                case R.styleable.View_viewName:
4015                    setViewName(a.getString(attr));
4016                    break;
4017                case R.styleable.View_nestedScrollingEnabled:
4018                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4019                    break;
4020                case R.styleable.View_stateListAnimator:
4021                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4022                            a.getResourceId(attr, 0)));
4023                    break;
4024            }
4025        }
4026
4027        setOverScrollMode(overScrollMode);
4028
4029        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4030        // the resolved layout direction). Those cached values will be used later during padding
4031        // resolution.
4032        mUserPaddingStart = startPadding;
4033        mUserPaddingEnd = endPadding;
4034
4035        if (background != null) {
4036            setBackground(background);
4037        }
4038
4039        // setBackground above will record that padding is currently provided by the background.
4040        // If we have padding specified via xml, record that here instead and use it.
4041        mLeftPaddingDefined = leftPaddingDefined;
4042        mRightPaddingDefined = rightPaddingDefined;
4043
4044        if (padding >= 0) {
4045            leftPadding = padding;
4046            topPadding = padding;
4047            rightPadding = padding;
4048            bottomPadding = padding;
4049            mUserPaddingLeftInitial = padding;
4050            mUserPaddingRightInitial = padding;
4051        }
4052
4053        if (isRtlCompatibilityMode()) {
4054            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4055            // left / right padding are used if defined (meaning here nothing to do). If they are not
4056            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4057            // start / end and resolve them as left / right (layout direction is not taken into account).
4058            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4059            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4060            // defined.
4061            if (!mLeftPaddingDefined && startPaddingDefined) {
4062                leftPadding = startPadding;
4063            }
4064            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4065            if (!mRightPaddingDefined && endPaddingDefined) {
4066                rightPadding = endPadding;
4067            }
4068            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4069        } else {
4070            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4071            // values defined. Otherwise, left /right values are used.
4072            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4073            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4074            // defined.
4075            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4076
4077            if (mLeftPaddingDefined && !hasRelativePadding) {
4078                mUserPaddingLeftInitial = leftPadding;
4079            }
4080            if (mRightPaddingDefined && !hasRelativePadding) {
4081                mUserPaddingRightInitial = rightPadding;
4082            }
4083        }
4084
4085        internalSetPadding(
4086                mUserPaddingLeftInitial,
4087                topPadding >= 0 ? topPadding : mPaddingTop,
4088                mUserPaddingRightInitial,
4089                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4090
4091        if (viewFlagMasks != 0) {
4092            setFlags(viewFlagValues, viewFlagMasks);
4093        }
4094
4095        if (initializeScrollbars) {
4096            initializeScrollbars(a);
4097        }
4098
4099        a.recycle();
4100
4101        // Needs to be called after mViewFlags is set
4102        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4103            recomputePadding();
4104        }
4105
4106        if (x != 0 || y != 0) {
4107            scrollTo(x, y);
4108        }
4109
4110        if (transformSet) {
4111            setTranslationX(tx);
4112            setTranslationY(ty);
4113            setTranslationZ(tz);
4114            setElevation(elevation);
4115            setRotation(rotation);
4116            setRotationX(rotationX);
4117            setRotationY(rotationY);
4118            setScaleX(sx);
4119            setScaleY(sy);
4120        }
4121
4122        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4123            setScrollContainer(true);
4124        }
4125
4126        computeOpaqueFlags();
4127    }
4128
4129    /**
4130     * Non-public constructor for use in testing
4131     */
4132    View() {
4133        mResources = null;
4134        mRenderNode = RenderNode.create(getClass().getName());
4135    }
4136
4137    public String toString() {
4138        StringBuilder out = new StringBuilder(128);
4139        out.append(getClass().getName());
4140        out.append('{');
4141        out.append(Integer.toHexString(System.identityHashCode(this)));
4142        out.append(' ');
4143        switch (mViewFlags&VISIBILITY_MASK) {
4144            case VISIBLE: out.append('V'); break;
4145            case INVISIBLE: out.append('I'); break;
4146            case GONE: out.append('G'); break;
4147            default: out.append('.'); break;
4148        }
4149        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4150        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4151        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4152        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4153        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4154        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4155        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4156        out.append(' ');
4157        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4158        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4159        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4160        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4161            out.append('p');
4162        } else {
4163            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4164        }
4165        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4166        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4167        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4168        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4169        out.append(' ');
4170        out.append(mLeft);
4171        out.append(',');
4172        out.append(mTop);
4173        out.append('-');
4174        out.append(mRight);
4175        out.append(',');
4176        out.append(mBottom);
4177        final int id = getId();
4178        if (id != NO_ID) {
4179            out.append(" #");
4180            out.append(Integer.toHexString(id));
4181            final Resources r = mResources;
4182            if (Resources.resourceHasPackage(id) && r != null) {
4183                try {
4184                    String pkgname;
4185                    switch (id&0xff000000) {
4186                        case 0x7f000000:
4187                            pkgname="app";
4188                            break;
4189                        case 0x01000000:
4190                            pkgname="android";
4191                            break;
4192                        default:
4193                            pkgname = r.getResourcePackageName(id);
4194                            break;
4195                    }
4196                    String typename = r.getResourceTypeName(id);
4197                    String entryname = r.getResourceEntryName(id);
4198                    out.append(" ");
4199                    out.append(pkgname);
4200                    out.append(":");
4201                    out.append(typename);
4202                    out.append("/");
4203                    out.append(entryname);
4204                } catch (Resources.NotFoundException e) {
4205                }
4206            }
4207        }
4208        out.append("}");
4209        return out.toString();
4210    }
4211
4212    /**
4213     * <p>
4214     * Initializes the fading edges from a given set of styled attributes. This
4215     * method should be called by subclasses that need fading edges and when an
4216     * instance of these subclasses is created programmatically rather than
4217     * being inflated from XML. This method is automatically called when the XML
4218     * is inflated.
4219     * </p>
4220     *
4221     * @param a the styled attributes set to initialize the fading edges from
4222     */
4223    protected void initializeFadingEdge(TypedArray a) {
4224        initScrollCache();
4225
4226        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4227                R.styleable.View_fadingEdgeLength,
4228                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4229    }
4230
4231    /**
4232     * Returns the size of the vertical faded edges used to indicate that more
4233     * content in this view is visible.
4234     *
4235     * @return The size in pixels of the vertical faded edge or 0 if vertical
4236     *         faded edges are not enabled for this view.
4237     * @attr ref android.R.styleable#View_fadingEdgeLength
4238     */
4239    public int getVerticalFadingEdgeLength() {
4240        if (isVerticalFadingEdgeEnabled()) {
4241            ScrollabilityCache cache = mScrollCache;
4242            if (cache != null) {
4243                return cache.fadingEdgeLength;
4244            }
4245        }
4246        return 0;
4247    }
4248
4249    /**
4250     * Set the size of the faded edge used to indicate that more content in this
4251     * view is available.  Will not change whether the fading edge is enabled; use
4252     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4253     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4254     * for the vertical or horizontal fading edges.
4255     *
4256     * @param length The size in pixels of the faded edge used to indicate that more
4257     *        content in this view is visible.
4258     */
4259    public void setFadingEdgeLength(int length) {
4260        initScrollCache();
4261        mScrollCache.fadingEdgeLength = length;
4262    }
4263
4264    /**
4265     * Returns the size of the horizontal faded edges used to indicate that more
4266     * content in this view is visible.
4267     *
4268     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4269     *         faded edges are not enabled for this view.
4270     * @attr ref android.R.styleable#View_fadingEdgeLength
4271     */
4272    public int getHorizontalFadingEdgeLength() {
4273        if (isHorizontalFadingEdgeEnabled()) {
4274            ScrollabilityCache cache = mScrollCache;
4275            if (cache != null) {
4276                return cache.fadingEdgeLength;
4277            }
4278        }
4279        return 0;
4280    }
4281
4282    /**
4283     * Returns the width of the vertical scrollbar.
4284     *
4285     * @return The width in pixels of the vertical scrollbar or 0 if there
4286     *         is no vertical scrollbar.
4287     */
4288    public int getVerticalScrollbarWidth() {
4289        ScrollabilityCache cache = mScrollCache;
4290        if (cache != null) {
4291            ScrollBarDrawable scrollBar = cache.scrollBar;
4292            if (scrollBar != null) {
4293                int size = scrollBar.getSize(true);
4294                if (size <= 0) {
4295                    size = cache.scrollBarSize;
4296                }
4297                return size;
4298            }
4299            return 0;
4300        }
4301        return 0;
4302    }
4303
4304    /**
4305     * Returns the height of the horizontal scrollbar.
4306     *
4307     * @return The height in pixels of the horizontal scrollbar or 0 if
4308     *         there is no horizontal scrollbar.
4309     */
4310    protected int getHorizontalScrollbarHeight() {
4311        ScrollabilityCache cache = mScrollCache;
4312        if (cache != null) {
4313            ScrollBarDrawable scrollBar = cache.scrollBar;
4314            if (scrollBar != null) {
4315                int size = scrollBar.getSize(false);
4316                if (size <= 0) {
4317                    size = cache.scrollBarSize;
4318                }
4319                return size;
4320            }
4321            return 0;
4322        }
4323        return 0;
4324    }
4325
4326    /**
4327     * <p>
4328     * Initializes the scrollbars from a given set of styled attributes. This
4329     * method should be called by subclasses that need scrollbars and when an
4330     * instance of these subclasses is created programmatically rather than
4331     * being inflated from XML. This method is automatically called when the XML
4332     * is inflated.
4333     * </p>
4334     *
4335     * @param a the styled attributes set to initialize the scrollbars from
4336     */
4337    protected void initializeScrollbars(TypedArray a) {
4338        initScrollCache();
4339
4340        final ScrollabilityCache scrollabilityCache = mScrollCache;
4341
4342        if (scrollabilityCache.scrollBar == null) {
4343            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4344        }
4345
4346        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4347
4348        if (!fadeScrollbars) {
4349            scrollabilityCache.state = ScrollabilityCache.ON;
4350        }
4351        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4352
4353
4354        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4355                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4356                        .getScrollBarFadeDuration());
4357        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4358                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4359                ViewConfiguration.getScrollDefaultDelay());
4360
4361
4362        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4363                com.android.internal.R.styleable.View_scrollbarSize,
4364                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4365
4366        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4367        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4368
4369        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4370        if (thumb != null) {
4371            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4372        }
4373
4374        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4375                false);
4376        if (alwaysDraw) {
4377            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4378        }
4379
4380        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4381        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4382
4383        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4384        if (thumb != null) {
4385            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4386        }
4387
4388        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4389                false);
4390        if (alwaysDraw) {
4391            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4392        }
4393
4394        // Apply layout direction to the new Drawables if needed
4395        final int layoutDirection = getLayoutDirection();
4396        if (track != null) {
4397            track.setLayoutDirection(layoutDirection);
4398        }
4399        if (thumb != null) {
4400            thumb.setLayoutDirection(layoutDirection);
4401        }
4402
4403        // Re-apply user/background padding so that scrollbar(s) get added
4404        resolvePadding();
4405    }
4406
4407    /**
4408     * <p>
4409     * Initalizes the scrollability cache if necessary.
4410     * </p>
4411     */
4412    private void initScrollCache() {
4413        if (mScrollCache == null) {
4414            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4415        }
4416    }
4417
4418    private ScrollabilityCache getScrollCache() {
4419        initScrollCache();
4420        return mScrollCache;
4421    }
4422
4423    /**
4424     * Set the position of the vertical scroll bar. Should be one of
4425     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4426     * {@link #SCROLLBAR_POSITION_RIGHT}.
4427     *
4428     * @param position Where the vertical scroll bar should be positioned.
4429     */
4430    public void setVerticalScrollbarPosition(int position) {
4431        if (mVerticalScrollbarPosition != position) {
4432            mVerticalScrollbarPosition = position;
4433            computeOpaqueFlags();
4434            resolvePadding();
4435        }
4436    }
4437
4438    /**
4439     * @return The position where the vertical scroll bar will show, if applicable.
4440     * @see #setVerticalScrollbarPosition(int)
4441     */
4442    public int getVerticalScrollbarPosition() {
4443        return mVerticalScrollbarPosition;
4444    }
4445
4446    ListenerInfo getListenerInfo() {
4447        if (mListenerInfo != null) {
4448            return mListenerInfo;
4449        }
4450        mListenerInfo = new ListenerInfo();
4451        return mListenerInfo;
4452    }
4453
4454    /**
4455     * Register a callback to be invoked when focus of this view changed.
4456     *
4457     * @param l The callback that will run.
4458     */
4459    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4460        getListenerInfo().mOnFocusChangeListener = l;
4461    }
4462
4463    /**
4464     * Add a listener that will be called when the bounds of the view change due to
4465     * layout processing.
4466     *
4467     * @param listener The listener that will be called when layout bounds change.
4468     */
4469    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4470        ListenerInfo li = getListenerInfo();
4471        if (li.mOnLayoutChangeListeners == null) {
4472            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4473        }
4474        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4475            li.mOnLayoutChangeListeners.add(listener);
4476        }
4477    }
4478
4479    /**
4480     * Remove a listener for layout changes.
4481     *
4482     * @param listener The listener for layout bounds change.
4483     */
4484    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4485        ListenerInfo li = mListenerInfo;
4486        if (li == null || li.mOnLayoutChangeListeners == null) {
4487            return;
4488        }
4489        li.mOnLayoutChangeListeners.remove(listener);
4490    }
4491
4492    /**
4493     * Add a listener for attach state changes.
4494     *
4495     * This listener will be called whenever this view is attached or detached
4496     * from a window. Remove the listener using
4497     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4498     *
4499     * @param listener Listener to attach
4500     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4501     */
4502    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4503        ListenerInfo li = getListenerInfo();
4504        if (li.mOnAttachStateChangeListeners == null) {
4505            li.mOnAttachStateChangeListeners
4506                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4507        }
4508        li.mOnAttachStateChangeListeners.add(listener);
4509    }
4510
4511    /**
4512     * Remove a listener for attach state changes. The listener will receive no further
4513     * notification of window attach/detach events.
4514     *
4515     * @param listener Listener to remove
4516     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4517     */
4518    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4519        ListenerInfo li = mListenerInfo;
4520        if (li == null || li.mOnAttachStateChangeListeners == null) {
4521            return;
4522        }
4523        li.mOnAttachStateChangeListeners.remove(listener);
4524    }
4525
4526    /**
4527     * Returns the focus-change callback registered for this view.
4528     *
4529     * @return The callback, or null if one is not registered.
4530     */
4531    public OnFocusChangeListener getOnFocusChangeListener() {
4532        ListenerInfo li = mListenerInfo;
4533        return li != null ? li.mOnFocusChangeListener : null;
4534    }
4535
4536    /**
4537     * Register a callback to be invoked when this view is clicked. If this view is not
4538     * clickable, it becomes clickable.
4539     *
4540     * @param l The callback that will run
4541     *
4542     * @see #setClickable(boolean)
4543     */
4544    public void setOnClickListener(OnClickListener l) {
4545        if (!isClickable()) {
4546            setClickable(true);
4547        }
4548        getListenerInfo().mOnClickListener = l;
4549    }
4550
4551    /**
4552     * Return whether this view has an attached OnClickListener.  Returns
4553     * true if there is a listener, false if there is none.
4554     */
4555    public boolean hasOnClickListeners() {
4556        ListenerInfo li = mListenerInfo;
4557        return (li != null && li.mOnClickListener != null);
4558    }
4559
4560    /**
4561     * Register a callback to be invoked when this view is clicked and held. If this view is not
4562     * long clickable, it becomes long clickable.
4563     *
4564     * @param l The callback that will run
4565     *
4566     * @see #setLongClickable(boolean)
4567     */
4568    public void setOnLongClickListener(OnLongClickListener l) {
4569        if (!isLongClickable()) {
4570            setLongClickable(true);
4571        }
4572        getListenerInfo().mOnLongClickListener = l;
4573    }
4574
4575    /**
4576     * Register a callback to be invoked when the context menu for this view is
4577     * being built. If this view is not long clickable, it becomes long clickable.
4578     *
4579     * @param l The callback that will run
4580     *
4581     */
4582    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4583        if (!isLongClickable()) {
4584            setLongClickable(true);
4585        }
4586        getListenerInfo().mOnCreateContextMenuListener = l;
4587    }
4588
4589    /**
4590     * Call this view's OnClickListener, if it is defined.  Performs all normal
4591     * actions associated with clicking: reporting accessibility event, playing
4592     * a sound, etc.
4593     *
4594     * @return True there was an assigned OnClickListener that was called, false
4595     *         otherwise is returned.
4596     */
4597    public boolean performClick() {
4598        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4599
4600        ListenerInfo li = mListenerInfo;
4601        if (li != null && li.mOnClickListener != null) {
4602            playSoundEffect(SoundEffectConstants.CLICK);
4603            li.mOnClickListener.onClick(this);
4604            return true;
4605        }
4606
4607        return false;
4608    }
4609
4610    /**
4611     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4612     * this only calls the listener, and does not do any associated clicking
4613     * actions like reporting an accessibility event.
4614     *
4615     * @return True there was an assigned OnClickListener that was called, false
4616     *         otherwise is returned.
4617     */
4618    public boolean callOnClick() {
4619        ListenerInfo li = mListenerInfo;
4620        if (li != null && li.mOnClickListener != null) {
4621            li.mOnClickListener.onClick(this);
4622            return true;
4623        }
4624        return false;
4625    }
4626
4627    /**
4628     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4629     * OnLongClickListener did not consume the event.
4630     *
4631     * @return True if one of the above receivers consumed the event, false otherwise.
4632     */
4633    public boolean performLongClick() {
4634        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4635
4636        boolean handled = false;
4637        ListenerInfo li = mListenerInfo;
4638        if (li != null && li.mOnLongClickListener != null) {
4639            handled = li.mOnLongClickListener.onLongClick(View.this);
4640        }
4641        if (!handled) {
4642            handled = showContextMenu();
4643        }
4644        if (handled) {
4645            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4646        }
4647        return handled;
4648    }
4649
4650    /**
4651     * Performs button-related actions during a touch down event.
4652     *
4653     * @param event The event.
4654     * @return True if the down was consumed.
4655     *
4656     * @hide
4657     */
4658    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4659        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4660            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4661                return true;
4662            }
4663        }
4664        return false;
4665    }
4666
4667    /**
4668     * Bring up the context menu for this view.
4669     *
4670     * @return Whether a context menu was displayed.
4671     */
4672    public boolean showContextMenu() {
4673        return getParent().showContextMenuForChild(this);
4674    }
4675
4676    /**
4677     * Bring up the context menu for this view, referring to the item under the specified point.
4678     *
4679     * @param x The referenced x coordinate.
4680     * @param y The referenced y coordinate.
4681     * @param metaState The keyboard modifiers that were pressed.
4682     * @return Whether a context menu was displayed.
4683     *
4684     * @hide
4685     */
4686    public boolean showContextMenu(float x, float y, int metaState) {
4687        return showContextMenu();
4688    }
4689
4690    /**
4691     * Start an action mode.
4692     *
4693     * @param callback Callback that will control the lifecycle of the action mode
4694     * @return The new action mode if it is started, null otherwise
4695     *
4696     * @see ActionMode
4697     */
4698    public ActionMode startActionMode(ActionMode.Callback callback) {
4699        ViewParent parent = getParent();
4700        if (parent == null) return null;
4701        return parent.startActionModeForChild(this, callback);
4702    }
4703
4704    /**
4705     * Register a callback to be invoked when a hardware key is pressed in this view.
4706     * Key presses in software input methods will generally not trigger the methods of
4707     * this listener.
4708     * @param l the key listener to attach to this view
4709     */
4710    public void setOnKeyListener(OnKeyListener l) {
4711        getListenerInfo().mOnKeyListener = l;
4712    }
4713
4714    /**
4715     * Register a callback to be invoked when a touch event is sent to this view.
4716     * @param l the touch listener to attach to this view
4717     */
4718    public void setOnTouchListener(OnTouchListener l) {
4719        getListenerInfo().mOnTouchListener = l;
4720    }
4721
4722    /**
4723     * Register a callback to be invoked when a generic motion event is sent to this view.
4724     * @param l the generic motion listener to attach to this view
4725     */
4726    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4727        getListenerInfo().mOnGenericMotionListener = l;
4728    }
4729
4730    /**
4731     * Register a callback to be invoked when a hover event is sent to this view.
4732     * @param l the hover listener to attach to this view
4733     */
4734    public void setOnHoverListener(OnHoverListener l) {
4735        getListenerInfo().mOnHoverListener = l;
4736    }
4737
4738    /**
4739     * Register a drag event listener callback object for this View. The parameter is
4740     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4741     * View, the system calls the
4742     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4743     * @param l An implementation of {@link android.view.View.OnDragListener}.
4744     */
4745    public void setOnDragListener(OnDragListener l) {
4746        getListenerInfo().mOnDragListener = l;
4747    }
4748
4749    /**
4750     * Give this view focus. This will cause
4751     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4752     *
4753     * Note: this does not check whether this {@link View} should get focus, it just
4754     * gives it focus no matter what.  It should only be called internally by framework
4755     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4756     *
4757     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4758     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4759     *        focus moved when requestFocus() is called. It may not always
4760     *        apply, in which case use the default View.FOCUS_DOWN.
4761     * @param previouslyFocusedRect The rectangle of the view that had focus
4762     *        prior in this View's coordinate system.
4763     */
4764    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4765        if (DBG) {
4766            System.out.println(this + " requestFocus()");
4767        }
4768
4769        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4770            mPrivateFlags |= PFLAG_FOCUSED;
4771
4772            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4773
4774            if (mParent != null) {
4775                mParent.requestChildFocus(this, this);
4776            }
4777
4778            if (mAttachInfo != null) {
4779                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4780            }
4781
4782            onFocusChanged(true, direction, previouslyFocusedRect);
4783            manageFocusHotspot(true, oldFocus);
4784            refreshDrawableState();
4785        }
4786    }
4787
4788    /**
4789     * Forwards focus information to the background drawable, if necessary. When
4790     * the view is gaining focus, <code>v</code> is the previous focus holder.
4791     * When the view is losing focus, <code>v</code> is the next focus holder.
4792     *
4793     * @param focused whether this view is focused
4794     * @param v previous or the next focus holder, or null if none
4795     */
4796    private void manageFocusHotspot(boolean focused, View v) {
4797        if (mBackground == null) {
4798            return;
4799        }
4800
4801        final Rect r = new Rect();
4802        if (!focused && v != null) {
4803            v.getBoundsOnScreen(r);
4804            final int[] location = new int[2];
4805            getLocationOnScreen(location);
4806            r.offset(-location[0], -location[1]);
4807        } else {
4808            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4809        }
4810
4811        final float x = r.exactCenterX();
4812        final float y = r.exactCenterY();
4813        mBackground.setHotspot(x, y);
4814    }
4815
4816    /**
4817     * Request that a rectangle of this view be visible on the screen,
4818     * scrolling if necessary just enough.
4819     *
4820     * <p>A View should call this if it maintains some notion of which part
4821     * of its content is interesting.  For example, a text editing view
4822     * should call this when its cursor moves.
4823     *
4824     * @param rectangle The rectangle.
4825     * @return Whether any parent scrolled.
4826     */
4827    public boolean requestRectangleOnScreen(Rect rectangle) {
4828        return requestRectangleOnScreen(rectangle, false);
4829    }
4830
4831    /**
4832     * Request that a rectangle of this view be visible on the screen,
4833     * scrolling if necessary just enough.
4834     *
4835     * <p>A View should call this if it maintains some notion of which part
4836     * of its content is interesting.  For example, a text editing view
4837     * should call this when its cursor moves.
4838     *
4839     * <p>When <code>immediate</code> is set to true, scrolling will not be
4840     * animated.
4841     *
4842     * @param rectangle The rectangle.
4843     * @param immediate True to forbid animated scrolling, false otherwise
4844     * @return Whether any parent scrolled.
4845     */
4846    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4847        if (mParent == null) {
4848            return false;
4849        }
4850
4851        View child = this;
4852
4853        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4854        position.set(rectangle);
4855
4856        ViewParent parent = mParent;
4857        boolean scrolled = false;
4858        while (parent != null) {
4859            rectangle.set((int) position.left, (int) position.top,
4860                    (int) position.right, (int) position.bottom);
4861
4862            scrolled |= parent.requestChildRectangleOnScreen(child,
4863                    rectangle, immediate);
4864
4865            if (!child.hasIdentityMatrix()) {
4866                child.getMatrix().mapRect(position);
4867            }
4868
4869            position.offset(child.mLeft, child.mTop);
4870
4871            if (!(parent instanceof View)) {
4872                break;
4873            }
4874
4875            View parentView = (View) parent;
4876
4877            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4878
4879            child = parentView;
4880            parent = child.getParent();
4881        }
4882
4883        return scrolled;
4884    }
4885
4886    /**
4887     * Called when this view wants to give up focus. If focus is cleared
4888     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4889     * <p>
4890     * <strong>Note:</strong> When a View clears focus the framework is trying
4891     * to give focus to the first focusable View from the top. Hence, if this
4892     * View is the first from the top that can take focus, then all callbacks
4893     * related to clearing focus will be invoked after wich the framework will
4894     * give focus to this view.
4895     * </p>
4896     */
4897    public void clearFocus() {
4898        if (DBG) {
4899            System.out.println(this + " clearFocus()");
4900        }
4901
4902        clearFocusInternal(null, true, true);
4903    }
4904
4905    /**
4906     * Clears focus from the view, optionally propagating the change up through
4907     * the parent hierarchy and requesting that the root view place new focus.
4908     *
4909     * @param propagate whether to propagate the change up through the parent
4910     *            hierarchy
4911     * @param refocus when propagate is true, specifies whether to request the
4912     *            root view place new focus
4913     */
4914    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4915        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4916            mPrivateFlags &= ~PFLAG_FOCUSED;
4917
4918            if (propagate && mParent != null) {
4919                mParent.clearChildFocus(this);
4920            }
4921
4922            onFocusChanged(false, 0, null);
4923
4924            manageFocusHotspot(false, focused);
4925            refreshDrawableState();
4926
4927            if (propagate && (!refocus || !rootViewRequestFocus())) {
4928                notifyGlobalFocusCleared(this);
4929            }
4930        }
4931    }
4932
4933    void notifyGlobalFocusCleared(View oldFocus) {
4934        if (oldFocus != null && mAttachInfo != null) {
4935            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4936        }
4937    }
4938
4939    boolean rootViewRequestFocus() {
4940        final View root = getRootView();
4941        return root != null && root.requestFocus();
4942    }
4943
4944    /**
4945     * Called internally by the view system when a new view is getting focus.
4946     * This is what clears the old focus.
4947     * <p>
4948     * <b>NOTE:</b> The parent view's focused child must be updated manually
4949     * after calling this method. Otherwise, the view hierarchy may be left in
4950     * an inconstent state.
4951     */
4952    void unFocus(View focused) {
4953        if (DBG) {
4954            System.out.println(this + " unFocus()");
4955        }
4956
4957        clearFocusInternal(focused, false, false);
4958    }
4959
4960    /**
4961     * Returns true if this view has focus iteself, or is the ancestor of the
4962     * view that has focus.
4963     *
4964     * @return True if this view has or contains focus, false otherwise.
4965     */
4966    @ViewDebug.ExportedProperty(category = "focus")
4967    public boolean hasFocus() {
4968        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4969    }
4970
4971    /**
4972     * Returns true if this view is focusable or if it contains a reachable View
4973     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4974     * is a View whose parents do not block descendants focus.
4975     *
4976     * Only {@link #VISIBLE} views are considered focusable.
4977     *
4978     * @return True if the view is focusable or if the view contains a focusable
4979     *         View, false otherwise.
4980     *
4981     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4982     */
4983    public boolean hasFocusable() {
4984        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4985    }
4986
4987    /**
4988     * Called by the view system when the focus state of this view changes.
4989     * When the focus change event is caused by directional navigation, direction
4990     * and previouslyFocusedRect provide insight into where the focus is coming from.
4991     * When overriding, be sure to call up through to the super class so that
4992     * the standard focus handling will occur.
4993     *
4994     * @param gainFocus True if the View has focus; false otherwise.
4995     * @param direction The direction focus has moved when requestFocus()
4996     *                  is called to give this view focus. Values are
4997     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4998     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4999     *                  It may not always apply, in which case use the default.
5000     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5001     *        system, of the previously focused view.  If applicable, this will be
5002     *        passed in as finer grained information about where the focus is coming
5003     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5004     */
5005    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5006            @Nullable Rect previouslyFocusedRect) {
5007        if (gainFocus) {
5008            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5009        } else {
5010            notifyViewAccessibilityStateChangedIfNeeded(
5011                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5012        }
5013
5014        InputMethodManager imm = InputMethodManager.peekInstance();
5015        if (!gainFocus) {
5016            if (isPressed()) {
5017                setPressed(false);
5018            }
5019            if (imm != null && mAttachInfo != null
5020                    && mAttachInfo.mHasWindowFocus) {
5021                imm.focusOut(this);
5022            }
5023            onFocusLost();
5024        } else if (imm != null && mAttachInfo != null
5025                && mAttachInfo.mHasWindowFocus) {
5026            imm.focusIn(this);
5027        }
5028
5029        invalidate(true);
5030        ListenerInfo li = mListenerInfo;
5031        if (li != null && li.mOnFocusChangeListener != null) {
5032            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5033        }
5034
5035        if (mAttachInfo != null) {
5036            mAttachInfo.mKeyDispatchState.reset(this);
5037        }
5038    }
5039
5040    /**
5041     * Sends an accessibility event of the given type. If accessibility is
5042     * not enabled this method has no effect. The default implementation calls
5043     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5044     * to populate information about the event source (this View), then calls
5045     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5046     * populate the text content of the event source including its descendants,
5047     * and last calls
5048     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5049     * on its parent to resuest sending of the event to interested parties.
5050     * <p>
5051     * If an {@link AccessibilityDelegate} has been specified via calling
5052     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5053     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5054     * responsible for handling this call.
5055     * </p>
5056     *
5057     * @param eventType The type of the event to send, as defined by several types from
5058     * {@link android.view.accessibility.AccessibilityEvent}, such as
5059     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5060     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5061     *
5062     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5063     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5064     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5065     * @see AccessibilityDelegate
5066     */
5067    public void sendAccessibilityEvent(int eventType) {
5068        if (mAccessibilityDelegate != null) {
5069            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5070        } else {
5071            sendAccessibilityEventInternal(eventType);
5072        }
5073    }
5074
5075    /**
5076     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5077     * {@link AccessibilityEvent} to make an announcement which is related to some
5078     * sort of a context change for which none of the events representing UI transitions
5079     * is a good fit. For example, announcing a new page in a book. If accessibility
5080     * is not enabled this method does nothing.
5081     *
5082     * @param text The announcement text.
5083     */
5084    public void announceForAccessibility(CharSequence text) {
5085        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5086            AccessibilityEvent event = AccessibilityEvent.obtain(
5087                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5088            onInitializeAccessibilityEvent(event);
5089            event.getText().add(text);
5090            event.setContentDescription(null);
5091            mParent.requestSendAccessibilityEvent(this, event);
5092        }
5093    }
5094
5095    /**
5096     * @see #sendAccessibilityEvent(int)
5097     *
5098     * Note: Called from the default {@link AccessibilityDelegate}.
5099     */
5100    void sendAccessibilityEventInternal(int eventType) {
5101        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5102            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5103        }
5104    }
5105
5106    /**
5107     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5108     * takes as an argument an empty {@link AccessibilityEvent} and does not
5109     * perform a check whether accessibility is enabled.
5110     * <p>
5111     * If an {@link AccessibilityDelegate} has been specified via calling
5112     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5113     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5114     * is responsible for handling this call.
5115     * </p>
5116     *
5117     * @param event The event to send.
5118     *
5119     * @see #sendAccessibilityEvent(int)
5120     */
5121    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5122        if (mAccessibilityDelegate != null) {
5123            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5124        } else {
5125            sendAccessibilityEventUncheckedInternal(event);
5126        }
5127    }
5128
5129    /**
5130     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5131     *
5132     * Note: Called from the default {@link AccessibilityDelegate}.
5133     */
5134    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5135        if (!isShown()) {
5136            return;
5137        }
5138        onInitializeAccessibilityEvent(event);
5139        // Only a subset of accessibility events populates text content.
5140        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5141            dispatchPopulateAccessibilityEvent(event);
5142        }
5143        // In the beginning we called #isShown(), so we know that getParent() is not null.
5144        getParent().requestSendAccessibilityEvent(this, event);
5145    }
5146
5147    /**
5148     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5149     * to its children for adding their text content to the event. Note that the
5150     * event text is populated in a separate dispatch path since we add to the
5151     * event not only the text of the source but also the text of all its descendants.
5152     * A typical implementation will call
5153     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5154     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5155     * on each child. Override this method if custom population of the event text
5156     * content is required.
5157     * <p>
5158     * If an {@link AccessibilityDelegate} has been specified via calling
5159     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5160     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5161     * is responsible for handling this call.
5162     * </p>
5163     * <p>
5164     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5165     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5166     * </p>
5167     *
5168     * @param event The event.
5169     *
5170     * @return True if the event population was completed.
5171     */
5172    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5173        if (mAccessibilityDelegate != null) {
5174            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5175        } else {
5176            return dispatchPopulateAccessibilityEventInternal(event);
5177        }
5178    }
5179
5180    /**
5181     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5182     *
5183     * Note: Called from the default {@link AccessibilityDelegate}.
5184     */
5185    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5186        onPopulateAccessibilityEvent(event);
5187        return false;
5188    }
5189
5190    /**
5191     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5192     * giving a chance to this View to populate the accessibility event with its
5193     * text content. While this method is free to modify event
5194     * attributes other than text content, doing so should normally be performed in
5195     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5196     * <p>
5197     * Example: Adding formatted date string to an accessibility event in addition
5198     *          to the text added by the super implementation:
5199     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5200     *     super.onPopulateAccessibilityEvent(event);
5201     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5202     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5203     *         mCurrentDate.getTimeInMillis(), flags);
5204     *     event.getText().add(selectedDateUtterance);
5205     * }</pre>
5206     * <p>
5207     * If an {@link AccessibilityDelegate} has been specified via calling
5208     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5209     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5210     * is responsible for handling this call.
5211     * </p>
5212     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5213     * information to the event, in case the default implementation has basic information to add.
5214     * </p>
5215     *
5216     * @param event The accessibility event which to populate.
5217     *
5218     * @see #sendAccessibilityEvent(int)
5219     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5220     */
5221    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5222        if (mAccessibilityDelegate != null) {
5223            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5224        } else {
5225            onPopulateAccessibilityEventInternal(event);
5226        }
5227    }
5228
5229    /**
5230     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5231     *
5232     * Note: Called from the default {@link AccessibilityDelegate}.
5233     */
5234    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5235    }
5236
5237    /**
5238     * Initializes an {@link AccessibilityEvent} with information about
5239     * this View which is the event source. In other words, the source of
5240     * an accessibility event is the view whose state change triggered firing
5241     * the event.
5242     * <p>
5243     * Example: Setting the password property of an event in addition
5244     *          to properties set by the super implementation:
5245     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5246     *     super.onInitializeAccessibilityEvent(event);
5247     *     event.setPassword(true);
5248     * }</pre>
5249     * <p>
5250     * If an {@link AccessibilityDelegate} has been specified via calling
5251     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5252     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5253     * is responsible for handling this call.
5254     * </p>
5255     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5256     * information to the event, in case the default implementation has basic information to add.
5257     * </p>
5258     * @param event The event to initialize.
5259     *
5260     * @see #sendAccessibilityEvent(int)
5261     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5262     */
5263    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5264        if (mAccessibilityDelegate != null) {
5265            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5266        } else {
5267            onInitializeAccessibilityEventInternal(event);
5268        }
5269    }
5270
5271    /**
5272     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5273     *
5274     * Note: Called from the default {@link AccessibilityDelegate}.
5275     */
5276    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5277        event.setSource(this);
5278        event.setClassName(View.class.getName());
5279        event.setPackageName(getContext().getPackageName());
5280        event.setEnabled(isEnabled());
5281        event.setContentDescription(mContentDescription);
5282
5283        switch (event.getEventType()) {
5284            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5285                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5286                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5287                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5288                event.setItemCount(focusablesTempList.size());
5289                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5290                if (mAttachInfo != null) {
5291                    focusablesTempList.clear();
5292                }
5293            } break;
5294            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5295                CharSequence text = getIterableTextForAccessibility();
5296                if (text != null && text.length() > 0) {
5297                    event.setFromIndex(getAccessibilitySelectionStart());
5298                    event.setToIndex(getAccessibilitySelectionEnd());
5299                    event.setItemCount(text.length());
5300                }
5301            } break;
5302        }
5303    }
5304
5305    /**
5306     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5307     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5308     * This method is responsible for obtaining an accessibility node info from a
5309     * pool of reusable instances and calling
5310     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5311     * initialize the former.
5312     * <p>
5313     * Note: The client is responsible for recycling the obtained instance by calling
5314     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5315     * </p>
5316     *
5317     * @return A populated {@link AccessibilityNodeInfo}.
5318     *
5319     * @see AccessibilityNodeInfo
5320     */
5321    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5322        if (mAccessibilityDelegate != null) {
5323            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5324        } else {
5325            return createAccessibilityNodeInfoInternal();
5326        }
5327    }
5328
5329    /**
5330     * @see #createAccessibilityNodeInfo()
5331     */
5332    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5333        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5334        if (provider != null) {
5335            return provider.createAccessibilityNodeInfo(View.NO_ID);
5336        } else {
5337            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5338            onInitializeAccessibilityNodeInfo(info);
5339            return info;
5340        }
5341    }
5342
5343    /**
5344     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5345     * The base implementation sets:
5346     * <ul>
5347     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5348     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5349     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5350     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5351     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5352     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5353     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5354     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5355     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5356     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5357     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5358     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5359     * </ul>
5360     * <p>
5361     * Subclasses should override this method, call the super implementation,
5362     * and set additional attributes.
5363     * </p>
5364     * <p>
5365     * If an {@link AccessibilityDelegate} has been specified via calling
5366     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5367     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5368     * is responsible for handling this call.
5369     * </p>
5370     *
5371     * @param info The instance to initialize.
5372     */
5373    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5374        if (mAccessibilityDelegate != null) {
5375            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5376        } else {
5377            onInitializeAccessibilityNodeInfoInternal(info);
5378        }
5379    }
5380
5381    /**
5382     * Gets the location of this view in screen coordintates.
5383     *
5384     * @param outRect The output location
5385     * @hide
5386     */
5387    public void getBoundsOnScreen(Rect outRect) {
5388        if (mAttachInfo == null) {
5389            return;
5390        }
5391
5392        RectF position = mAttachInfo.mTmpTransformRect;
5393        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5394
5395        if (!hasIdentityMatrix()) {
5396            getMatrix().mapRect(position);
5397        }
5398
5399        position.offset(mLeft, mTop);
5400
5401        ViewParent parent = mParent;
5402        while (parent instanceof View) {
5403            View parentView = (View) parent;
5404
5405            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5406
5407            if (!parentView.hasIdentityMatrix()) {
5408                parentView.getMatrix().mapRect(position);
5409            }
5410
5411            position.offset(parentView.mLeft, parentView.mTop);
5412
5413            parent = parentView.mParent;
5414        }
5415
5416        if (parent instanceof ViewRootImpl) {
5417            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5418            position.offset(0, -viewRootImpl.mCurScrollY);
5419        }
5420
5421        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5422
5423        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5424                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5425    }
5426
5427    /**
5428     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5429     *
5430     * Note: Called from the default {@link AccessibilityDelegate}.
5431     */
5432    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5433        Rect bounds = mAttachInfo.mTmpInvalRect;
5434
5435        getDrawingRect(bounds);
5436        info.setBoundsInParent(bounds);
5437
5438        getBoundsOnScreen(bounds);
5439        info.setBoundsInScreen(bounds);
5440
5441        ViewParent parent = getParentForAccessibility();
5442        if (parent instanceof View) {
5443            info.setParent((View) parent);
5444        }
5445
5446        if (mID != View.NO_ID) {
5447            View rootView = getRootView();
5448            if (rootView == null) {
5449                rootView = this;
5450            }
5451            View label = rootView.findLabelForView(this, mID);
5452            if (label != null) {
5453                info.setLabeledBy(label);
5454            }
5455
5456            if ((mAttachInfo.mAccessibilityFetchFlags
5457                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5458                    && Resources.resourceHasPackage(mID)) {
5459                try {
5460                    String viewId = getResources().getResourceName(mID);
5461                    info.setViewIdResourceName(viewId);
5462                } catch (Resources.NotFoundException nfe) {
5463                    /* ignore */
5464                }
5465            }
5466        }
5467
5468        if (mLabelForId != View.NO_ID) {
5469            View rootView = getRootView();
5470            if (rootView == null) {
5471                rootView = this;
5472            }
5473            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5474            if (labeled != null) {
5475                info.setLabelFor(labeled);
5476            }
5477        }
5478
5479        info.setVisibleToUser(isVisibleToUser());
5480
5481        info.setPackageName(mContext.getPackageName());
5482        info.setClassName(View.class.getName());
5483        info.setContentDescription(getContentDescription());
5484
5485        info.setEnabled(isEnabled());
5486        info.setClickable(isClickable());
5487        info.setFocusable(isFocusable());
5488        info.setFocused(isFocused());
5489        info.setAccessibilityFocused(isAccessibilityFocused());
5490        info.setSelected(isSelected());
5491        info.setLongClickable(isLongClickable());
5492        info.setLiveRegion(getAccessibilityLiveRegion());
5493
5494        // TODO: These make sense only if we are in an AdapterView but all
5495        // views can be selected. Maybe from accessibility perspective
5496        // we should report as selectable view in an AdapterView.
5497        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5498        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5499
5500        if (isFocusable()) {
5501            if (isFocused()) {
5502                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5503            } else {
5504                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5505            }
5506        }
5507
5508        if (!isAccessibilityFocused()) {
5509            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5510        } else {
5511            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5512        }
5513
5514        if (isClickable() && isEnabled()) {
5515            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5516        }
5517
5518        if (isLongClickable() && isEnabled()) {
5519            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5520        }
5521
5522        CharSequence text = getIterableTextForAccessibility();
5523        if (text != null && text.length() > 0) {
5524            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5525
5526            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5527            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5528            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5529            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5530                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5531                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5532        }
5533    }
5534
5535    private View findLabelForView(View view, int labeledId) {
5536        if (mMatchLabelForPredicate == null) {
5537            mMatchLabelForPredicate = new MatchLabelForPredicate();
5538        }
5539        mMatchLabelForPredicate.mLabeledId = labeledId;
5540        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5541    }
5542
5543    /**
5544     * Computes whether this view is visible to the user. Such a view is
5545     * attached, visible, all its predecessors are visible, it is not clipped
5546     * entirely by its predecessors, and has an alpha greater than zero.
5547     *
5548     * @return Whether the view is visible on the screen.
5549     *
5550     * @hide
5551     */
5552    protected boolean isVisibleToUser() {
5553        return isVisibleToUser(null);
5554    }
5555
5556    /**
5557     * Computes whether the given portion of this view is visible to the user.
5558     * Such a view is attached, visible, all its predecessors are visible,
5559     * has an alpha greater than zero, and the specified portion is not
5560     * clipped entirely by its predecessors.
5561     *
5562     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5563     *                    <code>null</code>, and the entire view will be tested in this case.
5564     *                    When <code>true</code> is returned by the function, the actual visible
5565     *                    region will be stored in this parameter; that is, if boundInView is fully
5566     *                    contained within the view, no modification will be made, otherwise regions
5567     *                    outside of the visible area of the view will be clipped.
5568     *
5569     * @return Whether the specified portion of the view is visible on the screen.
5570     *
5571     * @hide
5572     */
5573    protected boolean isVisibleToUser(Rect boundInView) {
5574        if (mAttachInfo != null) {
5575            // Attached to invisible window means this view is not visible.
5576            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5577                return false;
5578            }
5579            // An invisible predecessor or one with alpha zero means
5580            // that this view is not visible to the user.
5581            Object current = this;
5582            while (current instanceof View) {
5583                View view = (View) current;
5584                // We have attach info so this view is attached and there is no
5585                // need to check whether we reach to ViewRootImpl on the way up.
5586                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5587                        view.getVisibility() != VISIBLE) {
5588                    return false;
5589                }
5590                current = view.mParent;
5591            }
5592            // Check if the view is entirely covered by its predecessors.
5593            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5594            Point offset = mAttachInfo.mPoint;
5595            if (!getGlobalVisibleRect(visibleRect, offset)) {
5596                return false;
5597            }
5598            // Check if the visible portion intersects the rectangle of interest.
5599            if (boundInView != null) {
5600                visibleRect.offset(-offset.x, -offset.y);
5601                return boundInView.intersect(visibleRect);
5602            }
5603            return true;
5604        }
5605        return false;
5606    }
5607
5608    /**
5609     * Returns the delegate for implementing accessibility support via
5610     * composition. For more details see {@link AccessibilityDelegate}.
5611     *
5612     * @return The delegate, or null if none set.
5613     *
5614     * @hide
5615     */
5616    public AccessibilityDelegate getAccessibilityDelegate() {
5617        return mAccessibilityDelegate;
5618    }
5619
5620    /**
5621     * Sets a delegate for implementing accessibility support via composition as
5622     * opposed to inheritance. The delegate's primary use is for implementing
5623     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5624     *
5625     * @param delegate The delegate instance.
5626     *
5627     * @see AccessibilityDelegate
5628     */
5629    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5630        mAccessibilityDelegate = delegate;
5631    }
5632
5633    /**
5634     * Gets the provider for managing a virtual view hierarchy rooted at this View
5635     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5636     * that explore the window content.
5637     * <p>
5638     * If this method returns an instance, this instance is responsible for managing
5639     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5640     * View including the one representing the View itself. Similarly the returned
5641     * instance is responsible for performing accessibility actions on any virtual
5642     * view or the root view itself.
5643     * </p>
5644     * <p>
5645     * If an {@link AccessibilityDelegate} has been specified via calling
5646     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5647     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5648     * is responsible for handling this call.
5649     * </p>
5650     *
5651     * @return The provider.
5652     *
5653     * @see AccessibilityNodeProvider
5654     */
5655    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5656        if (mAccessibilityDelegate != null) {
5657            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5658        } else {
5659            return null;
5660        }
5661    }
5662
5663    /**
5664     * Gets the unique identifier of this view on the screen for accessibility purposes.
5665     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5666     *
5667     * @return The view accessibility id.
5668     *
5669     * @hide
5670     */
5671    public int getAccessibilityViewId() {
5672        if (mAccessibilityViewId == NO_ID) {
5673            mAccessibilityViewId = sNextAccessibilityViewId++;
5674        }
5675        return mAccessibilityViewId;
5676    }
5677
5678    /**
5679     * Gets the unique identifier of the window in which this View reseides.
5680     *
5681     * @return The window accessibility id.
5682     *
5683     * @hide
5684     */
5685    public int getAccessibilityWindowId() {
5686        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5687                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5688    }
5689
5690    /**
5691     * Gets the {@link View} description. It briefly describes the view and is
5692     * primarily used for accessibility support. Set this property to enable
5693     * better accessibility support for your application. This is especially
5694     * true for views that do not have textual representation (For example,
5695     * ImageButton).
5696     *
5697     * @return The content description.
5698     *
5699     * @attr ref android.R.styleable#View_contentDescription
5700     */
5701    @ViewDebug.ExportedProperty(category = "accessibility")
5702    public CharSequence getContentDescription() {
5703        return mContentDescription;
5704    }
5705
5706    /**
5707     * Sets the {@link View} description. It briefly describes the view and is
5708     * primarily used for accessibility support. Set this property to enable
5709     * better accessibility support for your application. This is especially
5710     * true for views that do not have textual representation (For example,
5711     * ImageButton).
5712     *
5713     * @param contentDescription The content description.
5714     *
5715     * @attr ref android.R.styleable#View_contentDescription
5716     */
5717    @RemotableViewMethod
5718    public void setContentDescription(CharSequence contentDescription) {
5719        if (mContentDescription == null) {
5720            if (contentDescription == null) {
5721                return;
5722            }
5723        } else if (mContentDescription.equals(contentDescription)) {
5724            return;
5725        }
5726        mContentDescription = contentDescription;
5727        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5728        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5729            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5730            notifySubtreeAccessibilityStateChangedIfNeeded();
5731        } else {
5732            notifyViewAccessibilityStateChangedIfNeeded(
5733                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5734        }
5735    }
5736
5737    /**
5738     * Gets the id of a view for which this view serves as a label for
5739     * accessibility purposes.
5740     *
5741     * @return The labeled view id.
5742     */
5743    @ViewDebug.ExportedProperty(category = "accessibility")
5744    public int getLabelFor() {
5745        return mLabelForId;
5746    }
5747
5748    /**
5749     * Sets the id of a view for which this view serves as a label for
5750     * accessibility purposes.
5751     *
5752     * @param id The labeled view id.
5753     */
5754    @RemotableViewMethod
5755    public void setLabelFor(int id) {
5756        mLabelForId = id;
5757        if (mLabelForId != View.NO_ID
5758                && mID == View.NO_ID) {
5759            mID = generateViewId();
5760        }
5761    }
5762
5763    /**
5764     * Invoked whenever this view loses focus, either by losing window focus or by losing
5765     * focus within its window. This method can be used to clear any state tied to the
5766     * focus. For instance, if a button is held pressed with the trackball and the window
5767     * loses focus, this method can be used to cancel the press.
5768     *
5769     * Subclasses of View overriding this method should always call super.onFocusLost().
5770     *
5771     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5772     * @see #onWindowFocusChanged(boolean)
5773     *
5774     * @hide pending API council approval
5775     */
5776    protected void onFocusLost() {
5777        resetPressedState();
5778    }
5779
5780    private void resetPressedState() {
5781        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5782            return;
5783        }
5784
5785        if (isPressed()) {
5786            setPressed(false);
5787
5788            if (!mHasPerformedLongPress) {
5789                removeLongPressCallback();
5790            }
5791        }
5792    }
5793
5794    /**
5795     * Returns true if this view has focus
5796     *
5797     * @return True if this view has focus, false otherwise.
5798     */
5799    @ViewDebug.ExportedProperty(category = "focus")
5800    public boolean isFocused() {
5801        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5802    }
5803
5804    /**
5805     * Find the view in the hierarchy rooted at this view that currently has
5806     * focus.
5807     *
5808     * @return The view that currently has focus, or null if no focused view can
5809     *         be found.
5810     */
5811    public View findFocus() {
5812        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5813    }
5814
5815    /**
5816     * Indicates whether this view is one of the set of scrollable containers in
5817     * its window.
5818     *
5819     * @return whether this view is one of the set of scrollable containers in
5820     * its window
5821     *
5822     * @attr ref android.R.styleable#View_isScrollContainer
5823     */
5824    public boolean isScrollContainer() {
5825        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5826    }
5827
5828    /**
5829     * Change whether this view is one of the set of scrollable containers in
5830     * its window.  This will be used to determine whether the window can
5831     * resize or must pan when a soft input area is open -- scrollable
5832     * containers allow the window to use resize mode since the container
5833     * will appropriately shrink.
5834     *
5835     * @attr ref android.R.styleable#View_isScrollContainer
5836     */
5837    public void setScrollContainer(boolean isScrollContainer) {
5838        if (isScrollContainer) {
5839            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5840                mAttachInfo.mScrollContainers.add(this);
5841                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5842            }
5843            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5844        } else {
5845            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5846                mAttachInfo.mScrollContainers.remove(this);
5847            }
5848            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5849        }
5850    }
5851
5852    /**
5853     * Returns the quality of the drawing cache.
5854     *
5855     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5856     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5857     *
5858     * @see #setDrawingCacheQuality(int)
5859     * @see #setDrawingCacheEnabled(boolean)
5860     * @see #isDrawingCacheEnabled()
5861     *
5862     * @attr ref android.R.styleable#View_drawingCacheQuality
5863     */
5864    @DrawingCacheQuality
5865    public int getDrawingCacheQuality() {
5866        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5867    }
5868
5869    /**
5870     * Set the drawing cache quality of this view. This value is used only when the
5871     * drawing cache is enabled
5872     *
5873     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5874     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5875     *
5876     * @see #getDrawingCacheQuality()
5877     * @see #setDrawingCacheEnabled(boolean)
5878     * @see #isDrawingCacheEnabled()
5879     *
5880     * @attr ref android.R.styleable#View_drawingCacheQuality
5881     */
5882    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5883        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5884    }
5885
5886    /**
5887     * Returns whether the screen should remain on, corresponding to the current
5888     * value of {@link #KEEP_SCREEN_ON}.
5889     *
5890     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5891     *
5892     * @see #setKeepScreenOn(boolean)
5893     *
5894     * @attr ref android.R.styleable#View_keepScreenOn
5895     */
5896    public boolean getKeepScreenOn() {
5897        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5898    }
5899
5900    /**
5901     * Controls whether the screen should remain on, modifying the
5902     * value of {@link #KEEP_SCREEN_ON}.
5903     *
5904     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5905     *
5906     * @see #getKeepScreenOn()
5907     *
5908     * @attr ref android.R.styleable#View_keepScreenOn
5909     */
5910    public void setKeepScreenOn(boolean keepScreenOn) {
5911        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5912    }
5913
5914    /**
5915     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5916     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5917     *
5918     * @attr ref android.R.styleable#View_nextFocusLeft
5919     */
5920    public int getNextFocusLeftId() {
5921        return mNextFocusLeftId;
5922    }
5923
5924    /**
5925     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5926     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5927     * decide automatically.
5928     *
5929     * @attr ref android.R.styleable#View_nextFocusLeft
5930     */
5931    public void setNextFocusLeftId(int nextFocusLeftId) {
5932        mNextFocusLeftId = nextFocusLeftId;
5933    }
5934
5935    /**
5936     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5937     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5938     *
5939     * @attr ref android.R.styleable#View_nextFocusRight
5940     */
5941    public int getNextFocusRightId() {
5942        return mNextFocusRightId;
5943    }
5944
5945    /**
5946     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5947     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5948     * decide automatically.
5949     *
5950     * @attr ref android.R.styleable#View_nextFocusRight
5951     */
5952    public void setNextFocusRightId(int nextFocusRightId) {
5953        mNextFocusRightId = nextFocusRightId;
5954    }
5955
5956    /**
5957     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5958     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5959     *
5960     * @attr ref android.R.styleable#View_nextFocusUp
5961     */
5962    public int getNextFocusUpId() {
5963        return mNextFocusUpId;
5964    }
5965
5966    /**
5967     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5968     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5969     * decide automatically.
5970     *
5971     * @attr ref android.R.styleable#View_nextFocusUp
5972     */
5973    public void setNextFocusUpId(int nextFocusUpId) {
5974        mNextFocusUpId = nextFocusUpId;
5975    }
5976
5977    /**
5978     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5979     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5980     *
5981     * @attr ref android.R.styleable#View_nextFocusDown
5982     */
5983    public int getNextFocusDownId() {
5984        return mNextFocusDownId;
5985    }
5986
5987    /**
5988     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5989     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5990     * decide automatically.
5991     *
5992     * @attr ref android.R.styleable#View_nextFocusDown
5993     */
5994    public void setNextFocusDownId(int nextFocusDownId) {
5995        mNextFocusDownId = nextFocusDownId;
5996    }
5997
5998    /**
5999     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6000     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6001     *
6002     * @attr ref android.R.styleable#View_nextFocusForward
6003     */
6004    public int getNextFocusForwardId() {
6005        return mNextFocusForwardId;
6006    }
6007
6008    /**
6009     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6010     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6011     * decide automatically.
6012     *
6013     * @attr ref android.R.styleable#View_nextFocusForward
6014     */
6015    public void setNextFocusForwardId(int nextFocusForwardId) {
6016        mNextFocusForwardId = nextFocusForwardId;
6017    }
6018
6019    /**
6020     * Returns the visibility of this view and all of its ancestors
6021     *
6022     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6023     */
6024    public boolean isShown() {
6025        View current = this;
6026        //noinspection ConstantConditions
6027        do {
6028            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6029                return false;
6030            }
6031            ViewParent parent = current.mParent;
6032            if (parent == null) {
6033                return false; // We are not attached to the view root
6034            }
6035            if (!(parent instanceof View)) {
6036                return true;
6037            }
6038            current = (View) parent;
6039        } while (current != null);
6040
6041        return false;
6042    }
6043
6044    /**
6045     * Called by the view hierarchy when the content insets for a window have
6046     * changed, to allow it to adjust its content to fit within those windows.
6047     * The content insets tell you the space that the status bar, input method,
6048     * and other system windows infringe on the application's window.
6049     *
6050     * <p>You do not normally need to deal with this function, since the default
6051     * window decoration given to applications takes care of applying it to the
6052     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6053     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6054     * and your content can be placed under those system elements.  You can then
6055     * use this method within your view hierarchy if you have parts of your UI
6056     * which you would like to ensure are not being covered.
6057     *
6058     * <p>The default implementation of this method simply applies the content
6059     * insets to the view's padding, consuming that content (modifying the
6060     * insets to be 0), and returning true.  This behavior is off by default, but can
6061     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6062     *
6063     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6064     * insets object is propagated down the hierarchy, so any changes made to it will
6065     * be seen by all following views (including potentially ones above in
6066     * the hierarchy since this is a depth-first traversal).  The first view
6067     * that returns true will abort the entire traversal.
6068     *
6069     * <p>The default implementation works well for a situation where it is
6070     * used with a container that covers the entire window, allowing it to
6071     * apply the appropriate insets to its content on all edges.  If you need
6072     * a more complicated layout (such as two different views fitting system
6073     * windows, one on the top of the window, and one on the bottom),
6074     * you can override the method and handle the insets however you would like.
6075     * Note that the insets provided by the framework are always relative to the
6076     * far edges of the window, not accounting for the location of the called view
6077     * within that window.  (In fact when this method is called you do not yet know
6078     * where the layout will place the view, as it is done before layout happens.)
6079     *
6080     * <p>Note: unlike many View methods, there is no dispatch phase to this
6081     * call.  If you are overriding it in a ViewGroup and want to allow the
6082     * call to continue to your children, you must be sure to call the super
6083     * implementation.
6084     *
6085     * <p>Here is a sample layout that makes use of fitting system windows
6086     * to have controls for a video view placed inside of the window decorations
6087     * that it hides and shows.  This can be used with code like the second
6088     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6089     *
6090     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6091     *
6092     * @param insets Current content insets of the window.  Prior to
6093     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6094     * the insets or else you and Android will be unhappy.
6095     *
6096     * @return {@code true} if this view applied the insets and it should not
6097     * continue propagating further down the hierarchy, {@code false} otherwise.
6098     * @see #getFitsSystemWindows()
6099     * @see #setFitsSystemWindows(boolean)
6100     * @see #setSystemUiVisibility(int)
6101     *
6102     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6103     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6104     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6105     * to implement handling their own insets.
6106     */
6107    protected boolean fitSystemWindows(Rect insets) {
6108        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6109            // If we're not in the process of dispatching the newer apply insets call,
6110            // that means we're not in the compatibility path. Dispatch into the newer
6111            // apply insets path and take things from there.
6112            try {
6113                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6114                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6115            } finally {
6116                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6117            }
6118        } else {
6119            // We're being called from the newer apply insets path.
6120            // Perform the standard fallback behavior.
6121            return fitSystemWindowsInt(insets);
6122        }
6123    }
6124
6125    private boolean fitSystemWindowsInt(Rect insets) {
6126        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6127            mUserPaddingStart = UNDEFINED_PADDING;
6128            mUserPaddingEnd = UNDEFINED_PADDING;
6129            Rect localInsets = sThreadLocal.get();
6130            if (localInsets == null) {
6131                localInsets = new Rect();
6132                sThreadLocal.set(localInsets);
6133            }
6134            boolean res = computeFitSystemWindows(insets, localInsets);
6135            mUserPaddingLeftInitial = localInsets.left;
6136            mUserPaddingRightInitial = localInsets.right;
6137            internalSetPadding(localInsets.left, localInsets.top,
6138                    localInsets.right, localInsets.bottom);
6139            return res;
6140        }
6141        return false;
6142    }
6143
6144    /**
6145     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6146     *
6147     * <p>This method should be overridden by views that wish to apply a policy different from or
6148     * in addition to the default behavior. Clients that wish to force a view subtree
6149     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6150     *
6151     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6152     * it will be called during dispatch instead of this method. The listener may optionally
6153     * call this method from its own implementation if it wishes to apply the view's default
6154     * insets policy in addition to its own.</p>
6155     *
6156     * <p>Implementations of this method should either return the insets parameter unchanged
6157     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6158     * that this view applied itself. This allows new inset types added in future platform
6159     * versions to pass through existing implementations unchanged without being erroneously
6160     * consumed.</p>
6161     *
6162     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6163     * property is set then the view will consume the system window insets and apply them
6164     * as padding for the view.</p>
6165     *
6166     * @param insets Insets to apply
6167     * @return The supplied insets with any applied insets consumed
6168     */
6169    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6170        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6171            // We weren't called from within a direct call to fitSystemWindows,
6172            // call into it as a fallback in case we're in a class that overrides it
6173            // and has logic to perform.
6174            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6175                return insets.consumeSystemWindowInsets();
6176            }
6177        } else {
6178            // We were called from within a direct call to fitSystemWindows.
6179            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6180                return insets.consumeSystemWindowInsets();
6181            }
6182        }
6183        return insets;
6184    }
6185
6186    /**
6187     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6188     * window insets to this view. The listener's
6189     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6190     * method will be called instead of the view's
6191     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6192     *
6193     * @param listener Listener to set
6194     *
6195     * @see #onApplyWindowInsets(WindowInsets)
6196     */
6197    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6198        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6199    }
6200
6201    /**
6202     * Request to apply the given window insets to this view or another view in its subtree.
6203     *
6204     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6205     * obscured by window decorations or overlays. This can include the status and navigation bars,
6206     * action bars, input methods and more. New inset categories may be added in the future.
6207     * The method returns the insets provided minus any that were applied by this view or its
6208     * children.</p>
6209     *
6210     * <p>Clients wishing to provide custom behavior should override the
6211     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6212     * {@link OnApplyWindowInsetsListener} via the
6213     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6214     * method.</p>
6215     *
6216     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6217     * </p>
6218     *
6219     * @param insets Insets to apply
6220     * @return The provided insets minus the insets that were consumed
6221     */
6222    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6223        try {
6224            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6225            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6226                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6227            } else {
6228                return onApplyWindowInsets(insets);
6229            }
6230        } finally {
6231            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6232        }
6233    }
6234
6235    /**
6236     * @hide Compute the insets that should be consumed by this view and the ones
6237     * that should propagate to those under it.
6238     */
6239    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6240        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6241                || mAttachInfo == null
6242                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6243                        && !mAttachInfo.mOverscanRequested)) {
6244            outLocalInsets.set(inoutInsets);
6245            inoutInsets.set(0, 0, 0, 0);
6246            return true;
6247        } else {
6248            // The application wants to take care of fitting system window for
6249            // the content...  however we still need to take care of any overscan here.
6250            final Rect overscan = mAttachInfo.mOverscanInsets;
6251            outLocalInsets.set(overscan);
6252            inoutInsets.left -= overscan.left;
6253            inoutInsets.top -= overscan.top;
6254            inoutInsets.right -= overscan.right;
6255            inoutInsets.bottom -= overscan.bottom;
6256            return false;
6257        }
6258    }
6259
6260    /**
6261     * Sets whether or not this view should account for system screen decorations
6262     * such as the status bar and inset its content; that is, controlling whether
6263     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6264     * executed.  See that method for more details.
6265     *
6266     * <p>Note that if you are providing your own implementation of
6267     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6268     * flag to true -- your implementation will be overriding the default
6269     * implementation that checks this flag.
6270     *
6271     * @param fitSystemWindows If true, then the default implementation of
6272     * {@link #fitSystemWindows(Rect)} will be executed.
6273     *
6274     * @attr ref android.R.styleable#View_fitsSystemWindows
6275     * @see #getFitsSystemWindows()
6276     * @see #fitSystemWindows(Rect)
6277     * @see #setSystemUiVisibility(int)
6278     */
6279    public void setFitsSystemWindows(boolean fitSystemWindows) {
6280        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6281    }
6282
6283    /**
6284     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6285     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6286     * will be executed.
6287     *
6288     * @return {@code true} if the default implementation of
6289     * {@link #fitSystemWindows(Rect)} will be executed.
6290     *
6291     * @attr ref android.R.styleable#View_fitsSystemWindows
6292     * @see #setFitsSystemWindows(boolean)
6293     * @see #fitSystemWindows(Rect)
6294     * @see #setSystemUiVisibility(int)
6295     */
6296    public boolean getFitsSystemWindows() {
6297        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6298    }
6299
6300    /** @hide */
6301    public boolean fitsSystemWindows() {
6302        return getFitsSystemWindows();
6303    }
6304
6305    /**
6306     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6307     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6308     */
6309    public void requestFitSystemWindows() {
6310        if (mParent != null) {
6311            mParent.requestFitSystemWindows();
6312        }
6313    }
6314
6315    /**
6316     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6317     */
6318    public void requestApplyInsets() {
6319        requestFitSystemWindows();
6320    }
6321
6322    /**
6323     * For use by PhoneWindow to make its own system window fitting optional.
6324     * @hide
6325     */
6326    public void makeOptionalFitsSystemWindows() {
6327        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6328    }
6329
6330    /**
6331     * Returns the visibility status for this view.
6332     *
6333     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6334     * @attr ref android.R.styleable#View_visibility
6335     */
6336    @ViewDebug.ExportedProperty(mapping = {
6337        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6338        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6339        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6340    })
6341    @Visibility
6342    public int getVisibility() {
6343        return mViewFlags & VISIBILITY_MASK;
6344    }
6345
6346    /**
6347     * Set the enabled state of this view.
6348     *
6349     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6350     * @attr ref android.R.styleable#View_visibility
6351     */
6352    @RemotableViewMethod
6353    public void setVisibility(@Visibility int visibility) {
6354        setFlags(visibility, VISIBILITY_MASK);
6355        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6356    }
6357
6358    /**
6359     * Returns the enabled status for this view. The interpretation of the
6360     * enabled state varies by subclass.
6361     *
6362     * @return True if this view is enabled, false otherwise.
6363     */
6364    @ViewDebug.ExportedProperty
6365    public boolean isEnabled() {
6366        return (mViewFlags & ENABLED_MASK) == ENABLED;
6367    }
6368
6369    /**
6370     * Set the enabled state of this view. The interpretation of the enabled
6371     * state varies by subclass.
6372     *
6373     * @param enabled True if this view is enabled, false otherwise.
6374     */
6375    @RemotableViewMethod
6376    public void setEnabled(boolean enabled) {
6377        if (enabled == isEnabled()) return;
6378
6379        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6380
6381        /*
6382         * The View most likely has to change its appearance, so refresh
6383         * the drawable state.
6384         */
6385        refreshDrawableState();
6386
6387        // Invalidate too, since the default behavior for views is to be
6388        // be drawn at 50% alpha rather than to change the drawable.
6389        invalidate(true);
6390
6391        if (!enabled) {
6392            cancelPendingInputEvents();
6393        }
6394    }
6395
6396    /**
6397     * Set whether this view can receive the focus.
6398     *
6399     * Setting this to false will also ensure that this view is not focusable
6400     * in touch mode.
6401     *
6402     * @param focusable If true, this view can receive the focus.
6403     *
6404     * @see #setFocusableInTouchMode(boolean)
6405     * @attr ref android.R.styleable#View_focusable
6406     */
6407    public void setFocusable(boolean focusable) {
6408        if (!focusable) {
6409            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6410        }
6411        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6412    }
6413
6414    /**
6415     * Set whether this view can receive focus while in touch mode.
6416     *
6417     * Setting this to true will also ensure that this view is focusable.
6418     *
6419     * @param focusableInTouchMode If true, this view can receive the focus while
6420     *   in touch mode.
6421     *
6422     * @see #setFocusable(boolean)
6423     * @attr ref android.R.styleable#View_focusableInTouchMode
6424     */
6425    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6426        // Focusable in touch mode should always be set before the focusable flag
6427        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6428        // which, in touch mode, will not successfully request focus on this view
6429        // because the focusable in touch mode flag is not set
6430        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6431        if (focusableInTouchMode) {
6432            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6433        }
6434    }
6435
6436    /**
6437     * Set whether this view should have sound effects enabled for events such as
6438     * clicking and touching.
6439     *
6440     * <p>You may wish to disable sound effects for a view if you already play sounds,
6441     * for instance, a dial key that plays dtmf tones.
6442     *
6443     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6444     * @see #isSoundEffectsEnabled()
6445     * @see #playSoundEffect(int)
6446     * @attr ref android.R.styleable#View_soundEffectsEnabled
6447     */
6448    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6449        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6450    }
6451
6452    /**
6453     * @return whether this view should have sound effects enabled for events such as
6454     *     clicking and touching.
6455     *
6456     * @see #setSoundEffectsEnabled(boolean)
6457     * @see #playSoundEffect(int)
6458     * @attr ref android.R.styleable#View_soundEffectsEnabled
6459     */
6460    @ViewDebug.ExportedProperty
6461    public boolean isSoundEffectsEnabled() {
6462        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6463    }
6464
6465    /**
6466     * Set whether this view should have haptic feedback for events such as
6467     * long presses.
6468     *
6469     * <p>You may wish to disable haptic feedback if your view already controls
6470     * its own haptic feedback.
6471     *
6472     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6473     * @see #isHapticFeedbackEnabled()
6474     * @see #performHapticFeedback(int)
6475     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6476     */
6477    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6478        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6479    }
6480
6481    /**
6482     * @return whether this view should have haptic feedback enabled for events
6483     * long presses.
6484     *
6485     * @see #setHapticFeedbackEnabled(boolean)
6486     * @see #performHapticFeedback(int)
6487     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6488     */
6489    @ViewDebug.ExportedProperty
6490    public boolean isHapticFeedbackEnabled() {
6491        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6492    }
6493
6494    /**
6495     * Returns the layout direction for this view.
6496     *
6497     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6498     *   {@link #LAYOUT_DIRECTION_RTL},
6499     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6500     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6501     *
6502     * @attr ref android.R.styleable#View_layoutDirection
6503     *
6504     * @hide
6505     */
6506    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6507        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6508        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6509        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6510        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6511    })
6512    @LayoutDir
6513    public int getRawLayoutDirection() {
6514        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6515    }
6516
6517    /**
6518     * Set the layout direction for this view. This will propagate a reset of layout direction
6519     * resolution to the view's children and resolve layout direction for this view.
6520     *
6521     * @param layoutDirection the layout direction to set. Should be one of:
6522     *
6523     * {@link #LAYOUT_DIRECTION_LTR},
6524     * {@link #LAYOUT_DIRECTION_RTL},
6525     * {@link #LAYOUT_DIRECTION_INHERIT},
6526     * {@link #LAYOUT_DIRECTION_LOCALE}.
6527     *
6528     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6529     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6530     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6531     *
6532     * @attr ref android.R.styleable#View_layoutDirection
6533     */
6534    @RemotableViewMethod
6535    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6536        if (getRawLayoutDirection() != layoutDirection) {
6537            // Reset the current layout direction and the resolved one
6538            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6539            resetRtlProperties();
6540            // Set the new layout direction (filtered)
6541            mPrivateFlags2 |=
6542                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6543            // We need to resolve all RTL properties as they all depend on layout direction
6544            resolveRtlPropertiesIfNeeded();
6545            requestLayout();
6546            invalidate(true);
6547        }
6548    }
6549
6550    /**
6551     * Returns the resolved layout direction for this view.
6552     *
6553     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6554     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6555     *
6556     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6557     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6558     *
6559     * @attr ref android.R.styleable#View_layoutDirection
6560     */
6561    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6562        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6563        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6564    })
6565    @ResolvedLayoutDir
6566    public int getLayoutDirection() {
6567        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6568        if (targetSdkVersion < JELLY_BEAN_MR1) {
6569            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6570            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6571        }
6572        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6573                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6574    }
6575
6576    /**
6577     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6578     * layout attribute and/or the inherited value from the parent
6579     *
6580     * @return true if the layout is right-to-left.
6581     *
6582     * @hide
6583     */
6584    @ViewDebug.ExportedProperty(category = "layout")
6585    public boolean isLayoutRtl() {
6586        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6587    }
6588
6589    /**
6590     * Indicates whether the view is currently tracking transient state that the
6591     * app should not need to concern itself with saving and restoring, but that
6592     * the framework should take special note to preserve when possible.
6593     *
6594     * <p>A view with transient state cannot be trivially rebound from an external
6595     * data source, such as an adapter binding item views in a list. This may be
6596     * because the view is performing an animation, tracking user selection
6597     * of content, or similar.</p>
6598     *
6599     * @return true if the view has transient state
6600     */
6601    @ViewDebug.ExportedProperty(category = "layout")
6602    public boolean hasTransientState() {
6603        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6604    }
6605
6606    /**
6607     * Set whether this view is currently tracking transient state that the
6608     * framework should attempt to preserve when possible. This flag is reference counted,
6609     * so every call to setHasTransientState(true) should be paired with a later call
6610     * to setHasTransientState(false).
6611     *
6612     * <p>A view with transient state cannot be trivially rebound from an external
6613     * data source, such as an adapter binding item views in a list. This may be
6614     * because the view is performing an animation, tracking user selection
6615     * of content, or similar.</p>
6616     *
6617     * @param hasTransientState true if this view has transient state
6618     */
6619    public void setHasTransientState(boolean hasTransientState) {
6620        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6621                mTransientStateCount - 1;
6622        if (mTransientStateCount < 0) {
6623            mTransientStateCount = 0;
6624            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6625                    "unmatched pair of setHasTransientState calls");
6626        } else if ((hasTransientState && mTransientStateCount == 1) ||
6627                (!hasTransientState && mTransientStateCount == 0)) {
6628            // update flag if we've just incremented up from 0 or decremented down to 0
6629            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6630                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6631            if (mParent != null) {
6632                try {
6633                    mParent.childHasTransientStateChanged(this, hasTransientState);
6634                } catch (AbstractMethodError e) {
6635                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6636                            " does not fully implement ViewParent", e);
6637                }
6638            }
6639        }
6640    }
6641
6642    /**
6643     * Returns true if this view is currently attached to a window.
6644     */
6645    public boolean isAttachedToWindow() {
6646        return mAttachInfo != null;
6647    }
6648
6649    /**
6650     * Returns true if this view has been through at least one layout since it
6651     * was last attached to or detached from a window.
6652     */
6653    public boolean isLaidOut() {
6654        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6655    }
6656
6657    /**
6658     * If this view doesn't do any drawing on its own, set this flag to
6659     * allow further optimizations. By default, this flag is not set on
6660     * View, but could be set on some View subclasses such as ViewGroup.
6661     *
6662     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6663     * you should clear this flag.
6664     *
6665     * @param willNotDraw whether or not this View draw on its own
6666     */
6667    public void setWillNotDraw(boolean willNotDraw) {
6668        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6669    }
6670
6671    /**
6672     * Returns whether or not this View draws on its own.
6673     *
6674     * @return true if this view has nothing to draw, false otherwise
6675     */
6676    @ViewDebug.ExportedProperty(category = "drawing")
6677    public boolean willNotDraw() {
6678        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6679    }
6680
6681    /**
6682     * When a View's drawing cache is enabled, drawing is redirected to an
6683     * offscreen bitmap. Some views, like an ImageView, must be able to
6684     * bypass this mechanism if they already draw a single bitmap, to avoid
6685     * unnecessary usage of the memory.
6686     *
6687     * @param willNotCacheDrawing true if this view does not cache its
6688     *        drawing, false otherwise
6689     */
6690    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6691        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6692    }
6693
6694    /**
6695     * Returns whether or not this View can cache its drawing or not.
6696     *
6697     * @return true if this view does not cache its drawing, false otherwise
6698     */
6699    @ViewDebug.ExportedProperty(category = "drawing")
6700    public boolean willNotCacheDrawing() {
6701        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6702    }
6703
6704    /**
6705     * Indicates whether this view reacts to click events or not.
6706     *
6707     * @return true if the view is clickable, false otherwise
6708     *
6709     * @see #setClickable(boolean)
6710     * @attr ref android.R.styleable#View_clickable
6711     */
6712    @ViewDebug.ExportedProperty
6713    public boolean isClickable() {
6714        return (mViewFlags & CLICKABLE) == CLICKABLE;
6715    }
6716
6717    /**
6718     * Enables or disables click events for this view. When a view
6719     * is clickable it will change its state to "pressed" on every click.
6720     * Subclasses should set the view clickable to visually react to
6721     * user's clicks.
6722     *
6723     * @param clickable true to make the view clickable, false otherwise
6724     *
6725     * @see #isClickable()
6726     * @attr ref android.R.styleable#View_clickable
6727     */
6728    public void setClickable(boolean clickable) {
6729        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6730    }
6731
6732    /**
6733     * Indicates whether this view reacts to long click events or not.
6734     *
6735     * @return true if the view is long clickable, false otherwise
6736     *
6737     * @see #setLongClickable(boolean)
6738     * @attr ref android.R.styleable#View_longClickable
6739     */
6740    public boolean isLongClickable() {
6741        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6742    }
6743
6744    /**
6745     * Enables or disables long click events for this view. When a view is long
6746     * clickable it reacts to the user holding down the button for a longer
6747     * duration than a tap. This event can either launch the listener or a
6748     * context menu.
6749     *
6750     * @param longClickable true to make the view long clickable, false otherwise
6751     * @see #isLongClickable()
6752     * @attr ref android.R.styleable#View_longClickable
6753     */
6754    public void setLongClickable(boolean longClickable) {
6755        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6756    }
6757
6758    /**
6759     * Sets the pressed state for this view and provides a touch coordinate for
6760     * animation hinting.
6761     *
6762     * @param pressed Pass true to set the View's internal state to "pressed",
6763     *            or false to reverts the View's internal state from a
6764     *            previously set "pressed" state.
6765     * @param x The x coordinate of the touch that caused the press
6766     * @param y The y coordinate of the touch that caused the press
6767     */
6768    private void setPressed(boolean pressed, float x, float y) {
6769        if (pressed) {
6770            setHotspot(x, y);
6771        }
6772
6773        setPressed(pressed);
6774    }
6775
6776    /**
6777     * Sets the pressed state for this view.
6778     *
6779     * @see #isClickable()
6780     * @see #setClickable(boolean)
6781     *
6782     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6783     *        the View's internal state from a previously set "pressed" state.
6784     */
6785    public void setPressed(boolean pressed) {
6786        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6787
6788        if (pressed) {
6789            mPrivateFlags |= PFLAG_PRESSED;
6790        } else {
6791            mPrivateFlags &= ~PFLAG_PRESSED;
6792        }
6793
6794        if (needsRefresh) {
6795            refreshDrawableState();
6796        }
6797        dispatchSetPressed(pressed);
6798    }
6799
6800    /**
6801     * Dispatch setPressed to all of this View's children.
6802     *
6803     * @see #setPressed(boolean)
6804     *
6805     * @param pressed The new pressed state
6806     */
6807    protected void dispatchSetPressed(boolean pressed) {
6808    }
6809
6810    /**
6811     * Indicates whether the view is currently in pressed state. Unless
6812     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6813     * the pressed state.
6814     *
6815     * @see #setPressed(boolean)
6816     * @see #isClickable()
6817     * @see #setClickable(boolean)
6818     *
6819     * @return true if the view is currently pressed, false otherwise
6820     */
6821    public boolean isPressed() {
6822        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6823    }
6824
6825    /**
6826     * Indicates whether this view will save its state (that is,
6827     * whether its {@link #onSaveInstanceState} method will be called).
6828     *
6829     * @return Returns true if the view state saving is enabled, else false.
6830     *
6831     * @see #setSaveEnabled(boolean)
6832     * @attr ref android.R.styleable#View_saveEnabled
6833     */
6834    public boolean isSaveEnabled() {
6835        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6836    }
6837
6838    /**
6839     * Controls whether the saving of this view's state is
6840     * enabled (that is, whether its {@link #onSaveInstanceState} method
6841     * will be called).  Note that even if freezing is enabled, the
6842     * view still must have an id assigned to it (via {@link #setId(int)})
6843     * for its state to be saved.  This flag can only disable the
6844     * saving of this view; any child views may still have their state saved.
6845     *
6846     * @param enabled Set to false to <em>disable</em> state saving, or true
6847     * (the default) to allow it.
6848     *
6849     * @see #isSaveEnabled()
6850     * @see #setId(int)
6851     * @see #onSaveInstanceState()
6852     * @attr ref android.R.styleable#View_saveEnabled
6853     */
6854    public void setSaveEnabled(boolean enabled) {
6855        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6856    }
6857
6858    /**
6859     * Gets whether the framework should discard touches when the view's
6860     * window is obscured by another visible window.
6861     * Refer to the {@link View} security documentation for more details.
6862     *
6863     * @return True if touch filtering is enabled.
6864     *
6865     * @see #setFilterTouchesWhenObscured(boolean)
6866     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6867     */
6868    @ViewDebug.ExportedProperty
6869    public boolean getFilterTouchesWhenObscured() {
6870        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6871    }
6872
6873    /**
6874     * Sets whether the framework should discard touches when the view's
6875     * window is obscured by another visible window.
6876     * Refer to the {@link View} security documentation for more details.
6877     *
6878     * @param enabled True if touch filtering should be enabled.
6879     *
6880     * @see #getFilterTouchesWhenObscured
6881     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6882     */
6883    public void setFilterTouchesWhenObscured(boolean enabled) {
6884        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6885                FILTER_TOUCHES_WHEN_OBSCURED);
6886    }
6887
6888    /**
6889     * Indicates whether the entire hierarchy under this view will save its
6890     * state when a state saving traversal occurs from its parent.  The default
6891     * is true; if false, these views will not be saved unless
6892     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6893     *
6894     * @return Returns true if the view state saving from parent is enabled, else false.
6895     *
6896     * @see #setSaveFromParentEnabled(boolean)
6897     */
6898    public boolean isSaveFromParentEnabled() {
6899        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6900    }
6901
6902    /**
6903     * Controls whether the entire hierarchy under this view will save its
6904     * state when a state saving traversal occurs from its parent.  The default
6905     * is true; if false, these views will not be saved unless
6906     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6907     *
6908     * @param enabled Set to false to <em>disable</em> state saving, or true
6909     * (the default) to allow it.
6910     *
6911     * @see #isSaveFromParentEnabled()
6912     * @see #setId(int)
6913     * @see #onSaveInstanceState()
6914     */
6915    public void setSaveFromParentEnabled(boolean enabled) {
6916        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6917    }
6918
6919
6920    /**
6921     * Returns whether this View is able to take focus.
6922     *
6923     * @return True if this view can take focus, or false otherwise.
6924     * @attr ref android.R.styleable#View_focusable
6925     */
6926    @ViewDebug.ExportedProperty(category = "focus")
6927    public final boolean isFocusable() {
6928        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6929    }
6930
6931    /**
6932     * When a view is focusable, it may not want to take focus when in touch mode.
6933     * For example, a button would like focus when the user is navigating via a D-pad
6934     * so that the user can click on it, but once the user starts touching the screen,
6935     * the button shouldn't take focus
6936     * @return Whether the view is focusable in touch mode.
6937     * @attr ref android.R.styleable#View_focusableInTouchMode
6938     */
6939    @ViewDebug.ExportedProperty
6940    public final boolean isFocusableInTouchMode() {
6941        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6942    }
6943
6944    /**
6945     * Find the nearest view in the specified direction that can take focus.
6946     * This does not actually give focus to that view.
6947     *
6948     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6949     *
6950     * @return The nearest focusable in the specified direction, or null if none
6951     *         can be found.
6952     */
6953    public View focusSearch(@FocusRealDirection int direction) {
6954        if (mParent != null) {
6955            return mParent.focusSearch(this, direction);
6956        } else {
6957            return null;
6958        }
6959    }
6960
6961    /**
6962     * This method is the last chance for the focused view and its ancestors to
6963     * respond to an arrow key. This is called when the focused view did not
6964     * consume the key internally, nor could the view system find a new view in
6965     * the requested direction to give focus to.
6966     *
6967     * @param focused The currently focused view.
6968     * @param direction The direction focus wants to move. One of FOCUS_UP,
6969     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6970     * @return True if the this view consumed this unhandled move.
6971     */
6972    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6973        return false;
6974    }
6975
6976    /**
6977     * If a user manually specified the next view id for a particular direction,
6978     * use the root to look up the view.
6979     * @param root The root view of the hierarchy containing this view.
6980     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6981     * or FOCUS_BACKWARD.
6982     * @return The user specified next view, or null if there is none.
6983     */
6984    View findUserSetNextFocus(View root, @FocusDirection int direction) {
6985        switch (direction) {
6986            case FOCUS_LEFT:
6987                if (mNextFocusLeftId == View.NO_ID) return null;
6988                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6989            case FOCUS_RIGHT:
6990                if (mNextFocusRightId == View.NO_ID) return null;
6991                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6992            case FOCUS_UP:
6993                if (mNextFocusUpId == View.NO_ID) return null;
6994                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6995            case FOCUS_DOWN:
6996                if (mNextFocusDownId == View.NO_ID) return null;
6997                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6998            case FOCUS_FORWARD:
6999                if (mNextFocusForwardId == View.NO_ID) return null;
7000                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7001            case FOCUS_BACKWARD: {
7002                if (mID == View.NO_ID) return null;
7003                final int id = mID;
7004                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7005                    @Override
7006                    public boolean apply(View t) {
7007                        return t.mNextFocusForwardId == id;
7008                    }
7009                });
7010            }
7011        }
7012        return null;
7013    }
7014
7015    private View findViewInsideOutShouldExist(View root, int id) {
7016        if (mMatchIdPredicate == null) {
7017            mMatchIdPredicate = new MatchIdPredicate();
7018        }
7019        mMatchIdPredicate.mId = id;
7020        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7021        if (result == null) {
7022            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7023        }
7024        return result;
7025    }
7026
7027    /**
7028     * Find and return all focusable views that are descendants of this view,
7029     * possibly including this view if it is focusable itself.
7030     *
7031     * @param direction The direction of the focus
7032     * @return A list of focusable views
7033     */
7034    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7035        ArrayList<View> result = new ArrayList<View>(24);
7036        addFocusables(result, direction);
7037        return result;
7038    }
7039
7040    /**
7041     * Add any focusable views that are descendants of this view (possibly
7042     * including this view if it is focusable itself) to views.  If we are in touch mode,
7043     * only add views that are also focusable in touch mode.
7044     *
7045     * @param views Focusable views found so far
7046     * @param direction The direction of the focus
7047     */
7048    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7049        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7050    }
7051
7052    /**
7053     * Adds any focusable views that are descendants of this view (possibly
7054     * including this view if it is focusable itself) to views. This method
7055     * adds all focusable views regardless if we are in touch mode or
7056     * only views focusable in touch mode if we are in touch mode or
7057     * only views that can take accessibility focus if accessibility is enabeld
7058     * depending on the focusable mode paramater.
7059     *
7060     * @param views Focusable views found so far or null if all we are interested is
7061     *        the number of focusables.
7062     * @param direction The direction of the focus.
7063     * @param focusableMode The type of focusables to be added.
7064     *
7065     * @see #FOCUSABLES_ALL
7066     * @see #FOCUSABLES_TOUCH_MODE
7067     */
7068    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7069            @FocusableMode int focusableMode) {
7070        if (views == null) {
7071            return;
7072        }
7073        if (!isFocusable()) {
7074            return;
7075        }
7076        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7077                && isInTouchMode() && !isFocusableInTouchMode()) {
7078            return;
7079        }
7080        views.add(this);
7081    }
7082
7083    /**
7084     * Finds the Views that contain given text. The containment is case insensitive.
7085     * The search is performed by either the text that the View renders or the content
7086     * description that describes the view for accessibility purposes and the view does
7087     * not render or both. Clients can specify how the search is to be performed via
7088     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7089     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7090     *
7091     * @param outViews The output list of matching Views.
7092     * @param searched The text to match against.
7093     *
7094     * @see #FIND_VIEWS_WITH_TEXT
7095     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7096     * @see #setContentDescription(CharSequence)
7097     */
7098    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7099            @FindViewFlags int flags) {
7100        if (getAccessibilityNodeProvider() != null) {
7101            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7102                outViews.add(this);
7103            }
7104        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7105                && (searched != null && searched.length() > 0)
7106                && (mContentDescription != null && mContentDescription.length() > 0)) {
7107            String searchedLowerCase = searched.toString().toLowerCase();
7108            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7109            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7110                outViews.add(this);
7111            }
7112        }
7113    }
7114
7115    /**
7116     * Find and return all touchable views that are descendants of this view,
7117     * possibly including this view if it is touchable itself.
7118     *
7119     * @return A list of touchable views
7120     */
7121    public ArrayList<View> getTouchables() {
7122        ArrayList<View> result = new ArrayList<View>();
7123        addTouchables(result);
7124        return result;
7125    }
7126
7127    /**
7128     * Add any touchable views that are descendants of this view (possibly
7129     * including this view if it is touchable itself) to views.
7130     *
7131     * @param views Touchable views found so far
7132     */
7133    public void addTouchables(ArrayList<View> views) {
7134        final int viewFlags = mViewFlags;
7135
7136        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7137                && (viewFlags & ENABLED_MASK) == ENABLED) {
7138            views.add(this);
7139        }
7140    }
7141
7142    /**
7143     * Returns whether this View is accessibility focused.
7144     *
7145     * @return True if this View is accessibility focused.
7146     */
7147    public boolean isAccessibilityFocused() {
7148        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7149    }
7150
7151    /**
7152     * Call this to try to give accessibility focus to this view.
7153     *
7154     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7155     * returns false or the view is no visible or the view already has accessibility
7156     * focus.
7157     *
7158     * See also {@link #focusSearch(int)}, which is what you call to say that you
7159     * have focus, and you want your parent to look for the next one.
7160     *
7161     * @return Whether this view actually took accessibility focus.
7162     *
7163     * @hide
7164     */
7165    public boolean requestAccessibilityFocus() {
7166        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7167        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7168            return false;
7169        }
7170        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7171            return false;
7172        }
7173        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7174            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7175            ViewRootImpl viewRootImpl = getViewRootImpl();
7176            if (viewRootImpl != null) {
7177                viewRootImpl.setAccessibilityFocus(this, null);
7178            }
7179            Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect();
7180            getDrawingRect(rect);
7181            requestRectangleOnScreen(rect, false);
7182            invalidate();
7183            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7184            return true;
7185        }
7186        return false;
7187    }
7188
7189    /**
7190     * Call this to try to clear accessibility focus of this view.
7191     *
7192     * See also {@link #focusSearch(int)}, which is what you call to say that you
7193     * have focus, and you want your parent to look for the next one.
7194     *
7195     * @hide
7196     */
7197    public void clearAccessibilityFocus() {
7198        clearAccessibilityFocusNoCallbacks();
7199        // Clear the global reference of accessibility focus if this
7200        // view or any of its descendants had accessibility focus.
7201        ViewRootImpl viewRootImpl = getViewRootImpl();
7202        if (viewRootImpl != null) {
7203            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7204            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7205                viewRootImpl.setAccessibilityFocus(null, null);
7206            }
7207        }
7208    }
7209
7210    private void sendAccessibilityHoverEvent(int eventType) {
7211        // Since we are not delivering to a client accessibility events from not
7212        // important views (unless the clinet request that) we need to fire the
7213        // event from the deepest view exposed to the client. As a consequence if
7214        // the user crosses a not exposed view the client will see enter and exit
7215        // of the exposed predecessor followed by and enter and exit of that same
7216        // predecessor when entering and exiting the not exposed descendant. This
7217        // is fine since the client has a clear idea which view is hovered at the
7218        // price of a couple more events being sent. This is a simple and
7219        // working solution.
7220        View source = this;
7221        while (true) {
7222            if (source.includeForAccessibility()) {
7223                source.sendAccessibilityEvent(eventType);
7224                return;
7225            }
7226            ViewParent parent = source.getParent();
7227            if (parent instanceof View) {
7228                source = (View) parent;
7229            } else {
7230                return;
7231            }
7232        }
7233    }
7234
7235    /**
7236     * Clears accessibility focus without calling any callback methods
7237     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7238     * is used for clearing accessibility focus when giving this focus to
7239     * another view.
7240     */
7241    void clearAccessibilityFocusNoCallbacks() {
7242        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7243            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7244            invalidate();
7245            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7246        }
7247    }
7248
7249    /**
7250     * Call this to try to give focus to a specific view or to one of its
7251     * descendants.
7252     *
7253     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7254     * false), or if it is focusable and it is not focusable in touch mode
7255     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7256     *
7257     * See also {@link #focusSearch(int)}, which is what you call to say that you
7258     * have focus, and you want your parent to look for the next one.
7259     *
7260     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7261     * {@link #FOCUS_DOWN} and <code>null</code>.
7262     *
7263     * @return Whether this view or one of its descendants actually took focus.
7264     */
7265    public final boolean requestFocus() {
7266        return requestFocus(View.FOCUS_DOWN);
7267    }
7268
7269    /**
7270     * Call this to try to give focus to a specific view or to one of its
7271     * descendants and give it a hint about what direction focus is heading.
7272     *
7273     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7274     * false), or if it is focusable and it is not focusable in touch mode
7275     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7276     *
7277     * See also {@link #focusSearch(int)}, which is what you call to say that you
7278     * have focus, and you want your parent to look for the next one.
7279     *
7280     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7281     * <code>null</code> set for the previously focused rectangle.
7282     *
7283     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7284     * @return Whether this view or one of its descendants actually took focus.
7285     */
7286    public final boolean requestFocus(int direction) {
7287        return requestFocus(direction, null);
7288    }
7289
7290    /**
7291     * Call this to try to give focus to a specific view or to one of its descendants
7292     * and give it hints about the direction and a specific rectangle that the focus
7293     * is coming from.  The rectangle can help give larger views a finer grained hint
7294     * about where focus is coming from, and therefore, where to show selection, or
7295     * forward focus change internally.
7296     *
7297     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7298     * false), or if it is focusable and it is not focusable in touch mode
7299     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7300     *
7301     * A View will not take focus if it is not visible.
7302     *
7303     * A View will not take focus if one of its parents has
7304     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7305     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7306     *
7307     * See also {@link #focusSearch(int)}, which is what you call to say that you
7308     * have focus, and you want your parent to look for the next one.
7309     *
7310     * You may wish to override this method if your custom {@link View} has an internal
7311     * {@link View} that it wishes to forward the request to.
7312     *
7313     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7314     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7315     *        to give a finer grained hint about where focus is coming from.  May be null
7316     *        if there is no hint.
7317     * @return Whether this view or one of its descendants actually took focus.
7318     */
7319    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7320        return requestFocusNoSearch(direction, previouslyFocusedRect);
7321    }
7322
7323    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7324        // need to be focusable
7325        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7326                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7327            return false;
7328        }
7329
7330        // need to be focusable in touch mode if in touch mode
7331        if (isInTouchMode() &&
7332            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7333               return false;
7334        }
7335
7336        // need to not have any parents blocking us
7337        if (hasAncestorThatBlocksDescendantFocus()) {
7338            return false;
7339        }
7340
7341        handleFocusGainInternal(direction, previouslyFocusedRect);
7342        return true;
7343    }
7344
7345    /**
7346     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7347     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7348     * touch mode to request focus when they are touched.
7349     *
7350     * @return Whether this view or one of its descendants actually took focus.
7351     *
7352     * @see #isInTouchMode()
7353     *
7354     */
7355    public final boolean requestFocusFromTouch() {
7356        // Leave touch mode if we need to
7357        if (isInTouchMode()) {
7358            ViewRootImpl viewRoot = getViewRootImpl();
7359            if (viewRoot != null) {
7360                viewRoot.ensureTouchMode(false);
7361            }
7362        }
7363        return requestFocus(View.FOCUS_DOWN);
7364    }
7365
7366    /**
7367     * @return Whether any ancestor of this view blocks descendant focus.
7368     */
7369    private boolean hasAncestorThatBlocksDescendantFocus() {
7370        ViewParent ancestor = mParent;
7371        while (ancestor instanceof ViewGroup) {
7372            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7373            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7374                return true;
7375            } else {
7376                ancestor = vgAncestor.getParent();
7377            }
7378        }
7379        return false;
7380    }
7381
7382    /**
7383     * Gets the mode for determining whether this View is important for accessibility
7384     * which is if it fires accessibility events and if it is reported to
7385     * accessibility services that query the screen.
7386     *
7387     * @return The mode for determining whether a View is important for accessibility.
7388     *
7389     * @attr ref android.R.styleable#View_importantForAccessibility
7390     *
7391     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7392     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7393     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7394     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7395     */
7396    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7397            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7398            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7399            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7400            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7401                    to = "noHideDescendants")
7402        })
7403    public int getImportantForAccessibility() {
7404        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7405                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7406    }
7407
7408    /**
7409     * Sets the live region mode for this view. This indicates to accessibility
7410     * services whether they should automatically notify the user about changes
7411     * to the view's content description or text, or to the content descriptions
7412     * or text of the view's children (where applicable).
7413     * <p>
7414     * For example, in a login screen with a TextView that displays an "incorrect
7415     * password" notification, that view should be marked as a live region with
7416     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7417     * <p>
7418     * To disable change notifications for this view, use
7419     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7420     * mode for most views.
7421     * <p>
7422     * To indicate that the user should be notified of changes, use
7423     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7424     * <p>
7425     * If the view's changes should interrupt ongoing speech and notify the user
7426     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7427     *
7428     * @param mode The live region mode for this view, one of:
7429     *        <ul>
7430     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7431     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7432     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7433     *        </ul>
7434     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7435     */
7436    public void setAccessibilityLiveRegion(int mode) {
7437        if (mode != getAccessibilityLiveRegion()) {
7438            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7439            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7440                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7441            notifyViewAccessibilityStateChangedIfNeeded(
7442                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7443        }
7444    }
7445
7446    /**
7447     * Gets the live region mode for this View.
7448     *
7449     * @return The live region mode for the view.
7450     *
7451     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7452     *
7453     * @see #setAccessibilityLiveRegion(int)
7454     */
7455    public int getAccessibilityLiveRegion() {
7456        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7457                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7458    }
7459
7460    /**
7461     * Sets how to determine whether this view is important for accessibility
7462     * which is if it fires accessibility events and if it is reported to
7463     * accessibility services that query the screen.
7464     *
7465     * @param mode How to determine whether this view is important for accessibility.
7466     *
7467     * @attr ref android.R.styleable#View_importantForAccessibility
7468     *
7469     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7470     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7471     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7472     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7473     */
7474    public void setImportantForAccessibility(int mode) {
7475        final int oldMode = getImportantForAccessibility();
7476        if (mode != oldMode) {
7477            // If we're moving between AUTO and another state, we might not need
7478            // to send a subtree changed notification. We'll store the computed
7479            // importance, since we'll need to check it later to make sure.
7480            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7481                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7482            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7483            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7484            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7485                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7486            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7487                notifySubtreeAccessibilityStateChangedIfNeeded();
7488            } else {
7489                notifyViewAccessibilityStateChangedIfNeeded(
7490                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7491            }
7492        }
7493    }
7494
7495    /**
7496     * Computes whether this view should be exposed for accessibility. In
7497     * general, views that are interactive or provide information are exposed
7498     * while views that serve only as containers are hidden.
7499     * <p>
7500     * If an ancestor of this view has importance
7501     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7502     * returns <code>false</code>.
7503     * <p>
7504     * Otherwise, the value is computed according to the view's
7505     * {@link #getImportantForAccessibility()} value:
7506     * <ol>
7507     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7508     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7509     * </code>
7510     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7511     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7512     * view satisfies any of the following:
7513     * <ul>
7514     * <li>Is actionable, e.g. {@link #isClickable()},
7515     * {@link #isLongClickable()}, or {@link #isFocusable()}
7516     * <li>Has an {@link AccessibilityDelegate}
7517     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7518     * {@link OnKeyListener}, etc.
7519     * <li>Is an accessibility live region, e.g.
7520     * {@link #getAccessibilityLiveRegion()} is not
7521     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7522     * </ul>
7523     * </ol>
7524     *
7525     * @return Whether the view is exposed for accessibility.
7526     * @see #setImportantForAccessibility(int)
7527     * @see #getImportantForAccessibility()
7528     */
7529    public boolean isImportantForAccessibility() {
7530        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7531                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7532        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7533                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7534            return false;
7535        }
7536
7537        // Check parent mode to ensure we're not hidden.
7538        ViewParent parent = mParent;
7539        while (parent instanceof View) {
7540            if (((View) parent).getImportantForAccessibility()
7541                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7542                return false;
7543            }
7544            parent = parent.getParent();
7545        }
7546
7547        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7548                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7549                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7550    }
7551
7552    /**
7553     * Gets the parent for accessibility purposes. Note that the parent for
7554     * accessibility is not necessary the immediate parent. It is the first
7555     * predecessor that is important for accessibility.
7556     *
7557     * @return The parent for accessibility purposes.
7558     */
7559    public ViewParent getParentForAccessibility() {
7560        if (mParent instanceof View) {
7561            View parentView = (View) mParent;
7562            if (parentView.includeForAccessibility()) {
7563                return mParent;
7564            } else {
7565                return mParent.getParentForAccessibility();
7566            }
7567        }
7568        return null;
7569    }
7570
7571    /**
7572     * Adds the children of a given View for accessibility. Since some Views are
7573     * not important for accessibility the children for accessibility are not
7574     * necessarily direct children of the view, rather they are the first level of
7575     * descendants important for accessibility.
7576     *
7577     * @param children The list of children for accessibility.
7578     */
7579    public void addChildrenForAccessibility(ArrayList<View> children) {
7580
7581    }
7582
7583    /**
7584     * Whether to regard this view for accessibility. A view is regarded for
7585     * accessibility if it is important for accessibility or the querying
7586     * accessibility service has explicitly requested that view not
7587     * important for accessibility are regarded.
7588     *
7589     * @return Whether to regard the view for accessibility.
7590     *
7591     * @hide
7592     */
7593    public boolean includeForAccessibility() {
7594        if (mAttachInfo != null) {
7595            return (mAttachInfo.mAccessibilityFetchFlags
7596                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7597                    || isImportantForAccessibility();
7598        }
7599        return false;
7600    }
7601
7602    /**
7603     * Returns whether the View is considered actionable from
7604     * accessibility perspective. Such view are important for
7605     * accessibility.
7606     *
7607     * @return True if the view is actionable for accessibility.
7608     *
7609     * @hide
7610     */
7611    public boolean isActionableForAccessibility() {
7612        return (isClickable() || isLongClickable() || isFocusable());
7613    }
7614
7615    /**
7616     * Returns whether the View has registered callbacks which makes it
7617     * important for accessibility.
7618     *
7619     * @return True if the view is actionable for accessibility.
7620     */
7621    private boolean hasListenersForAccessibility() {
7622        ListenerInfo info = getListenerInfo();
7623        return mTouchDelegate != null || info.mOnKeyListener != null
7624                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7625                || info.mOnHoverListener != null || info.mOnDragListener != null;
7626    }
7627
7628    /**
7629     * Notifies that the accessibility state of this view changed. The change
7630     * is local to this view and does not represent structural changes such
7631     * as children and parent. For example, the view became focusable. The
7632     * notification is at at most once every
7633     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7634     * to avoid unnecessary load to the system. Also once a view has a pending
7635     * notification this method is a NOP until the notification has been sent.
7636     *
7637     * @hide
7638     */
7639    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7640        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7641            return;
7642        }
7643        if (mSendViewStateChangedAccessibilityEvent == null) {
7644            mSendViewStateChangedAccessibilityEvent =
7645                    new SendViewStateChangedAccessibilityEvent();
7646        }
7647        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7648    }
7649
7650    /**
7651     * Notifies that the accessibility state of this view changed. The change
7652     * is *not* local to this view and does represent structural changes such
7653     * as children and parent. For example, the view size changed. The
7654     * notification is at at most once every
7655     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7656     * to avoid unnecessary load to the system. Also once a view has a pending
7657     * notification this method is a NOP until the notification has been sent.
7658     *
7659     * @hide
7660     */
7661    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7662        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7663            return;
7664        }
7665        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7666            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7667            if (mParent != null) {
7668                try {
7669                    mParent.notifySubtreeAccessibilityStateChanged(
7670                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7671                } catch (AbstractMethodError e) {
7672                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7673                            " does not fully implement ViewParent", e);
7674                }
7675            }
7676        }
7677    }
7678
7679    /**
7680     * Reset the flag indicating the accessibility state of the subtree rooted
7681     * at this view changed.
7682     */
7683    void resetSubtreeAccessibilityStateChanged() {
7684        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7685    }
7686
7687    /**
7688     * Performs the specified accessibility action on the view. For
7689     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7690     * <p>
7691     * If an {@link AccessibilityDelegate} has been specified via calling
7692     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7693     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7694     * is responsible for handling this call.
7695     * </p>
7696     *
7697     * @param action The action to perform.
7698     * @param arguments Optional action arguments.
7699     * @return Whether the action was performed.
7700     */
7701    public boolean performAccessibilityAction(int action, Bundle arguments) {
7702      if (mAccessibilityDelegate != null) {
7703          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7704      } else {
7705          return performAccessibilityActionInternal(action, arguments);
7706      }
7707    }
7708
7709   /**
7710    * @see #performAccessibilityAction(int, Bundle)
7711    *
7712    * Note: Called from the default {@link AccessibilityDelegate}.
7713    */
7714    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7715        switch (action) {
7716            case AccessibilityNodeInfo.ACTION_CLICK: {
7717                if (isClickable()) {
7718                    performClick();
7719                    return true;
7720                }
7721            } break;
7722            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7723                if (isLongClickable()) {
7724                    performLongClick();
7725                    return true;
7726                }
7727            } break;
7728            case AccessibilityNodeInfo.ACTION_FOCUS: {
7729                if (!hasFocus()) {
7730                    // Get out of touch mode since accessibility
7731                    // wants to move focus around.
7732                    getViewRootImpl().ensureTouchMode(false);
7733                    return requestFocus();
7734                }
7735            } break;
7736            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7737                if (hasFocus()) {
7738                    clearFocus();
7739                    return !isFocused();
7740                }
7741            } break;
7742            case AccessibilityNodeInfo.ACTION_SELECT: {
7743                if (!isSelected()) {
7744                    setSelected(true);
7745                    return isSelected();
7746                }
7747            } break;
7748            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7749                if (isSelected()) {
7750                    setSelected(false);
7751                    return !isSelected();
7752                }
7753            } break;
7754            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7755                if (!isAccessibilityFocused()) {
7756                    return requestAccessibilityFocus();
7757                }
7758            } break;
7759            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7760                if (isAccessibilityFocused()) {
7761                    clearAccessibilityFocus();
7762                    return true;
7763                }
7764            } break;
7765            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7766                if (arguments != null) {
7767                    final int granularity = arguments.getInt(
7768                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7769                    final boolean extendSelection = arguments.getBoolean(
7770                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7771                    return traverseAtGranularity(granularity, true, extendSelection);
7772                }
7773            } break;
7774            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7775                if (arguments != null) {
7776                    final int granularity = arguments.getInt(
7777                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7778                    final boolean extendSelection = arguments.getBoolean(
7779                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7780                    return traverseAtGranularity(granularity, false, extendSelection);
7781                }
7782            } break;
7783            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7784                CharSequence text = getIterableTextForAccessibility();
7785                if (text == null) {
7786                    return false;
7787                }
7788                final int start = (arguments != null) ? arguments.getInt(
7789                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7790                final int end = (arguments != null) ? arguments.getInt(
7791                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7792                // Only cursor position can be specified (selection length == 0)
7793                if ((getAccessibilitySelectionStart() != start
7794                        || getAccessibilitySelectionEnd() != end)
7795                        && (start == end)) {
7796                    setAccessibilitySelection(start, end);
7797                    notifyViewAccessibilityStateChangedIfNeeded(
7798                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7799                    return true;
7800                }
7801            } break;
7802        }
7803        return false;
7804    }
7805
7806    private boolean traverseAtGranularity(int granularity, boolean forward,
7807            boolean extendSelection) {
7808        CharSequence text = getIterableTextForAccessibility();
7809        if (text == null || text.length() == 0) {
7810            return false;
7811        }
7812        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7813        if (iterator == null) {
7814            return false;
7815        }
7816        int current = getAccessibilitySelectionEnd();
7817        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7818            current = forward ? 0 : text.length();
7819        }
7820        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7821        if (range == null) {
7822            return false;
7823        }
7824        final int segmentStart = range[0];
7825        final int segmentEnd = range[1];
7826        int selectionStart;
7827        int selectionEnd;
7828        if (extendSelection && isAccessibilitySelectionExtendable()) {
7829            selectionStart = getAccessibilitySelectionStart();
7830            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7831                selectionStart = forward ? segmentStart : segmentEnd;
7832            }
7833            selectionEnd = forward ? segmentEnd : segmentStart;
7834        } else {
7835            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7836        }
7837        setAccessibilitySelection(selectionStart, selectionEnd);
7838        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7839                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7840        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7841        return true;
7842    }
7843
7844    /**
7845     * Gets the text reported for accessibility purposes.
7846     *
7847     * @return The accessibility text.
7848     *
7849     * @hide
7850     */
7851    public CharSequence getIterableTextForAccessibility() {
7852        return getContentDescription();
7853    }
7854
7855    /**
7856     * Gets whether accessibility selection can be extended.
7857     *
7858     * @return If selection is extensible.
7859     *
7860     * @hide
7861     */
7862    public boolean isAccessibilitySelectionExtendable() {
7863        return false;
7864    }
7865
7866    /**
7867     * @hide
7868     */
7869    public int getAccessibilitySelectionStart() {
7870        return mAccessibilityCursorPosition;
7871    }
7872
7873    /**
7874     * @hide
7875     */
7876    public int getAccessibilitySelectionEnd() {
7877        return getAccessibilitySelectionStart();
7878    }
7879
7880    /**
7881     * @hide
7882     */
7883    public void setAccessibilitySelection(int start, int end) {
7884        if (start ==  end && end == mAccessibilityCursorPosition) {
7885            return;
7886        }
7887        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7888            mAccessibilityCursorPosition = start;
7889        } else {
7890            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7891        }
7892        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7893    }
7894
7895    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7896            int fromIndex, int toIndex) {
7897        if (mParent == null) {
7898            return;
7899        }
7900        AccessibilityEvent event = AccessibilityEvent.obtain(
7901                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7902        onInitializeAccessibilityEvent(event);
7903        onPopulateAccessibilityEvent(event);
7904        event.setFromIndex(fromIndex);
7905        event.setToIndex(toIndex);
7906        event.setAction(action);
7907        event.setMovementGranularity(granularity);
7908        mParent.requestSendAccessibilityEvent(this, event);
7909    }
7910
7911    /**
7912     * @hide
7913     */
7914    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7915        switch (granularity) {
7916            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7917                CharSequence text = getIterableTextForAccessibility();
7918                if (text != null && text.length() > 0) {
7919                    CharacterTextSegmentIterator iterator =
7920                        CharacterTextSegmentIterator.getInstance(
7921                                mContext.getResources().getConfiguration().locale);
7922                    iterator.initialize(text.toString());
7923                    return iterator;
7924                }
7925            } break;
7926            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7927                CharSequence text = getIterableTextForAccessibility();
7928                if (text != null && text.length() > 0) {
7929                    WordTextSegmentIterator iterator =
7930                        WordTextSegmentIterator.getInstance(
7931                                mContext.getResources().getConfiguration().locale);
7932                    iterator.initialize(text.toString());
7933                    return iterator;
7934                }
7935            } break;
7936            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7937                CharSequence text = getIterableTextForAccessibility();
7938                if (text != null && text.length() > 0) {
7939                    ParagraphTextSegmentIterator iterator =
7940                        ParagraphTextSegmentIterator.getInstance();
7941                    iterator.initialize(text.toString());
7942                    return iterator;
7943                }
7944            } break;
7945        }
7946        return null;
7947    }
7948
7949    /**
7950     * @hide
7951     */
7952    public void dispatchStartTemporaryDetach() {
7953        onStartTemporaryDetach();
7954    }
7955
7956    /**
7957     * This is called when a container is going to temporarily detach a child, with
7958     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7959     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7960     * {@link #onDetachedFromWindow()} when the container is done.
7961     */
7962    public void onStartTemporaryDetach() {
7963        removeUnsetPressCallback();
7964        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7965    }
7966
7967    /**
7968     * @hide
7969     */
7970    public void dispatchFinishTemporaryDetach() {
7971        onFinishTemporaryDetach();
7972    }
7973
7974    /**
7975     * Called after {@link #onStartTemporaryDetach} when the container is done
7976     * changing the view.
7977     */
7978    public void onFinishTemporaryDetach() {
7979    }
7980
7981    /**
7982     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7983     * for this view's window.  Returns null if the view is not currently attached
7984     * to the window.  Normally you will not need to use this directly, but
7985     * just use the standard high-level event callbacks like
7986     * {@link #onKeyDown(int, KeyEvent)}.
7987     */
7988    public KeyEvent.DispatcherState getKeyDispatcherState() {
7989        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7990    }
7991
7992    /**
7993     * Dispatch a key event before it is processed by any input method
7994     * associated with the view hierarchy.  This can be used to intercept
7995     * key events in special situations before the IME consumes them; a
7996     * typical example would be handling the BACK key to update the application's
7997     * UI instead of allowing the IME to see it and close itself.
7998     *
7999     * @param event The key event to be dispatched.
8000     * @return True if the event was handled, false otherwise.
8001     */
8002    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8003        return onKeyPreIme(event.getKeyCode(), event);
8004    }
8005
8006    /**
8007     * Dispatch a key event to the next view on the focus path. This path runs
8008     * from the top of the view tree down to the currently focused view. If this
8009     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8010     * the next node down the focus path. This method also fires any key
8011     * listeners.
8012     *
8013     * @param event The key event to be dispatched.
8014     * @return True if the event was handled, false otherwise.
8015     */
8016    public boolean dispatchKeyEvent(KeyEvent event) {
8017        if (mInputEventConsistencyVerifier != null) {
8018            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8019        }
8020
8021        // Give any attached key listener a first crack at the event.
8022        //noinspection SimplifiableIfStatement
8023        ListenerInfo li = mListenerInfo;
8024        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8025                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8026            return true;
8027        }
8028
8029        if (event.dispatch(this, mAttachInfo != null
8030                ? mAttachInfo.mKeyDispatchState : null, this)) {
8031            return true;
8032        }
8033
8034        if (mInputEventConsistencyVerifier != null) {
8035            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8036        }
8037        return false;
8038    }
8039
8040    /**
8041     * Dispatches a key shortcut event.
8042     *
8043     * @param event The key event to be dispatched.
8044     * @return True if the event was handled by the view, false otherwise.
8045     */
8046    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8047        return onKeyShortcut(event.getKeyCode(), event);
8048    }
8049
8050    /**
8051     * Pass the touch screen motion event down to the target view, or this
8052     * view if it is the target.
8053     *
8054     * @param event The motion event to be dispatched.
8055     * @return True if the event was handled by the view, false otherwise.
8056     */
8057    public boolean dispatchTouchEvent(MotionEvent event) {
8058        boolean result = false;
8059
8060        if (mInputEventConsistencyVerifier != null) {
8061            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8062        }
8063
8064        final int actionMasked = event.getActionMasked();
8065        if (actionMasked == MotionEvent.ACTION_DOWN) {
8066            // Defensive cleanup for new gesture
8067            stopNestedScroll();
8068        }
8069
8070        if (onFilterTouchEventForSecurity(event)) {
8071            //noinspection SimplifiableIfStatement
8072            ListenerInfo li = mListenerInfo;
8073            if (li != null && li.mOnTouchListener != null
8074                    && (mViewFlags & ENABLED_MASK) == ENABLED
8075                    && li.mOnTouchListener.onTouch(this, event)) {
8076                result = true;
8077            }
8078
8079            if (!result && onTouchEvent(event)) {
8080                result = true;
8081            }
8082        }
8083
8084        if (!result && mInputEventConsistencyVerifier != null) {
8085            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8086        }
8087
8088        // Clean up after nested scrolls if this is the end of a gesture;
8089        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8090        // of the gesture.
8091        if (actionMasked == MotionEvent.ACTION_UP ||
8092                actionMasked == MotionEvent.ACTION_CANCEL ||
8093                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8094            stopNestedScroll();
8095        }
8096
8097        return result;
8098    }
8099
8100    /**
8101     * Filter the touch event to apply security policies.
8102     *
8103     * @param event The motion event to be filtered.
8104     * @return True if the event should be dispatched, false if the event should be dropped.
8105     *
8106     * @see #getFilterTouchesWhenObscured
8107     */
8108    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8109        //noinspection RedundantIfStatement
8110        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8111                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8112            // Window is obscured, drop this touch.
8113            return false;
8114        }
8115        return true;
8116    }
8117
8118    /**
8119     * Pass a trackball motion event down to the focused view.
8120     *
8121     * @param event The motion event to be dispatched.
8122     * @return True if the event was handled by the view, false otherwise.
8123     */
8124    public boolean dispatchTrackballEvent(MotionEvent event) {
8125        if (mInputEventConsistencyVerifier != null) {
8126            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8127        }
8128
8129        return onTrackballEvent(event);
8130    }
8131
8132    /**
8133     * Dispatch a generic motion event.
8134     * <p>
8135     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8136     * are delivered to the view under the pointer.  All other generic motion events are
8137     * delivered to the focused view.  Hover events are handled specially and are delivered
8138     * to {@link #onHoverEvent(MotionEvent)}.
8139     * </p>
8140     *
8141     * @param event The motion event to be dispatched.
8142     * @return True if the event was handled by the view, false otherwise.
8143     */
8144    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8145        if (mInputEventConsistencyVerifier != null) {
8146            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8147        }
8148
8149        final int source = event.getSource();
8150        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8151            final int action = event.getAction();
8152            if (action == MotionEvent.ACTION_HOVER_ENTER
8153                    || action == MotionEvent.ACTION_HOVER_MOVE
8154                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8155                if (dispatchHoverEvent(event)) {
8156                    return true;
8157                }
8158            } else if (dispatchGenericPointerEvent(event)) {
8159                return true;
8160            }
8161        } else if (dispatchGenericFocusedEvent(event)) {
8162            return true;
8163        }
8164
8165        if (dispatchGenericMotionEventInternal(event)) {
8166            return true;
8167        }
8168
8169        if (mInputEventConsistencyVerifier != null) {
8170            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8171        }
8172        return false;
8173    }
8174
8175    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8176        //noinspection SimplifiableIfStatement
8177        ListenerInfo li = mListenerInfo;
8178        if (li != null && li.mOnGenericMotionListener != null
8179                && (mViewFlags & ENABLED_MASK) == ENABLED
8180                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8181            return true;
8182        }
8183
8184        if (onGenericMotionEvent(event)) {
8185            return true;
8186        }
8187
8188        if (mInputEventConsistencyVerifier != null) {
8189            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8190        }
8191        return false;
8192    }
8193
8194    /**
8195     * Dispatch a hover event.
8196     * <p>
8197     * Do not call this method directly.
8198     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8199     * </p>
8200     *
8201     * @param event The motion event to be dispatched.
8202     * @return True if the event was handled by the view, false otherwise.
8203     */
8204    protected boolean dispatchHoverEvent(MotionEvent event) {
8205        ListenerInfo li = mListenerInfo;
8206        //noinspection SimplifiableIfStatement
8207        if (li != null && li.mOnHoverListener != null
8208                && (mViewFlags & ENABLED_MASK) == ENABLED
8209                && li.mOnHoverListener.onHover(this, event)) {
8210            return true;
8211        }
8212
8213        return onHoverEvent(event);
8214    }
8215
8216    /**
8217     * Returns true if the view has a child to which it has recently sent
8218     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8219     * it does not have a hovered child, then it must be the innermost hovered view.
8220     * @hide
8221     */
8222    protected boolean hasHoveredChild() {
8223        return false;
8224    }
8225
8226    /**
8227     * Dispatch a generic motion event to the view under the first pointer.
8228     * <p>
8229     * Do not call this method directly.
8230     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8231     * </p>
8232     *
8233     * @param event The motion event to be dispatched.
8234     * @return True if the event was handled by the view, false otherwise.
8235     */
8236    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8237        return false;
8238    }
8239
8240    /**
8241     * Dispatch a generic motion event to the currently focused view.
8242     * <p>
8243     * Do not call this method directly.
8244     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8245     * </p>
8246     *
8247     * @param event The motion event to be dispatched.
8248     * @return True if the event was handled by the view, false otherwise.
8249     */
8250    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8251        return false;
8252    }
8253
8254    /**
8255     * Dispatch a pointer event.
8256     * <p>
8257     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8258     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8259     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8260     * and should not be expected to handle other pointing device features.
8261     * </p>
8262     *
8263     * @param event The motion event to be dispatched.
8264     * @return True if the event was handled by the view, false otherwise.
8265     * @hide
8266     */
8267    public final boolean dispatchPointerEvent(MotionEvent event) {
8268        if (event.isTouchEvent()) {
8269            return dispatchTouchEvent(event);
8270        } else {
8271            return dispatchGenericMotionEvent(event);
8272        }
8273    }
8274
8275    /**
8276     * Called when the window containing this view gains or loses window focus.
8277     * ViewGroups should override to route to their children.
8278     *
8279     * @param hasFocus True if the window containing this view now has focus,
8280     *        false otherwise.
8281     */
8282    public void dispatchWindowFocusChanged(boolean hasFocus) {
8283        onWindowFocusChanged(hasFocus);
8284    }
8285
8286    /**
8287     * Called when the window containing this view gains or loses focus.  Note
8288     * that this is separate from view focus: to receive key events, both
8289     * your view and its window must have focus.  If a window is displayed
8290     * on top of yours that takes input focus, then your own window will lose
8291     * focus but the view focus will remain unchanged.
8292     *
8293     * @param hasWindowFocus True if the window containing this view now has
8294     *        focus, false otherwise.
8295     */
8296    public void onWindowFocusChanged(boolean hasWindowFocus) {
8297        InputMethodManager imm = InputMethodManager.peekInstance();
8298        if (!hasWindowFocus) {
8299            if (isPressed()) {
8300                setPressed(false);
8301            }
8302            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8303                imm.focusOut(this);
8304            }
8305            removeLongPressCallback();
8306            removeTapCallback();
8307            onFocusLost();
8308        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8309            imm.focusIn(this);
8310        }
8311        refreshDrawableState();
8312    }
8313
8314    /**
8315     * Returns true if this view is in a window that currently has window focus.
8316     * Note that this is not the same as the view itself having focus.
8317     *
8318     * @return True if this view is in a window that currently has window focus.
8319     */
8320    public boolean hasWindowFocus() {
8321        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8322    }
8323
8324    /**
8325     * Dispatch a view visibility change down the view hierarchy.
8326     * ViewGroups should override to route to their children.
8327     * @param changedView The view whose visibility changed. Could be 'this' or
8328     * an ancestor view.
8329     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8330     * {@link #INVISIBLE} or {@link #GONE}.
8331     */
8332    protected void dispatchVisibilityChanged(@NonNull View changedView,
8333            @Visibility int visibility) {
8334        onVisibilityChanged(changedView, visibility);
8335    }
8336
8337    /**
8338     * Called when the visibility of the view or an ancestor of the view is changed.
8339     * @param changedView The view whose visibility changed. Could be 'this' or
8340     * an ancestor view.
8341     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8342     * {@link #INVISIBLE} or {@link #GONE}.
8343     */
8344    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8345        if (visibility == VISIBLE) {
8346            if (mAttachInfo != null) {
8347                initialAwakenScrollBars();
8348            } else {
8349                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8350            }
8351        }
8352    }
8353
8354    /**
8355     * Dispatch a hint about whether this view is displayed. For instance, when
8356     * a View moves out of the screen, it might receives a display hint indicating
8357     * the view is not displayed. Applications should not <em>rely</em> on this hint
8358     * as there is no guarantee that they will receive one.
8359     *
8360     * @param hint A hint about whether or not this view is displayed:
8361     * {@link #VISIBLE} or {@link #INVISIBLE}.
8362     */
8363    public void dispatchDisplayHint(@Visibility int hint) {
8364        onDisplayHint(hint);
8365    }
8366
8367    /**
8368     * Gives this view a hint about whether is displayed or not. For instance, when
8369     * a View moves out of the screen, it might receives a display hint indicating
8370     * the view is not displayed. Applications should not <em>rely</em> on this hint
8371     * as there is no guarantee that they will receive one.
8372     *
8373     * @param hint A hint about whether or not this view is displayed:
8374     * {@link #VISIBLE} or {@link #INVISIBLE}.
8375     */
8376    protected void onDisplayHint(@Visibility int hint) {
8377    }
8378
8379    /**
8380     * Dispatch a window visibility change down the view hierarchy.
8381     * ViewGroups should override to route to their children.
8382     *
8383     * @param visibility The new visibility of the window.
8384     *
8385     * @see #onWindowVisibilityChanged(int)
8386     */
8387    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8388        onWindowVisibilityChanged(visibility);
8389    }
8390
8391    /**
8392     * Called when the window containing has change its visibility
8393     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8394     * that this tells you whether or not your window is being made visible
8395     * to the window manager; this does <em>not</em> tell you whether or not
8396     * your window is obscured by other windows on the screen, even if it
8397     * is itself visible.
8398     *
8399     * @param visibility The new visibility of the window.
8400     */
8401    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8402        if (visibility == VISIBLE) {
8403            initialAwakenScrollBars();
8404        }
8405    }
8406
8407    /**
8408     * Returns the current visibility of the window this view is attached to
8409     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8410     *
8411     * @return Returns the current visibility of the view's window.
8412     */
8413    @Visibility
8414    public int getWindowVisibility() {
8415        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8416    }
8417
8418    /**
8419     * Retrieve the overall visible display size in which the window this view is
8420     * attached to has been positioned in.  This takes into account screen
8421     * decorations above the window, for both cases where the window itself
8422     * is being position inside of them or the window is being placed under
8423     * then and covered insets are used for the window to position its content
8424     * inside.  In effect, this tells you the available area where content can
8425     * be placed and remain visible to users.
8426     *
8427     * <p>This function requires an IPC back to the window manager to retrieve
8428     * the requested information, so should not be used in performance critical
8429     * code like drawing.
8430     *
8431     * @param outRect Filled in with the visible display frame.  If the view
8432     * is not attached to a window, this is simply the raw display size.
8433     */
8434    public void getWindowVisibleDisplayFrame(Rect outRect) {
8435        if (mAttachInfo != null) {
8436            try {
8437                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8438            } catch (RemoteException e) {
8439                return;
8440            }
8441            // XXX This is really broken, and probably all needs to be done
8442            // in the window manager, and we need to know more about whether
8443            // we want the area behind or in front of the IME.
8444            final Rect insets = mAttachInfo.mVisibleInsets;
8445            outRect.left += insets.left;
8446            outRect.top += insets.top;
8447            outRect.right -= insets.right;
8448            outRect.bottom -= insets.bottom;
8449            return;
8450        }
8451        // The view is not attached to a display so we don't have a context.
8452        // Make a best guess about the display size.
8453        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8454        d.getRectSize(outRect);
8455    }
8456
8457    /**
8458     * Dispatch a notification about a resource configuration change down
8459     * the view hierarchy.
8460     * ViewGroups should override to route to their children.
8461     *
8462     * @param newConfig The new resource configuration.
8463     *
8464     * @see #onConfigurationChanged(android.content.res.Configuration)
8465     */
8466    public void dispatchConfigurationChanged(Configuration newConfig) {
8467        onConfigurationChanged(newConfig);
8468    }
8469
8470    /**
8471     * Called when the current configuration of the resources being used
8472     * by the application have changed.  You can use this to decide when
8473     * to reload resources that can changed based on orientation and other
8474     * configuration characterstics.  You only need to use this if you are
8475     * not relying on the normal {@link android.app.Activity} mechanism of
8476     * recreating the activity instance upon a configuration change.
8477     *
8478     * @param newConfig The new resource configuration.
8479     */
8480    protected void onConfigurationChanged(Configuration newConfig) {
8481    }
8482
8483    /**
8484     * Private function to aggregate all per-view attributes in to the view
8485     * root.
8486     */
8487    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8488        performCollectViewAttributes(attachInfo, visibility);
8489    }
8490
8491    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8492        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8493            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8494                attachInfo.mKeepScreenOn = true;
8495            }
8496            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8497            ListenerInfo li = mListenerInfo;
8498            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8499                attachInfo.mHasSystemUiListeners = true;
8500            }
8501        }
8502    }
8503
8504    void needGlobalAttributesUpdate(boolean force) {
8505        final AttachInfo ai = mAttachInfo;
8506        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8507            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8508                    || ai.mHasSystemUiListeners) {
8509                ai.mRecomputeGlobalAttributes = true;
8510            }
8511        }
8512    }
8513
8514    /**
8515     * Returns whether the device is currently in touch mode.  Touch mode is entered
8516     * once the user begins interacting with the device by touch, and affects various
8517     * things like whether focus is always visible to the user.
8518     *
8519     * @return Whether the device is in touch mode.
8520     */
8521    @ViewDebug.ExportedProperty
8522    public boolean isInTouchMode() {
8523        if (mAttachInfo != null) {
8524            return mAttachInfo.mInTouchMode;
8525        } else {
8526            return ViewRootImpl.isInTouchMode();
8527        }
8528    }
8529
8530    /**
8531     * Returns the context the view is running in, through which it can
8532     * access the current theme, resources, etc.
8533     *
8534     * @return The view's Context.
8535     */
8536    @ViewDebug.CapturedViewProperty
8537    public final Context getContext() {
8538        return mContext;
8539    }
8540
8541    /**
8542     * Handle a key event before it is processed by any input method
8543     * associated with the view hierarchy.  This can be used to intercept
8544     * key events in special situations before the IME consumes them; a
8545     * typical example would be handling the BACK key to update the application's
8546     * UI instead of allowing the IME to see it and close itself.
8547     *
8548     * @param keyCode The value in event.getKeyCode().
8549     * @param event Description of the key event.
8550     * @return If you handled the event, return true. If you want to allow the
8551     *         event to be handled by the next receiver, return false.
8552     */
8553    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8554        return false;
8555    }
8556
8557    /**
8558     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8559     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8560     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8561     * is released, if the view is enabled and clickable.
8562     *
8563     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8564     * although some may elect to do so in some situations. Do not rely on this to
8565     * catch software key presses.
8566     *
8567     * @param keyCode A key code that represents the button pressed, from
8568     *                {@link android.view.KeyEvent}.
8569     * @param event   The KeyEvent object that defines the button action.
8570     */
8571    public boolean onKeyDown(int keyCode, KeyEvent event) {
8572        boolean result = false;
8573
8574        if (KeyEvent.isConfirmKey(keyCode)) {
8575            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8576                return true;
8577            }
8578            // Long clickable items don't necessarily have to be clickable
8579            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8580                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8581                    (event.getRepeatCount() == 0)) {
8582                setPressed(true);
8583                checkForLongClick(0);
8584                return true;
8585            }
8586        }
8587        return result;
8588    }
8589
8590    /**
8591     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8592     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8593     * the event).
8594     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8595     * although some may elect to do so in some situations. Do not rely on this to
8596     * catch software key presses.
8597     */
8598    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8599        return false;
8600    }
8601
8602    /**
8603     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8604     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8605     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8606     * {@link KeyEvent#KEYCODE_ENTER} is released.
8607     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8608     * although some may elect to do so in some situations. Do not rely on this to
8609     * catch software key presses.
8610     *
8611     * @param keyCode A key code that represents the button pressed, from
8612     *                {@link android.view.KeyEvent}.
8613     * @param event   The KeyEvent object that defines the button action.
8614     */
8615    public boolean onKeyUp(int keyCode, KeyEvent event) {
8616        if (KeyEvent.isConfirmKey(keyCode)) {
8617            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8618                return true;
8619            }
8620            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8621                setPressed(false);
8622
8623                if (!mHasPerformedLongPress) {
8624                    // This is a tap, so remove the longpress check
8625                    removeLongPressCallback();
8626                    return performClick();
8627                }
8628            }
8629        }
8630        return false;
8631    }
8632
8633    /**
8634     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8635     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8636     * the event).
8637     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8638     * although some may elect to do so in some situations. Do not rely on this to
8639     * catch software key presses.
8640     *
8641     * @param keyCode     A key code that represents the button pressed, from
8642     *                    {@link android.view.KeyEvent}.
8643     * @param repeatCount The number of times the action was made.
8644     * @param event       The KeyEvent object that defines the button action.
8645     */
8646    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8647        return false;
8648    }
8649
8650    /**
8651     * Called on the focused view when a key shortcut event is not handled.
8652     * Override this method to implement local key shortcuts for the View.
8653     * Key shortcuts can also be implemented by setting the
8654     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8655     *
8656     * @param keyCode The value in event.getKeyCode().
8657     * @param event Description of the key event.
8658     * @return If you handled the event, return true. If you want to allow the
8659     *         event to be handled by the next receiver, return false.
8660     */
8661    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8662        return false;
8663    }
8664
8665    /**
8666     * Check whether the called view is a text editor, in which case it
8667     * would make sense to automatically display a soft input window for
8668     * it.  Subclasses should override this if they implement
8669     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8670     * a call on that method would return a non-null InputConnection, and
8671     * they are really a first-class editor that the user would normally
8672     * start typing on when the go into a window containing your view.
8673     *
8674     * <p>The default implementation always returns false.  This does
8675     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8676     * will not be called or the user can not otherwise perform edits on your
8677     * view; it is just a hint to the system that this is not the primary
8678     * purpose of this view.
8679     *
8680     * @return Returns true if this view is a text editor, else false.
8681     */
8682    public boolean onCheckIsTextEditor() {
8683        return false;
8684    }
8685
8686    /**
8687     * Create a new InputConnection for an InputMethod to interact
8688     * with the view.  The default implementation returns null, since it doesn't
8689     * support input methods.  You can override this to implement such support.
8690     * This is only needed for views that take focus and text input.
8691     *
8692     * <p>When implementing this, you probably also want to implement
8693     * {@link #onCheckIsTextEditor()} to indicate you will return a
8694     * non-null InputConnection.</p>
8695     *
8696     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8697     * object correctly and in its entirety, so that the connected IME can rely
8698     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8699     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8700     * must be filled in with the correct cursor position for IMEs to work correctly
8701     * with your application.</p>
8702     *
8703     * @param outAttrs Fill in with attribute information about the connection.
8704     */
8705    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8706        return null;
8707    }
8708
8709    /**
8710     * Called by the {@link android.view.inputmethod.InputMethodManager}
8711     * when a view who is not the current
8712     * input connection target is trying to make a call on the manager.  The
8713     * default implementation returns false; you can override this to return
8714     * true for certain views if you are performing InputConnection proxying
8715     * to them.
8716     * @param view The View that is making the InputMethodManager call.
8717     * @return Return true to allow the call, false to reject.
8718     */
8719    public boolean checkInputConnectionProxy(View view) {
8720        return false;
8721    }
8722
8723    /**
8724     * Show the context menu for this view. It is not safe to hold on to the
8725     * menu after returning from this method.
8726     *
8727     * You should normally not overload this method. Overload
8728     * {@link #onCreateContextMenu(ContextMenu)} or define an
8729     * {@link OnCreateContextMenuListener} to add items to the context menu.
8730     *
8731     * @param menu The context menu to populate
8732     */
8733    public void createContextMenu(ContextMenu menu) {
8734        ContextMenuInfo menuInfo = getContextMenuInfo();
8735
8736        // Sets the current menu info so all items added to menu will have
8737        // my extra info set.
8738        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8739
8740        onCreateContextMenu(menu);
8741        ListenerInfo li = mListenerInfo;
8742        if (li != null && li.mOnCreateContextMenuListener != null) {
8743            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8744        }
8745
8746        // Clear the extra information so subsequent items that aren't mine don't
8747        // have my extra info.
8748        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8749
8750        if (mParent != null) {
8751            mParent.createContextMenu(menu);
8752        }
8753    }
8754
8755    /**
8756     * Views should implement this if they have extra information to associate
8757     * with the context menu. The return result is supplied as a parameter to
8758     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8759     * callback.
8760     *
8761     * @return Extra information about the item for which the context menu
8762     *         should be shown. This information will vary across different
8763     *         subclasses of View.
8764     */
8765    protected ContextMenuInfo getContextMenuInfo() {
8766        return null;
8767    }
8768
8769    /**
8770     * Views should implement this if the view itself is going to add items to
8771     * the context menu.
8772     *
8773     * @param menu the context menu to populate
8774     */
8775    protected void onCreateContextMenu(ContextMenu menu) {
8776    }
8777
8778    /**
8779     * Implement this method to handle trackball motion events.  The
8780     * <em>relative</em> movement of the trackball since the last event
8781     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8782     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8783     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8784     * they will often be fractional values, representing the more fine-grained
8785     * movement information available from a trackball).
8786     *
8787     * @param event The motion event.
8788     * @return True if the event was handled, false otherwise.
8789     */
8790    public boolean onTrackballEvent(MotionEvent event) {
8791        return false;
8792    }
8793
8794    /**
8795     * Implement this method to handle generic motion events.
8796     * <p>
8797     * Generic motion events describe joystick movements, mouse hovers, track pad
8798     * touches, scroll wheel movements and other input events.  The
8799     * {@link MotionEvent#getSource() source} of the motion event specifies
8800     * the class of input that was received.  Implementations of this method
8801     * must examine the bits in the source before processing the event.
8802     * The following code example shows how this is done.
8803     * </p><p>
8804     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8805     * are delivered to the view under the pointer.  All other generic motion events are
8806     * delivered to the focused view.
8807     * </p>
8808     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8809     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8810     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8811     *             // process the joystick movement...
8812     *             return true;
8813     *         }
8814     *     }
8815     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8816     *         switch (event.getAction()) {
8817     *             case MotionEvent.ACTION_HOVER_MOVE:
8818     *                 // process the mouse hover movement...
8819     *                 return true;
8820     *             case MotionEvent.ACTION_SCROLL:
8821     *                 // process the scroll wheel movement...
8822     *                 return true;
8823     *         }
8824     *     }
8825     *     return super.onGenericMotionEvent(event);
8826     * }</pre>
8827     *
8828     * @param event The generic motion event being processed.
8829     * @return True if the event was handled, false otherwise.
8830     */
8831    public boolean onGenericMotionEvent(MotionEvent event) {
8832        return false;
8833    }
8834
8835    /**
8836     * Implement this method to handle hover events.
8837     * <p>
8838     * This method is called whenever a pointer is hovering into, over, or out of the
8839     * bounds of a view and the view is not currently being touched.
8840     * Hover events are represented as pointer events with action
8841     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8842     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8843     * </p>
8844     * <ul>
8845     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8846     * when the pointer enters the bounds of the view.</li>
8847     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8848     * when the pointer has already entered the bounds of the view and has moved.</li>
8849     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8850     * when the pointer has exited the bounds of the view or when the pointer is
8851     * about to go down due to a button click, tap, or similar user action that
8852     * causes the view to be touched.</li>
8853     * </ul>
8854     * <p>
8855     * The view should implement this method to return true to indicate that it is
8856     * handling the hover event, such as by changing its drawable state.
8857     * </p><p>
8858     * The default implementation calls {@link #setHovered} to update the hovered state
8859     * of the view when a hover enter or hover exit event is received, if the view
8860     * is enabled and is clickable.  The default implementation also sends hover
8861     * accessibility events.
8862     * </p>
8863     *
8864     * @param event The motion event that describes the hover.
8865     * @return True if the view handled the hover event.
8866     *
8867     * @see #isHovered
8868     * @see #setHovered
8869     * @see #onHoverChanged
8870     */
8871    public boolean onHoverEvent(MotionEvent event) {
8872        // The root view may receive hover (or touch) events that are outside the bounds of
8873        // the window.  This code ensures that we only send accessibility events for
8874        // hovers that are actually within the bounds of the root view.
8875        final int action = event.getActionMasked();
8876        if (!mSendingHoverAccessibilityEvents) {
8877            if ((action == MotionEvent.ACTION_HOVER_ENTER
8878                    || action == MotionEvent.ACTION_HOVER_MOVE)
8879                    && !hasHoveredChild()
8880                    && pointInView(event.getX(), event.getY())) {
8881                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8882                mSendingHoverAccessibilityEvents = true;
8883            }
8884        } else {
8885            if (action == MotionEvent.ACTION_HOVER_EXIT
8886                    || (action == MotionEvent.ACTION_MOVE
8887                            && !pointInView(event.getX(), event.getY()))) {
8888                mSendingHoverAccessibilityEvents = false;
8889                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8890            }
8891        }
8892
8893        if (isHoverable()) {
8894            switch (action) {
8895                case MotionEvent.ACTION_HOVER_ENTER:
8896                    setHovered(true);
8897                    break;
8898                case MotionEvent.ACTION_HOVER_EXIT:
8899                    setHovered(false);
8900                    break;
8901            }
8902
8903            // Dispatch the event to onGenericMotionEvent before returning true.
8904            // This is to provide compatibility with existing applications that
8905            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8906            // break because of the new default handling for hoverable views
8907            // in onHoverEvent.
8908            // Note that onGenericMotionEvent will be called by default when
8909            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8910            dispatchGenericMotionEventInternal(event);
8911            // The event was already handled by calling setHovered(), so always
8912            // return true.
8913            return true;
8914        }
8915
8916        return false;
8917    }
8918
8919    /**
8920     * Returns true if the view should handle {@link #onHoverEvent}
8921     * by calling {@link #setHovered} to change its hovered state.
8922     *
8923     * @return True if the view is hoverable.
8924     */
8925    private boolean isHoverable() {
8926        final int viewFlags = mViewFlags;
8927        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8928            return false;
8929        }
8930
8931        return (viewFlags & CLICKABLE) == CLICKABLE
8932                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8933    }
8934
8935    /**
8936     * Returns true if the view is currently hovered.
8937     *
8938     * @return True if the view is currently hovered.
8939     *
8940     * @see #setHovered
8941     * @see #onHoverChanged
8942     */
8943    @ViewDebug.ExportedProperty
8944    public boolean isHovered() {
8945        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8946    }
8947
8948    /**
8949     * Sets whether the view is currently hovered.
8950     * <p>
8951     * Calling this method also changes the drawable state of the view.  This
8952     * enables the view to react to hover by using different drawable resources
8953     * to change its appearance.
8954     * </p><p>
8955     * The {@link #onHoverChanged} method is called when the hovered state changes.
8956     * </p>
8957     *
8958     * @param hovered True if the view is hovered.
8959     *
8960     * @see #isHovered
8961     * @see #onHoverChanged
8962     */
8963    public void setHovered(boolean hovered) {
8964        if (hovered) {
8965            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8966                mPrivateFlags |= PFLAG_HOVERED;
8967                refreshDrawableState();
8968                onHoverChanged(true);
8969            }
8970        } else {
8971            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8972                mPrivateFlags &= ~PFLAG_HOVERED;
8973                refreshDrawableState();
8974                onHoverChanged(false);
8975            }
8976        }
8977    }
8978
8979    /**
8980     * Implement this method to handle hover state changes.
8981     * <p>
8982     * This method is called whenever the hover state changes as a result of a
8983     * call to {@link #setHovered}.
8984     * </p>
8985     *
8986     * @param hovered The current hover state, as returned by {@link #isHovered}.
8987     *
8988     * @see #isHovered
8989     * @see #setHovered
8990     */
8991    public void onHoverChanged(boolean hovered) {
8992    }
8993
8994    /**
8995     * Implement this method to handle touch screen motion events.
8996     * <p>
8997     * If this method is used to detect click actions, it is recommended that
8998     * the actions be performed by implementing and calling
8999     * {@link #performClick()}. This will ensure consistent system behavior,
9000     * including:
9001     * <ul>
9002     * <li>obeying click sound preferences
9003     * <li>dispatching OnClickListener calls
9004     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9005     * accessibility features are enabled
9006     * </ul>
9007     *
9008     * @param event The motion event.
9009     * @return True if the event was handled, false otherwise.
9010     */
9011    public boolean onTouchEvent(MotionEvent event) {
9012        final float x = event.getX();
9013        final float y = event.getY();
9014        final int viewFlags = mViewFlags;
9015
9016        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9017            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9018                setPressed(false);
9019            }
9020            // A disabled view that is clickable still consumes the touch
9021            // events, it just doesn't respond to them.
9022            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9023                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9024        }
9025
9026        if (mTouchDelegate != null) {
9027            if (mTouchDelegate.onTouchEvent(event)) {
9028                return true;
9029            }
9030        }
9031
9032        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9033                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9034            switch (event.getAction()) {
9035                case MotionEvent.ACTION_UP:
9036                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9037                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9038                        // take focus if we don't have it already and we should in
9039                        // touch mode.
9040                        boolean focusTaken = false;
9041                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9042                            focusTaken = requestFocus();
9043                        }
9044
9045                        if (prepressed) {
9046                            // The button is being released before we actually
9047                            // showed it as pressed.  Make it show the pressed
9048                            // state now (before scheduling the click) to ensure
9049                            // the user sees it.
9050                            setPressed(true, x, y);
9051                       }
9052
9053                        if (!mHasPerformedLongPress) {
9054                            // This is a tap, so remove the longpress check
9055                            removeLongPressCallback();
9056
9057                            // Only perform take click actions if we were in the pressed state
9058                            if (!focusTaken) {
9059                                // Use a Runnable and post this rather than calling
9060                                // performClick directly. This lets other visual state
9061                                // of the view update before click actions start.
9062                                if (mPerformClick == null) {
9063                                    mPerformClick = new PerformClick();
9064                                }
9065                                if (!post(mPerformClick)) {
9066                                    performClick();
9067                                }
9068                            }
9069                        }
9070
9071                        if (mUnsetPressedState == null) {
9072                            mUnsetPressedState = new UnsetPressedState();
9073                        }
9074
9075                        if (prepressed) {
9076                            postDelayed(mUnsetPressedState,
9077                                    ViewConfiguration.getPressedStateDuration());
9078                        } else if (!post(mUnsetPressedState)) {
9079                            // If the post failed, unpress right now
9080                            mUnsetPressedState.run();
9081                        }
9082
9083                        removeTapCallback();
9084                    }
9085                    break;
9086
9087                case MotionEvent.ACTION_DOWN:
9088                    mHasPerformedLongPress = false;
9089
9090                    if (performButtonActionOnTouchDown(event)) {
9091                        break;
9092                    }
9093
9094                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9095                    boolean isInScrollingContainer = isInScrollingContainer();
9096
9097                    // For views inside a scrolling container, delay the pressed feedback for
9098                    // a short period in case this is a scroll.
9099                    if (isInScrollingContainer) {
9100                        mPrivateFlags |= PFLAG_PREPRESSED;
9101                        if (mPendingCheckForTap == null) {
9102                            mPendingCheckForTap = new CheckForTap();
9103                        }
9104                        mPendingCheckForTap.x = event.getX();
9105                        mPendingCheckForTap.y = event.getY();
9106                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9107                    } else {
9108                        // Not inside a scrolling container, so show the feedback right away
9109                        setHotspot(x, y);
9110                        setPressed(true);
9111                        checkForLongClick(0);
9112                    }
9113                    break;
9114
9115                case MotionEvent.ACTION_CANCEL:
9116                    setPressed(false);
9117                    removeTapCallback();
9118                    removeLongPressCallback();
9119                    break;
9120
9121                case MotionEvent.ACTION_MOVE:
9122                    setHotspot(x, y);
9123
9124                    // Be lenient about moving outside of buttons
9125                    if (!pointInView(x, y, mTouchSlop)) {
9126                        // Outside button
9127                        removeTapCallback();
9128                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9129                            // Remove any future long press/tap checks
9130                            removeLongPressCallback();
9131
9132                            setPressed(false);
9133                        }
9134                    }
9135                    break;
9136            }
9137
9138            return true;
9139        }
9140
9141        return false;
9142    }
9143
9144    private void setHotspot(float x, float y) {
9145        if (mBackground != null) {
9146            mBackground.setHotspot(x, y);
9147        }
9148    }
9149
9150    /**
9151     * @hide
9152     */
9153    public boolean isInScrollingContainer() {
9154        ViewParent p = getParent();
9155        while (p != null && p instanceof ViewGroup) {
9156            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9157                return true;
9158            }
9159            p = p.getParent();
9160        }
9161        return false;
9162    }
9163
9164    /**
9165     * Remove the longpress detection timer.
9166     */
9167    private void removeLongPressCallback() {
9168        if (mPendingCheckForLongPress != null) {
9169          removeCallbacks(mPendingCheckForLongPress);
9170        }
9171    }
9172
9173    /**
9174     * Remove the pending click action
9175     */
9176    private void removePerformClickCallback() {
9177        if (mPerformClick != null) {
9178            removeCallbacks(mPerformClick);
9179        }
9180    }
9181
9182    /**
9183     * Remove the prepress detection timer.
9184     */
9185    private void removeUnsetPressCallback() {
9186        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9187            setPressed(false);
9188            removeCallbacks(mUnsetPressedState);
9189        }
9190    }
9191
9192    /**
9193     * Remove the tap detection timer.
9194     */
9195    private void removeTapCallback() {
9196        if (mPendingCheckForTap != null) {
9197            mPrivateFlags &= ~PFLAG_PREPRESSED;
9198            removeCallbacks(mPendingCheckForTap);
9199        }
9200    }
9201
9202    /**
9203     * Cancels a pending long press.  Your subclass can use this if you
9204     * want the context menu to come up if the user presses and holds
9205     * at the same place, but you don't want it to come up if they press
9206     * and then move around enough to cause scrolling.
9207     */
9208    public void cancelLongPress() {
9209        removeLongPressCallback();
9210
9211        /*
9212         * The prepressed state handled by the tap callback is a display
9213         * construct, but the tap callback will post a long press callback
9214         * less its own timeout. Remove it here.
9215         */
9216        removeTapCallback();
9217    }
9218
9219    /**
9220     * Remove the pending callback for sending a
9221     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9222     */
9223    private void removeSendViewScrolledAccessibilityEventCallback() {
9224        if (mSendViewScrolledAccessibilityEvent != null) {
9225            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9226            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9227        }
9228    }
9229
9230    /**
9231     * Sets the TouchDelegate for this View.
9232     */
9233    public void setTouchDelegate(TouchDelegate delegate) {
9234        mTouchDelegate = delegate;
9235    }
9236
9237    /**
9238     * Gets the TouchDelegate for this View.
9239     */
9240    public TouchDelegate getTouchDelegate() {
9241        return mTouchDelegate;
9242    }
9243
9244    /**
9245     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9246     *
9247     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9248     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9249     * available. This method should only be called for touch events.
9250     *
9251     * <p class="note">This api is not intended for most applications. Buffered dispatch
9252     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9253     * streams will not improve your input latency. Side effects include: increased latency,
9254     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9255     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9256     * you.</p>
9257     */
9258    public final void requestUnbufferedDispatch(MotionEvent event) {
9259        final int action = event.getAction();
9260        if (mAttachInfo == null
9261                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9262                || !event.isTouchEvent()) {
9263            return;
9264        }
9265        mAttachInfo.mUnbufferedDispatchRequested = true;
9266    }
9267
9268    /**
9269     * Set flags controlling behavior of this view.
9270     *
9271     * @param flags Constant indicating the value which should be set
9272     * @param mask Constant indicating the bit range that should be changed
9273     */
9274    void setFlags(int flags, int mask) {
9275        final boolean accessibilityEnabled =
9276                AccessibilityManager.getInstance(mContext).isEnabled();
9277        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9278
9279        int old = mViewFlags;
9280        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9281
9282        int changed = mViewFlags ^ old;
9283        if (changed == 0) {
9284            return;
9285        }
9286        int privateFlags = mPrivateFlags;
9287
9288        /* Check if the FOCUSABLE bit has changed */
9289        if (((changed & FOCUSABLE_MASK) != 0) &&
9290                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9291            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9292                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9293                /* Give up focus if we are no longer focusable */
9294                clearFocus();
9295            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9296                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9297                /*
9298                 * Tell the view system that we are now available to take focus
9299                 * if no one else already has it.
9300                 */
9301                if (mParent != null) mParent.focusableViewAvailable(this);
9302            }
9303        }
9304
9305        final int newVisibility = flags & VISIBILITY_MASK;
9306        if (newVisibility == VISIBLE) {
9307            if ((changed & VISIBILITY_MASK) != 0) {
9308                /*
9309                 * If this view is becoming visible, invalidate it in case it changed while
9310                 * it was not visible. Marking it drawn ensures that the invalidation will
9311                 * go through.
9312                 */
9313                mPrivateFlags |= PFLAG_DRAWN;
9314                invalidate(true);
9315
9316                needGlobalAttributesUpdate(true);
9317
9318                // a view becoming visible is worth notifying the parent
9319                // about in case nothing has focus.  even if this specific view
9320                // isn't focusable, it may contain something that is, so let
9321                // the root view try to give this focus if nothing else does.
9322                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9323                    mParent.focusableViewAvailable(this);
9324                }
9325            }
9326        }
9327
9328        /* Check if the GONE bit has changed */
9329        if ((changed & GONE) != 0) {
9330            needGlobalAttributesUpdate(false);
9331            requestLayout();
9332
9333            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9334                if (hasFocus()) clearFocus();
9335                clearAccessibilityFocus();
9336                destroyDrawingCache();
9337                if (mParent instanceof View) {
9338                    // GONE views noop invalidation, so invalidate the parent
9339                    ((View) mParent).invalidate(true);
9340                }
9341                // Mark the view drawn to ensure that it gets invalidated properly the next
9342                // time it is visible and gets invalidated
9343                mPrivateFlags |= PFLAG_DRAWN;
9344            }
9345            if (mAttachInfo != null) {
9346                mAttachInfo.mViewVisibilityChanged = true;
9347            }
9348        }
9349
9350        /* Check if the VISIBLE bit has changed */
9351        if ((changed & INVISIBLE) != 0) {
9352            needGlobalAttributesUpdate(false);
9353            /*
9354             * If this view is becoming invisible, set the DRAWN flag so that
9355             * the next invalidate() will not be skipped.
9356             */
9357            mPrivateFlags |= PFLAG_DRAWN;
9358
9359            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9360                // root view becoming invisible shouldn't clear focus and accessibility focus
9361                if (getRootView() != this) {
9362                    if (hasFocus()) clearFocus();
9363                    clearAccessibilityFocus();
9364                }
9365            }
9366            if (mAttachInfo != null) {
9367                mAttachInfo.mViewVisibilityChanged = true;
9368            }
9369        }
9370
9371        if ((changed & VISIBILITY_MASK) != 0) {
9372            // If the view is invisible, cleanup its display list to free up resources
9373            if (newVisibility != VISIBLE && mAttachInfo != null) {
9374                cleanupDraw();
9375            }
9376
9377            if (mParent instanceof ViewGroup) {
9378                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9379                        (changed & VISIBILITY_MASK), newVisibility);
9380                ((View) mParent).invalidate(true);
9381            } else if (mParent != null) {
9382                mParent.invalidateChild(this, null);
9383            }
9384            dispatchVisibilityChanged(this, newVisibility);
9385
9386            notifySubtreeAccessibilityStateChangedIfNeeded();
9387        }
9388
9389        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9390            destroyDrawingCache();
9391        }
9392
9393        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9394            destroyDrawingCache();
9395            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9396            invalidateParentCaches();
9397        }
9398
9399        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9400            destroyDrawingCache();
9401            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9402        }
9403
9404        if ((changed & DRAW_MASK) != 0) {
9405            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9406                if (mBackground != null) {
9407                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9408                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9409                } else {
9410                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9411                }
9412            } else {
9413                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9414            }
9415            requestLayout();
9416            invalidate(true);
9417        }
9418
9419        if ((changed & KEEP_SCREEN_ON) != 0) {
9420            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9421                mParent.recomputeViewAttributes(this);
9422            }
9423        }
9424
9425        if (accessibilityEnabled) {
9426            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9427                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9428                if (oldIncludeForAccessibility != includeForAccessibility()) {
9429                    notifySubtreeAccessibilityStateChangedIfNeeded();
9430                } else {
9431                    notifyViewAccessibilityStateChangedIfNeeded(
9432                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9433                }
9434            } else if ((changed & ENABLED_MASK) != 0) {
9435                notifyViewAccessibilityStateChangedIfNeeded(
9436                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9437            }
9438        }
9439    }
9440
9441    /**
9442     * Change the view's z order in the tree, so it's on top of other sibling
9443     * views. This ordering change may affect layout, if the parent container
9444     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9445     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9446     * method should be followed by calls to {@link #requestLayout()} and
9447     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9448     * with the new child ordering.
9449     *
9450     * @see ViewGroup#bringChildToFront(View)
9451     */
9452    public void bringToFront() {
9453        if (mParent != null) {
9454            mParent.bringChildToFront(this);
9455        }
9456    }
9457
9458    /**
9459     * This is called in response to an internal scroll in this view (i.e., the
9460     * view scrolled its own contents). This is typically as a result of
9461     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9462     * called.
9463     *
9464     * @param l Current horizontal scroll origin.
9465     * @param t Current vertical scroll origin.
9466     * @param oldl Previous horizontal scroll origin.
9467     * @param oldt Previous vertical scroll origin.
9468     */
9469    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9470        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9471            postSendViewScrolledAccessibilityEventCallback();
9472        }
9473
9474        mBackgroundSizeChanged = true;
9475
9476        final AttachInfo ai = mAttachInfo;
9477        if (ai != null) {
9478            ai.mViewScrollChanged = true;
9479        }
9480    }
9481
9482    /**
9483     * Interface definition for a callback to be invoked when the layout bounds of a view
9484     * changes due to layout processing.
9485     */
9486    public interface OnLayoutChangeListener {
9487        /**
9488         * Called when the layout bounds of a view changes due to layout processing.
9489         *
9490         * @param v The view whose bounds have changed.
9491         * @param left The new value of the view's left property.
9492         * @param top The new value of the view's top property.
9493         * @param right The new value of the view's right property.
9494         * @param bottom The new value of the view's bottom property.
9495         * @param oldLeft The previous value of the view's left property.
9496         * @param oldTop The previous value of the view's top property.
9497         * @param oldRight The previous value of the view's right property.
9498         * @param oldBottom The previous value of the view's bottom property.
9499         */
9500        void onLayoutChange(View v, int left, int top, int right, int bottom,
9501            int oldLeft, int oldTop, int oldRight, int oldBottom);
9502    }
9503
9504    /**
9505     * This is called during layout when the size of this view has changed. If
9506     * you were just added to the view hierarchy, you're called with the old
9507     * values of 0.
9508     *
9509     * @param w Current width of this view.
9510     * @param h Current height of this view.
9511     * @param oldw Old width of this view.
9512     * @param oldh Old height of this view.
9513     */
9514    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9515    }
9516
9517    /**
9518     * Called by draw to draw the child views. This may be overridden
9519     * by derived classes to gain control just before its children are drawn
9520     * (but after its own view has been drawn).
9521     * @param canvas the canvas on which to draw the view
9522     */
9523    protected void dispatchDraw(Canvas canvas) {
9524
9525    }
9526
9527    /**
9528     * Gets the parent of this view. Note that the parent is a
9529     * ViewParent and not necessarily a View.
9530     *
9531     * @return Parent of this view.
9532     */
9533    public final ViewParent getParent() {
9534        return mParent;
9535    }
9536
9537    /**
9538     * Set the horizontal scrolled position of your view. This will cause a call to
9539     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9540     * invalidated.
9541     * @param value the x position to scroll to
9542     */
9543    public void setScrollX(int value) {
9544        scrollTo(value, mScrollY);
9545    }
9546
9547    /**
9548     * Set the vertical scrolled position of your view. This will cause a call to
9549     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9550     * invalidated.
9551     * @param value the y position to scroll to
9552     */
9553    public void setScrollY(int value) {
9554        scrollTo(mScrollX, value);
9555    }
9556
9557    /**
9558     * Return the scrolled left position of this view. This is the left edge of
9559     * the displayed part of your view. You do not need to draw any pixels
9560     * farther left, since those are outside of the frame of your view on
9561     * screen.
9562     *
9563     * @return The left edge of the displayed part of your view, in pixels.
9564     */
9565    public final int getScrollX() {
9566        return mScrollX;
9567    }
9568
9569    /**
9570     * Return the scrolled top position of this view. This is the top edge of
9571     * the displayed part of your view. You do not need to draw any pixels above
9572     * it, since those are outside of the frame of your view on screen.
9573     *
9574     * @return The top edge of the displayed part of your view, in pixels.
9575     */
9576    public final int getScrollY() {
9577        return mScrollY;
9578    }
9579
9580    /**
9581     * Return the width of the your view.
9582     *
9583     * @return The width of your view, in pixels.
9584     */
9585    @ViewDebug.ExportedProperty(category = "layout")
9586    public final int getWidth() {
9587        return mRight - mLeft;
9588    }
9589
9590    /**
9591     * Return the height of your view.
9592     *
9593     * @return The height of your view, in pixels.
9594     */
9595    @ViewDebug.ExportedProperty(category = "layout")
9596    public final int getHeight() {
9597        return mBottom - mTop;
9598    }
9599
9600    /**
9601     * Return the visible drawing bounds of your view. Fills in the output
9602     * rectangle with the values from getScrollX(), getScrollY(),
9603     * getWidth(), and getHeight(). These bounds do not account for any
9604     * transformation properties currently set on the view, such as
9605     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9606     *
9607     * @param outRect The (scrolled) drawing bounds of the view.
9608     */
9609    public void getDrawingRect(Rect outRect) {
9610        outRect.left = mScrollX;
9611        outRect.top = mScrollY;
9612        outRect.right = mScrollX + (mRight - mLeft);
9613        outRect.bottom = mScrollY + (mBottom - mTop);
9614    }
9615
9616    /**
9617     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9618     * raw width component (that is the result is masked by
9619     * {@link #MEASURED_SIZE_MASK}).
9620     *
9621     * @return The raw measured width of this view.
9622     */
9623    public final int getMeasuredWidth() {
9624        return mMeasuredWidth & MEASURED_SIZE_MASK;
9625    }
9626
9627    /**
9628     * Return the full width measurement information for this view as computed
9629     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9630     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9631     * This should be used during measurement and layout calculations only. Use
9632     * {@link #getWidth()} to see how wide a view is after layout.
9633     *
9634     * @return The measured width of this view as a bit mask.
9635     */
9636    public final int getMeasuredWidthAndState() {
9637        return mMeasuredWidth;
9638    }
9639
9640    /**
9641     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9642     * raw width component (that is the result is masked by
9643     * {@link #MEASURED_SIZE_MASK}).
9644     *
9645     * @return The raw measured height of this view.
9646     */
9647    public final int getMeasuredHeight() {
9648        return mMeasuredHeight & MEASURED_SIZE_MASK;
9649    }
9650
9651    /**
9652     * Return the full height measurement information for this view as computed
9653     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9654     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9655     * This should be used during measurement and layout calculations only. Use
9656     * {@link #getHeight()} to see how wide a view is after layout.
9657     *
9658     * @return The measured width of this view as a bit mask.
9659     */
9660    public final int getMeasuredHeightAndState() {
9661        return mMeasuredHeight;
9662    }
9663
9664    /**
9665     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9666     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9667     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9668     * and the height component is at the shifted bits
9669     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9670     */
9671    public final int getMeasuredState() {
9672        return (mMeasuredWidth&MEASURED_STATE_MASK)
9673                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9674                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9675    }
9676
9677    /**
9678     * The transform matrix of this view, which is calculated based on the current
9679     * rotation, scale, and pivot properties.
9680     *
9681     * @see #getRotation()
9682     * @see #getScaleX()
9683     * @see #getScaleY()
9684     * @see #getPivotX()
9685     * @see #getPivotY()
9686     * @return The current transform matrix for the view
9687     */
9688    public Matrix getMatrix() {
9689        ensureTransformationInfo();
9690        final Matrix matrix = mTransformationInfo.mMatrix;
9691        mRenderNode.getMatrix(matrix);
9692        return matrix;
9693    }
9694
9695    /**
9696     * Returns true if the transform matrix is the identity matrix.
9697     * Recomputes the matrix if necessary.
9698     *
9699     * @return True if the transform matrix is the identity matrix, false otherwise.
9700     */
9701    final boolean hasIdentityMatrix() {
9702        return mRenderNode.hasIdentityMatrix();
9703    }
9704
9705    void ensureTransformationInfo() {
9706        if (mTransformationInfo == null) {
9707            mTransformationInfo = new TransformationInfo();
9708        }
9709    }
9710
9711   /**
9712     * Utility method to retrieve the inverse of the current mMatrix property.
9713     * We cache the matrix to avoid recalculating it when transform properties
9714     * have not changed.
9715     *
9716     * @return The inverse of the current matrix of this view.
9717     */
9718    final Matrix getInverseMatrix() {
9719        ensureTransformationInfo();
9720        if (mTransformationInfo.mInverseMatrix == null) {
9721            mTransformationInfo.mInverseMatrix = new Matrix();
9722        }
9723        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9724        mRenderNode.getInverseMatrix(matrix);
9725        return matrix;
9726    }
9727
9728    /**
9729     * Gets the distance along the Z axis from the camera to this view.
9730     *
9731     * @see #setCameraDistance(float)
9732     *
9733     * @return The distance along the Z axis.
9734     */
9735    public float getCameraDistance() {
9736        final float dpi = mResources.getDisplayMetrics().densityDpi;
9737        return -(mRenderNode.getCameraDistance() * dpi);
9738    }
9739
9740    /**
9741     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9742     * views are drawn) from the camera to this view. The camera's distance
9743     * affects 3D transformations, for instance rotations around the X and Y
9744     * axis. If the rotationX or rotationY properties are changed and this view is
9745     * large (more than half the size of the screen), it is recommended to always
9746     * use a camera distance that's greater than the height (X axis rotation) or
9747     * the width (Y axis rotation) of this view.</p>
9748     *
9749     * <p>The distance of the camera from the view plane can have an affect on the
9750     * perspective distortion of the view when it is rotated around the x or y axis.
9751     * For example, a large distance will result in a large viewing angle, and there
9752     * will not be much perspective distortion of the view as it rotates. A short
9753     * distance may cause much more perspective distortion upon rotation, and can
9754     * also result in some drawing artifacts if the rotated view ends up partially
9755     * behind the camera (which is why the recommendation is to use a distance at
9756     * least as far as the size of the view, if the view is to be rotated.)</p>
9757     *
9758     * <p>The distance is expressed in "depth pixels." The default distance depends
9759     * on the screen density. For instance, on a medium density display, the
9760     * default distance is 1280. On a high density display, the default distance
9761     * is 1920.</p>
9762     *
9763     * <p>If you want to specify a distance that leads to visually consistent
9764     * results across various densities, use the following formula:</p>
9765     * <pre>
9766     * float scale = context.getResources().getDisplayMetrics().density;
9767     * view.setCameraDistance(distance * scale);
9768     * </pre>
9769     *
9770     * <p>The density scale factor of a high density display is 1.5,
9771     * and 1920 = 1280 * 1.5.</p>
9772     *
9773     * @param distance The distance in "depth pixels", if negative the opposite
9774     *        value is used
9775     *
9776     * @see #setRotationX(float)
9777     * @see #setRotationY(float)
9778     */
9779    public void setCameraDistance(float distance) {
9780        final float dpi = mResources.getDisplayMetrics().densityDpi;
9781
9782        invalidateViewProperty(true, false);
9783        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9784        invalidateViewProperty(false, false);
9785
9786        invalidateParentIfNeededAndWasQuickRejected();
9787    }
9788
9789    /**
9790     * The degrees that the view is rotated around the pivot point.
9791     *
9792     * @see #setRotation(float)
9793     * @see #getPivotX()
9794     * @see #getPivotY()
9795     *
9796     * @return The degrees of rotation.
9797     */
9798    @ViewDebug.ExportedProperty(category = "drawing")
9799    public float getRotation() {
9800        return mRenderNode.getRotation();
9801    }
9802
9803    /**
9804     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9805     * result in clockwise rotation.
9806     *
9807     * @param rotation The degrees of rotation.
9808     *
9809     * @see #getRotation()
9810     * @see #getPivotX()
9811     * @see #getPivotY()
9812     * @see #setRotationX(float)
9813     * @see #setRotationY(float)
9814     *
9815     * @attr ref android.R.styleable#View_rotation
9816     */
9817    public void setRotation(float rotation) {
9818        if (rotation != getRotation()) {
9819            // Double-invalidation is necessary to capture view's old and new areas
9820            invalidateViewProperty(true, false);
9821            mRenderNode.setRotation(rotation);
9822            invalidateViewProperty(false, true);
9823
9824            invalidateParentIfNeededAndWasQuickRejected();
9825            notifySubtreeAccessibilityStateChangedIfNeeded();
9826        }
9827    }
9828
9829    /**
9830     * The degrees that the view is rotated around the vertical axis through the pivot point.
9831     *
9832     * @see #getPivotX()
9833     * @see #getPivotY()
9834     * @see #setRotationY(float)
9835     *
9836     * @return The degrees of Y rotation.
9837     */
9838    @ViewDebug.ExportedProperty(category = "drawing")
9839    public float getRotationY() {
9840        return mRenderNode.getRotationY();
9841    }
9842
9843    /**
9844     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9845     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9846     * down the y axis.
9847     *
9848     * When rotating large views, it is recommended to adjust the camera distance
9849     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9850     *
9851     * @param rotationY The degrees of Y rotation.
9852     *
9853     * @see #getRotationY()
9854     * @see #getPivotX()
9855     * @see #getPivotY()
9856     * @see #setRotation(float)
9857     * @see #setRotationX(float)
9858     * @see #setCameraDistance(float)
9859     *
9860     * @attr ref android.R.styleable#View_rotationY
9861     */
9862    public void setRotationY(float rotationY) {
9863        if (rotationY != getRotationY()) {
9864            invalidateViewProperty(true, false);
9865            mRenderNode.setRotationY(rotationY);
9866            invalidateViewProperty(false, true);
9867
9868            invalidateParentIfNeededAndWasQuickRejected();
9869            notifySubtreeAccessibilityStateChangedIfNeeded();
9870        }
9871    }
9872
9873    /**
9874     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9875     *
9876     * @see #getPivotX()
9877     * @see #getPivotY()
9878     * @see #setRotationX(float)
9879     *
9880     * @return The degrees of X rotation.
9881     */
9882    @ViewDebug.ExportedProperty(category = "drawing")
9883    public float getRotationX() {
9884        return mRenderNode.getRotationX();
9885    }
9886
9887    /**
9888     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9889     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9890     * x axis.
9891     *
9892     * When rotating large views, it is recommended to adjust the camera distance
9893     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9894     *
9895     * @param rotationX The degrees of X rotation.
9896     *
9897     * @see #getRotationX()
9898     * @see #getPivotX()
9899     * @see #getPivotY()
9900     * @see #setRotation(float)
9901     * @see #setRotationY(float)
9902     * @see #setCameraDistance(float)
9903     *
9904     * @attr ref android.R.styleable#View_rotationX
9905     */
9906    public void setRotationX(float rotationX) {
9907        if (rotationX != getRotationX()) {
9908            invalidateViewProperty(true, false);
9909            mRenderNode.setRotationX(rotationX);
9910            invalidateViewProperty(false, true);
9911
9912            invalidateParentIfNeededAndWasQuickRejected();
9913            notifySubtreeAccessibilityStateChangedIfNeeded();
9914        }
9915    }
9916
9917    /**
9918     * The amount that the view is scaled in x around the pivot point, as a proportion of
9919     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9920     *
9921     * <p>By default, this is 1.0f.
9922     *
9923     * @see #getPivotX()
9924     * @see #getPivotY()
9925     * @return The scaling factor.
9926     */
9927    @ViewDebug.ExportedProperty(category = "drawing")
9928    public float getScaleX() {
9929        return mRenderNode.getScaleX();
9930    }
9931
9932    /**
9933     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9934     * the view's unscaled width. A value of 1 means that no scaling is applied.
9935     *
9936     * @param scaleX The scaling factor.
9937     * @see #getPivotX()
9938     * @see #getPivotY()
9939     *
9940     * @attr ref android.R.styleable#View_scaleX
9941     */
9942    public void setScaleX(float scaleX) {
9943        if (scaleX != getScaleX()) {
9944            invalidateViewProperty(true, false);
9945            mRenderNode.setScaleX(scaleX);
9946            invalidateViewProperty(false, true);
9947
9948            invalidateParentIfNeededAndWasQuickRejected();
9949            notifySubtreeAccessibilityStateChangedIfNeeded();
9950        }
9951    }
9952
9953    /**
9954     * The amount that the view is scaled in y around the pivot point, as a proportion of
9955     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9956     *
9957     * <p>By default, this is 1.0f.
9958     *
9959     * @see #getPivotX()
9960     * @see #getPivotY()
9961     * @return The scaling factor.
9962     */
9963    @ViewDebug.ExportedProperty(category = "drawing")
9964    public float getScaleY() {
9965        return mRenderNode.getScaleY();
9966    }
9967
9968    /**
9969     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9970     * the view's unscaled width. A value of 1 means that no scaling is applied.
9971     *
9972     * @param scaleY The scaling factor.
9973     * @see #getPivotX()
9974     * @see #getPivotY()
9975     *
9976     * @attr ref android.R.styleable#View_scaleY
9977     */
9978    public void setScaleY(float scaleY) {
9979        if (scaleY != getScaleY()) {
9980            invalidateViewProperty(true, false);
9981            mRenderNode.setScaleY(scaleY);
9982            invalidateViewProperty(false, true);
9983
9984            invalidateParentIfNeededAndWasQuickRejected();
9985            notifySubtreeAccessibilityStateChangedIfNeeded();
9986        }
9987    }
9988
9989    /**
9990     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9991     * and {@link #setScaleX(float) scaled}.
9992     *
9993     * @see #getRotation()
9994     * @see #getScaleX()
9995     * @see #getScaleY()
9996     * @see #getPivotY()
9997     * @return The x location of the pivot point.
9998     *
9999     * @attr ref android.R.styleable#View_transformPivotX
10000     */
10001    @ViewDebug.ExportedProperty(category = "drawing")
10002    public float getPivotX() {
10003        return mRenderNode.getPivotX();
10004    }
10005
10006    /**
10007     * Sets the x location of the point around which the view is
10008     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10009     * By default, the pivot point is centered on the object.
10010     * Setting this property disables this behavior and causes the view to use only the
10011     * explicitly set pivotX and pivotY values.
10012     *
10013     * @param pivotX The x location of the pivot point.
10014     * @see #getRotation()
10015     * @see #getScaleX()
10016     * @see #getScaleY()
10017     * @see #getPivotY()
10018     *
10019     * @attr ref android.R.styleable#View_transformPivotX
10020     */
10021    public void setPivotX(float pivotX) {
10022        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10023            invalidateViewProperty(true, false);
10024            mRenderNode.setPivotX(pivotX);
10025            invalidateViewProperty(false, true);
10026
10027            invalidateParentIfNeededAndWasQuickRejected();
10028        }
10029    }
10030
10031    /**
10032     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10033     * and {@link #setScaleY(float) scaled}.
10034     *
10035     * @see #getRotation()
10036     * @see #getScaleX()
10037     * @see #getScaleY()
10038     * @see #getPivotY()
10039     * @return The y location of the pivot point.
10040     *
10041     * @attr ref android.R.styleable#View_transformPivotY
10042     */
10043    @ViewDebug.ExportedProperty(category = "drawing")
10044    public float getPivotY() {
10045        return mRenderNode.getPivotY();
10046    }
10047
10048    /**
10049     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10050     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10051     * Setting this property disables this behavior and causes the view to use only the
10052     * explicitly set pivotX and pivotY values.
10053     *
10054     * @param pivotY The y location of the pivot point.
10055     * @see #getRotation()
10056     * @see #getScaleX()
10057     * @see #getScaleY()
10058     * @see #getPivotY()
10059     *
10060     * @attr ref android.R.styleable#View_transformPivotY
10061     */
10062    public void setPivotY(float pivotY) {
10063        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10064            invalidateViewProperty(true, false);
10065            mRenderNode.setPivotY(pivotY);
10066            invalidateViewProperty(false, true);
10067
10068            invalidateParentIfNeededAndWasQuickRejected();
10069        }
10070    }
10071
10072    /**
10073     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10074     * completely transparent and 1 means the view is completely opaque.
10075     *
10076     * <p>By default this is 1.0f.
10077     * @return The opacity of the view.
10078     */
10079    @ViewDebug.ExportedProperty(category = "drawing")
10080    public float getAlpha() {
10081        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10082    }
10083
10084    /**
10085     * Returns whether this View has content which overlaps.
10086     *
10087     * <p>This function, intended to be overridden by specific View types, is an optimization when
10088     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10089     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10090     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10091     * directly. An example of overlapping rendering is a TextView with a background image, such as
10092     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10093     * ImageView with only the foreground image. The default implementation returns true; subclasses
10094     * should override if they have cases which can be optimized.</p>
10095     *
10096     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10097     * necessitates that a View return true if it uses the methods internally without passing the
10098     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10099     *
10100     * @return true if the content in this view might overlap, false otherwise.
10101     */
10102    public boolean hasOverlappingRendering() {
10103        return true;
10104    }
10105
10106    /**
10107     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10108     * completely transparent and 1 means the view is completely opaque.</p>
10109     *
10110     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10111     * performance implications, especially for large views. It is best to use the alpha property
10112     * sparingly and transiently, as in the case of fading animations.</p>
10113     *
10114     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10115     * strongly recommended for performance reasons to either override
10116     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10117     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10118     *
10119     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10120     * responsible for applying the opacity itself.</p>
10121     *
10122     * <p>Note that if the view is backed by a
10123     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10124     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10125     * 1.0 will supercede the alpha of the layer paint.</p>
10126     *
10127     * @param alpha The opacity of the view.
10128     *
10129     * @see #hasOverlappingRendering()
10130     * @see #setLayerType(int, android.graphics.Paint)
10131     *
10132     * @attr ref android.R.styleable#View_alpha
10133     */
10134    public void setAlpha(float alpha) {
10135        ensureTransformationInfo();
10136        if (mTransformationInfo.mAlpha != alpha) {
10137            mTransformationInfo.mAlpha = alpha;
10138            if (onSetAlpha((int) (alpha * 255))) {
10139                mPrivateFlags |= PFLAG_ALPHA_SET;
10140                // subclass is handling alpha - don't optimize rendering cache invalidation
10141                invalidateParentCaches();
10142                invalidate(true);
10143            } else {
10144                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10145                invalidateViewProperty(true, false);
10146                mRenderNode.setAlpha(getFinalAlpha());
10147                notifyViewAccessibilityStateChangedIfNeeded(
10148                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10149            }
10150        }
10151    }
10152
10153    /**
10154     * Faster version of setAlpha() which performs the same steps except there are
10155     * no calls to invalidate(). The caller of this function should perform proper invalidation
10156     * on the parent and this object. The return value indicates whether the subclass handles
10157     * alpha (the return value for onSetAlpha()).
10158     *
10159     * @param alpha The new value for the alpha property
10160     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10161     *         the new value for the alpha property is different from the old value
10162     */
10163    boolean setAlphaNoInvalidation(float alpha) {
10164        ensureTransformationInfo();
10165        if (mTransformationInfo.mAlpha != alpha) {
10166            mTransformationInfo.mAlpha = alpha;
10167            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10168            if (subclassHandlesAlpha) {
10169                mPrivateFlags |= PFLAG_ALPHA_SET;
10170                return true;
10171            } else {
10172                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10173                mRenderNode.setAlpha(getFinalAlpha());
10174            }
10175        }
10176        return false;
10177    }
10178
10179    /**
10180     * This property is hidden and intended only for use by the Fade transition, which
10181     * animates it to produce a visual translucency that does not side-effect (or get
10182     * affected by) the real alpha property. This value is composited with the other
10183     * alpha value (and the AlphaAnimation value, when that is present) to produce
10184     * a final visual translucency result, which is what is passed into the DisplayList.
10185     *
10186     * @hide
10187     */
10188    public void setTransitionAlpha(float alpha) {
10189        ensureTransformationInfo();
10190        if (mTransformationInfo.mTransitionAlpha != alpha) {
10191            mTransformationInfo.mTransitionAlpha = alpha;
10192            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10193            invalidateViewProperty(true, false);
10194            mRenderNode.setAlpha(getFinalAlpha());
10195        }
10196    }
10197
10198    /**
10199     * Calculates the visual alpha of this view, which is a combination of the actual
10200     * alpha value and the transitionAlpha value (if set).
10201     */
10202    private float getFinalAlpha() {
10203        if (mTransformationInfo != null) {
10204            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10205        }
10206        return 1;
10207    }
10208
10209    /**
10210     * This property is hidden and intended only for use by the Fade transition, which
10211     * animates it to produce a visual translucency that does not side-effect (or get
10212     * affected by) the real alpha property. This value is composited with the other
10213     * alpha value (and the AlphaAnimation value, when that is present) to produce
10214     * a final visual translucency result, which is what is passed into the DisplayList.
10215     *
10216     * @hide
10217     */
10218    public float getTransitionAlpha() {
10219        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10220    }
10221
10222    /**
10223     * Top position of this view relative to its parent.
10224     *
10225     * @return The top of this view, in pixels.
10226     */
10227    @ViewDebug.CapturedViewProperty
10228    public final int getTop() {
10229        return mTop;
10230    }
10231
10232    /**
10233     * Sets the top position of this view relative to its parent. This method is meant to be called
10234     * by the layout system and should not generally be called otherwise, because the property
10235     * may be changed at any time by the layout.
10236     *
10237     * @param top The top of this view, in pixels.
10238     */
10239    public final void setTop(int top) {
10240        if (top != mTop) {
10241            final boolean matrixIsIdentity = hasIdentityMatrix();
10242            if (matrixIsIdentity) {
10243                if (mAttachInfo != null) {
10244                    int minTop;
10245                    int yLoc;
10246                    if (top < mTop) {
10247                        minTop = top;
10248                        yLoc = top - mTop;
10249                    } else {
10250                        minTop = mTop;
10251                        yLoc = 0;
10252                    }
10253                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10254                }
10255            } else {
10256                // Double-invalidation is necessary to capture view's old and new areas
10257                invalidate(true);
10258            }
10259
10260            int width = mRight - mLeft;
10261            int oldHeight = mBottom - mTop;
10262
10263            mTop = top;
10264            mRenderNode.setTop(mTop);
10265
10266            sizeChange(width, mBottom - mTop, width, oldHeight);
10267
10268            if (!matrixIsIdentity) {
10269                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10270                invalidate(true);
10271            }
10272            mBackgroundSizeChanged = true;
10273            invalidateParentIfNeeded();
10274            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10275                // View was rejected last time it was drawn by its parent; this may have changed
10276                invalidateParentIfNeeded();
10277            }
10278        }
10279    }
10280
10281    /**
10282     * Bottom position of this view relative to its parent.
10283     *
10284     * @return The bottom of this view, in pixels.
10285     */
10286    @ViewDebug.CapturedViewProperty
10287    public final int getBottom() {
10288        return mBottom;
10289    }
10290
10291    /**
10292     * True if this view has changed since the last time being drawn.
10293     *
10294     * @return The dirty state of this view.
10295     */
10296    public boolean isDirty() {
10297        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10298    }
10299
10300    /**
10301     * Sets the bottom position of this view relative to its parent. This method is meant to be
10302     * called by the layout system and should not generally be called otherwise, because the
10303     * property may be changed at any time by the layout.
10304     *
10305     * @param bottom The bottom of this view, in pixels.
10306     */
10307    public final void setBottom(int bottom) {
10308        if (bottom != mBottom) {
10309            final boolean matrixIsIdentity = hasIdentityMatrix();
10310            if (matrixIsIdentity) {
10311                if (mAttachInfo != null) {
10312                    int maxBottom;
10313                    if (bottom < mBottom) {
10314                        maxBottom = mBottom;
10315                    } else {
10316                        maxBottom = bottom;
10317                    }
10318                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10319                }
10320            } else {
10321                // Double-invalidation is necessary to capture view's old and new areas
10322                invalidate(true);
10323            }
10324
10325            int width = mRight - mLeft;
10326            int oldHeight = mBottom - mTop;
10327
10328            mBottom = bottom;
10329            mRenderNode.setBottom(mBottom);
10330
10331            sizeChange(width, mBottom - mTop, width, oldHeight);
10332
10333            if (!matrixIsIdentity) {
10334                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10335                invalidate(true);
10336            }
10337            mBackgroundSizeChanged = true;
10338            invalidateParentIfNeeded();
10339            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10340                // View was rejected last time it was drawn by its parent; this may have changed
10341                invalidateParentIfNeeded();
10342            }
10343        }
10344    }
10345
10346    /**
10347     * Left position of this view relative to its parent.
10348     *
10349     * @return The left edge of this view, in pixels.
10350     */
10351    @ViewDebug.CapturedViewProperty
10352    public final int getLeft() {
10353        return mLeft;
10354    }
10355
10356    /**
10357     * Sets the left position of this view relative to its parent. This method is meant to be called
10358     * by the layout system and should not generally be called otherwise, because the property
10359     * may be changed at any time by the layout.
10360     *
10361     * @param left The left of this view, in pixels.
10362     */
10363    public final void setLeft(int left) {
10364        if (left != mLeft) {
10365            final boolean matrixIsIdentity = hasIdentityMatrix();
10366            if (matrixIsIdentity) {
10367                if (mAttachInfo != null) {
10368                    int minLeft;
10369                    int xLoc;
10370                    if (left < mLeft) {
10371                        minLeft = left;
10372                        xLoc = left - mLeft;
10373                    } else {
10374                        minLeft = mLeft;
10375                        xLoc = 0;
10376                    }
10377                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10378                }
10379            } else {
10380                // Double-invalidation is necessary to capture view's old and new areas
10381                invalidate(true);
10382            }
10383
10384            int oldWidth = mRight - mLeft;
10385            int height = mBottom - mTop;
10386
10387            mLeft = left;
10388            mRenderNode.setLeft(left);
10389
10390            sizeChange(mRight - mLeft, height, oldWidth, height);
10391
10392            if (!matrixIsIdentity) {
10393                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10394                invalidate(true);
10395            }
10396            mBackgroundSizeChanged = true;
10397            invalidateParentIfNeeded();
10398            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10399                // View was rejected last time it was drawn by its parent; this may have changed
10400                invalidateParentIfNeeded();
10401            }
10402        }
10403    }
10404
10405    /**
10406     * Right position of this view relative to its parent.
10407     *
10408     * @return The right edge of this view, in pixels.
10409     */
10410    @ViewDebug.CapturedViewProperty
10411    public final int getRight() {
10412        return mRight;
10413    }
10414
10415    /**
10416     * Sets the right position of this view relative to its parent. This method is meant to be called
10417     * by the layout system and should not generally be called otherwise, because the property
10418     * may be changed at any time by the layout.
10419     *
10420     * @param right The right of this view, in pixels.
10421     */
10422    public final void setRight(int right) {
10423        if (right != mRight) {
10424            final boolean matrixIsIdentity = hasIdentityMatrix();
10425            if (matrixIsIdentity) {
10426                if (mAttachInfo != null) {
10427                    int maxRight;
10428                    if (right < mRight) {
10429                        maxRight = mRight;
10430                    } else {
10431                        maxRight = right;
10432                    }
10433                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10434                }
10435            } else {
10436                // Double-invalidation is necessary to capture view's old and new areas
10437                invalidate(true);
10438            }
10439
10440            int oldWidth = mRight - mLeft;
10441            int height = mBottom - mTop;
10442
10443            mRight = right;
10444            mRenderNode.setRight(mRight);
10445
10446            sizeChange(mRight - mLeft, height, oldWidth, height);
10447
10448            if (!matrixIsIdentity) {
10449                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10450                invalidate(true);
10451            }
10452            mBackgroundSizeChanged = true;
10453            invalidateParentIfNeeded();
10454            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10455                // View was rejected last time it was drawn by its parent; this may have changed
10456                invalidateParentIfNeeded();
10457            }
10458        }
10459    }
10460
10461    /**
10462     * The visual x position of this view, in pixels. This is equivalent to the
10463     * {@link #setTranslationX(float) translationX} property plus the current
10464     * {@link #getLeft() left} property.
10465     *
10466     * @return The visual x position of this view, in pixels.
10467     */
10468    @ViewDebug.ExportedProperty(category = "drawing")
10469    public float getX() {
10470        return mLeft + getTranslationX();
10471    }
10472
10473    /**
10474     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10475     * {@link #setTranslationX(float) translationX} property to be the difference between
10476     * the x value passed in and the current {@link #getLeft() left} property.
10477     *
10478     * @param x The visual x position of this view, in pixels.
10479     */
10480    public void setX(float x) {
10481        setTranslationX(x - mLeft);
10482    }
10483
10484    /**
10485     * The visual y position of this view, in pixels. This is equivalent to the
10486     * {@link #setTranslationY(float) translationY} property plus the current
10487     * {@link #getTop() top} property.
10488     *
10489     * @return The visual y position of this view, in pixels.
10490     */
10491    @ViewDebug.ExportedProperty(category = "drawing")
10492    public float getY() {
10493        return mTop + getTranslationY();
10494    }
10495
10496    /**
10497     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10498     * {@link #setTranslationY(float) translationY} property to be the difference between
10499     * the y value passed in and the current {@link #getTop() top} property.
10500     *
10501     * @param y The visual y position of this view, in pixels.
10502     */
10503    public void setY(float y) {
10504        setTranslationY(y - mTop);
10505    }
10506
10507    /**
10508     * The visual z position of this view, in pixels. This is equivalent to the
10509     * {@link #setTranslationZ(float) translationZ} property plus the current
10510     * {@link #getElevation() elevation} property.
10511     *
10512     * @return The visual z position of this view, in pixels.
10513     */
10514    @ViewDebug.ExportedProperty(category = "drawing")
10515    public float getZ() {
10516        return getElevation() + getTranslationZ();
10517    }
10518
10519    /**
10520     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10521     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10522     * the x value passed in and the current {@link #getElevation() elevation} property.
10523     *
10524     * @param z The visual z position of this view, in pixels.
10525     */
10526    public void setZ(float z) {
10527        setTranslationZ(z - getElevation());
10528    }
10529
10530    /**
10531     * The base elevation of this view relative to its parent, in pixels.
10532     *
10533     * @return The base depth position of the view, in pixels.
10534     */
10535    @ViewDebug.ExportedProperty(category = "drawing")
10536    public float getElevation() {
10537        return mRenderNode.getElevation();
10538    }
10539
10540    /**
10541     * Sets the base elevation of this view, in pixels.
10542     *
10543     * @attr ref android.R.styleable#View_elevation
10544     */
10545    public void setElevation(float elevation) {
10546        if (elevation != getElevation()) {
10547            invalidateViewProperty(true, false);
10548            mRenderNode.setElevation(elevation);
10549            invalidateViewProperty(false, true);
10550
10551            invalidateParentIfNeededAndWasQuickRejected();
10552        }
10553    }
10554
10555    /**
10556     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10557     * This position is post-layout, in addition to wherever the object's
10558     * layout placed it.
10559     *
10560     * @return The horizontal position of this view relative to its left position, in pixels.
10561     */
10562    @ViewDebug.ExportedProperty(category = "drawing")
10563    public float getTranslationX() {
10564        return mRenderNode.getTranslationX();
10565    }
10566
10567    /**
10568     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10569     * This effectively positions the object post-layout, in addition to wherever the object's
10570     * layout placed it.
10571     *
10572     * @param translationX The horizontal position of this view relative to its left position,
10573     * in pixels.
10574     *
10575     * @attr ref android.R.styleable#View_translationX
10576     */
10577    public void setTranslationX(float translationX) {
10578        if (translationX != getTranslationX()) {
10579            invalidateViewProperty(true, false);
10580            mRenderNode.setTranslationX(translationX);
10581            invalidateViewProperty(false, true);
10582
10583            invalidateParentIfNeededAndWasQuickRejected();
10584            notifySubtreeAccessibilityStateChangedIfNeeded();
10585        }
10586    }
10587
10588    /**
10589     * The vertical location of this view relative to its {@link #getTop() top} position.
10590     * This position is post-layout, in addition to wherever the object's
10591     * layout placed it.
10592     *
10593     * @return The vertical position of this view relative to its top position,
10594     * in pixels.
10595     */
10596    @ViewDebug.ExportedProperty(category = "drawing")
10597    public float getTranslationY() {
10598        return mRenderNode.getTranslationY();
10599    }
10600
10601    /**
10602     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10603     * This effectively positions the object post-layout, in addition to wherever the object's
10604     * layout placed it.
10605     *
10606     * @param translationY The vertical position of this view relative to its top position,
10607     * in pixels.
10608     *
10609     * @attr ref android.R.styleable#View_translationY
10610     */
10611    public void setTranslationY(float translationY) {
10612        if (translationY != getTranslationY()) {
10613            invalidateViewProperty(true, false);
10614            mRenderNode.setTranslationY(translationY);
10615            invalidateViewProperty(false, true);
10616
10617            invalidateParentIfNeededAndWasQuickRejected();
10618        }
10619    }
10620
10621    /**
10622     * The depth location of this view relative to its {@link #getElevation() elevation}.
10623     *
10624     * @return The depth of this view relative to its elevation.
10625     */
10626    @ViewDebug.ExportedProperty(category = "drawing")
10627    public float getTranslationZ() {
10628        return mRenderNode.getTranslationZ();
10629    }
10630
10631    /**
10632     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10633     *
10634     * @attr ref android.R.styleable#View_translationZ
10635     */
10636    public void setTranslationZ(float translationZ) {
10637        if (translationZ != getTranslationZ()) {
10638            invalidateViewProperty(true, false);
10639            mRenderNode.setTranslationZ(translationZ);
10640            invalidateViewProperty(false, true);
10641
10642            invalidateParentIfNeededAndWasQuickRejected();
10643        }
10644    }
10645
10646    /**
10647     * Returns a ValueAnimator which can animate a clearing circle.
10648     * <p>
10649     * The View is prevented from drawing within the circle, so the content
10650     * behind the View shows through.
10651     *
10652     * @param centerX The x coordinate of the center of the animating circle.
10653     * @param centerY The y coordinate of the center of the animating circle.
10654     * @param startRadius The starting radius of the animating circle.
10655     * @param endRadius The ending radius of the animating circle.
10656     *
10657     * @hide
10658     */
10659    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10660            float startRadius, float endRadius) {
10661        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10662                startRadius, endRadius, true);
10663    }
10664
10665    /**
10666     * Returns the current StateListAnimator if exists.
10667     *
10668     * @return StateListAnimator or null if it does not exists
10669     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10670     */
10671    public StateListAnimator getStateListAnimator() {
10672        return mStateListAnimator;
10673    }
10674
10675    /**
10676     * Attaches the provided StateListAnimator to this View.
10677     * <p>
10678     * Any previously attached StateListAnimator will be detached.
10679     *
10680     * @param stateListAnimator The StateListAnimator to update the view
10681     * @see {@link android.animation.StateListAnimator}
10682     */
10683    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10684        if (mStateListAnimator == stateListAnimator) {
10685            return;
10686        }
10687        if (mStateListAnimator != null) {
10688            mStateListAnimator.setTarget(null);
10689        }
10690        mStateListAnimator = stateListAnimator;
10691        if (stateListAnimator != null) {
10692            stateListAnimator.setTarget(this);
10693            if (isAttachedToWindow()) {
10694                stateListAnimator.setState(getDrawableState());
10695            }
10696        }
10697    }
10698
10699    /**
10700     * Sets the {@link Outline} of the view, which defines the shape of the shadow it
10701     * casts, and enables outline clipping.
10702     * <p>
10703     * By default, a View queries its Outline from its background drawable, via
10704     * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows
10705     * this behavior to be overridden.
10706     * <p>
10707     * If the outline is {@link Outline#isEmpty()} or is <code>null</code>,
10708     * shadows will not be cast.
10709     * <p>
10710     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10711     *
10712     * @param outline The new outline of the view.
10713     *
10714     * @see #setClipToOutline(boolean)
10715     * @see #getClipToOutline()
10716     */
10717    public void setOutline(@Nullable Outline outline) {
10718        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10719
10720        if (outline == null || outline.isEmpty()) {
10721            if (mOutline != null) {
10722                mOutline.setEmpty();
10723            }
10724        } else {
10725            // always copy the path since caller may reuse
10726            if (mOutline == null) {
10727                mOutline = new Outline();
10728            }
10729            mOutline.set(outline);
10730        }
10731        mRenderNode.setOutline(mOutline);
10732    }
10733
10734    /**
10735     * Returns whether the Outline should be used to clip the contents of the View.
10736     * <p>
10737     * Note that this flag will only be respected if the View's Outline returns true from
10738     * {@link Outline#canClip()}.
10739     *
10740     * @see #setOutline(Outline)
10741     * @see #setClipToOutline(boolean)
10742     */
10743    public final boolean getClipToOutline() {
10744        return mRenderNode.getClipToOutline();
10745    }
10746
10747    /**
10748     * Sets whether the View's Outline should be used to clip the contents of the View.
10749     * <p>
10750     * Note that this flag will only be respected if the View's Outline returns true from
10751     * {@link Outline#canClip()}.
10752     *
10753     * @see #setOutline(Outline)
10754     * @see #getClipToOutline()
10755     */
10756    public void setClipToOutline(boolean clipToOutline) {
10757        damageInParent();
10758        if (getClipToOutline() != clipToOutline) {
10759            mRenderNode.setClipToOutline(clipToOutline);
10760        }
10761    }
10762
10763    private void queryOutlineFromBackgroundIfUndefined() {
10764        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
10765            // Outline not currently defined, query from background
10766            if (mOutline == null) {
10767                mOutline = new Outline();
10768            } else {
10769                //invalidate outline, to ensure background calculates it
10770                mOutline.setEmpty();
10771            }
10772            if (mBackground.getOutline(mOutline)) {
10773                if (mOutline.isEmpty()) {
10774                    throw new IllegalStateException("Background drawable failed to build outline");
10775                }
10776                mRenderNode.setOutline(mOutline);
10777            } else {
10778                mRenderNode.setOutline(null);
10779            }
10780            notifySubtreeAccessibilityStateChangedIfNeeded();
10781        }
10782    }
10783
10784    /**
10785     * Private API to be used for reveal animation
10786     *
10787     * @hide
10788     */
10789    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10790            float x, float y, float radius) {
10791        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10792        // TODO: Handle this invalidate in a better way, or purely in native.
10793        invalidate();
10794    }
10795
10796    /**
10797     * Hit rectangle in parent's coordinates
10798     *
10799     * @param outRect The hit rectangle of the view.
10800     */
10801    public void getHitRect(Rect outRect) {
10802        if (hasIdentityMatrix() || mAttachInfo == null) {
10803            outRect.set(mLeft, mTop, mRight, mBottom);
10804        } else {
10805            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10806            tmpRect.set(0, 0, getWidth(), getHeight());
10807            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10808            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10809                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10810        }
10811    }
10812
10813    /**
10814     * Determines whether the given point, in local coordinates is inside the view.
10815     */
10816    /*package*/ final boolean pointInView(float localX, float localY) {
10817        return localX >= 0 && localX < (mRight - mLeft)
10818                && localY >= 0 && localY < (mBottom - mTop);
10819    }
10820
10821    /**
10822     * Utility method to determine whether the given point, in local coordinates,
10823     * is inside the view, where the area of the view is expanded by the slop factor.
10824     * This method is called while processing touch-move events to determine if the event
10825     * is still within the view.
10826     *
10827     * @hide
10828     */
10829    public boolean pointInView(float localX, float localY, float slop) {
10830        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10831                localY < ((mBottom - mTop) + slop);
10832    }
10833
10834    /**
10835     * When a view has focus and the user navigates away from it, the next view is searched for
10836     * starting from the rectangle filled in by this method.
10837     *
10838     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10839     * of the view.  However, if your view maintains some idea of internal selection,
10840     * such as a cursor, or a selected row or column, you should override this method and
10841     * fill in a more specific rectangle.
10842     *
10843     * @param r The rectangle to fill in, in this view's coordinates.
10844     */
10845    public void getFocusedRect(Rect r) {
10846        getDrawingRect(r);
10847    }
10848
10849    /**
10850     * If some part of this view is not clipped by any of its parents, then
10851     * return that area in r in global (root) coordinates. To convert r to local
10852     * coordinates (without taking possible View rotations into account), offset
10853     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10854     * If the view is completely clipped or translated out, return false.
10855     *
10856     * @param r If true is returned, r holds the global coordinates of the
10857     *        visible portion of this view.
10858     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10859     *        between this view and its root. globalOffet may be null.
10860     * @return true if r is non-empty (i.e. part of the view is visible at the
10861     *         root level.
10862     */
10863    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10864        int width = mRight - mLeft;
10865        int height = mBottom - mTop;
10866        if (width > 0 && height > 0) {
10867            r.set(0, 0, width, height);
10868            if (globalOffset != null) {
10869                globalOffset.set(-mScrollX, -mScrollY);
10870            }
10871            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10872        }
10873        return false;
10874    }
10875
10876    public final boolean getGlobalVisibleRect(Rect r) {
10877        return getGlobalVisibleRect(r, null);
10878    }
10879
10880    public final boolean getLocalVisibleRect(Rect r) {
10881        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10882        if (getGlobalVisibleRect(r, offset)) {
10883            r.offset(-offset.x, -offset.y); // make r local
10884            return true;
10885        }
10886        return false;
10887    }
10888
10889    /**
10890     * Offset this view's vertical location by the specified number of pixels.
10891     *
10892     * @param offset the number of pixels to offset the view by
10893     */
10894    public void offsetTopAndBottom(int offset) {
10895        if (offset != 0) {
10896            final boolean matrixIsIdentity = hasIdentityMatrix();
10897            if (matrixIsIdentity) {
10898                if (isHardwareAccelerated()) {
10899                    invalidateViewProperty(false, false);
10900                } else {
10901                    final ViewParent p = mParent;
10902                    if (p != null && mAttachInfo != null) {
10903                        final Rect r = mAttachInfo.mTmpInvalRect;
10904                        int minTop;
10905                        int maxBottom;
10906                        int yLoc;
10907                        if (offset < 0) {
10908                            minTop = mTop + offset;
10909                            maxBottom = mBottom;
10910                            yLoc = offset;
10911                        } else {
10912                            minTop = mTop;
10913                            maxBottom = mBottom + offset;
10914                            yLoc = 0;
10915                        }
10916                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10917                        p.invalidateChild(this, r);
10918                    }
10919                }
10920            } else {
10921                invalidateViewProperty(false, false);
10922            }
10923
10924            mTop += offset;
10925            mBottom += offset;
10926            mRenderNode.offsetTopAndBottom(offset);
10927            if (isHardwareAccelerated()) {
10928                invalidateViewProperty(false, false);
10929            } else {
10930                if (!matrixIsIdentity) {
10931                    invalidateViewProperty(false, true);
10932                }
10933                invalidateParentIfNeeded();
10934            }
10935            notifySubtreeAccessibilityStateChangedIfNeeded();
10936        }
10937    }
10938
10939    /**
10940     * Offset this view's horizontal location by the specified amount of pixels.
10941     *
10942     * @param offset the number of pixels to offset the view by
10943     */
10944    public void offsetLeftAndRight(int offset) {
10945        if (offset != 0) {
10946            final boolean matrixIsIdentity = hasIdentityMatrix();
10947            if (matrixIsIdentity) {
10948                if (isHardwareAccelerated()) {
10949                    invalidateViewProperty(false, false);
10950                } else {
10951                    final ViewParent p = mParent;
10952                    if (p != null && mAttachInfo != null) {
10953                        final Rect r = mAttachInfo.mTmpInvalRect;
10954                        int minLeft;
10955                        int maxRight;
10956                        if (offset < 0) {
10957                            minLeft = mLeft + offset;
10958                            maxRight = mRight;
10959                        } else {
10960                            minLeft = mLeft;
10961                            maxRight = mRight + offset;
10962                        }
10963                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10964                        p.invalidateChild(this, r);
10965                    }
10966                }
10967            } else {
10968                invalidateViewProperty(false, false);
10969            }
10970
10971            mLeft += offset;
10972            mRight += offset;
10973            mRenderNode.offsetLeftAndRight(offset);
10974            if (isHardwareAccelerated()) {
10975                invalidateViewProperty(false, false);
10976            } else {
10977                if (!matrixIsIdentity) {
10978                    invalidateViewProperty(false, true);
10979                }
10980                invalidateParentIfNeeded();
10981            }
10982            notifySubtreeAccessibilityStateChangedIfNeeded();
10983        }
10984    }
10985
10986    /**
10987     * Get the LayoutParams associated with this view. All views should have
10988     * layout parameters. These supply parameters to the <i>parent</i> of this
10989     * view specifying how it should be arranged. There are many subclasses of
10990     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10991     * of ViewGroup that are responsible for arranging their children.
10992     *
10993     * This method may return null if this View is not attached to a parent
10994     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10995     * was not invoked successfully. When a View is attached to a parent
10996     * ViewGroup, this method must not return null.
10997     *
10998     * @return The LayoutParams associated with this view, or null if no
10999     *         parameters have been set yet
11000     */
11001    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11002    public ViewGroup.LayoutParams getLayoutParams() {
11003        return mLayoutParams;
11004    }
11005
11006    /**
11007     * Set the layout parameters associated with this view. These supply
11008     * parameters to the <i>parent</i> of this view specifying how it should be
11009     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11010     * correspond to the different subclasses of ViewGroup that are responsible
11011     * for arranging their children.
11012     *
11013     * @param params The layout parameters for this view, cannot be null
11014     */
11015    public void setLayoutParams(ViewGroup.LayoutParams params) {
11016        if (params == null) {
11017            throw new NullPointerException("Layout parameters cannot be null");
11018        }
11019        mLayoutParams = params;
11020        resolveLayoutParams();
11021        if (mParent instanceof ViewGroup) {
11022            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11023        }
11024        requestLayout();
11025    }
11026
11027    /**
11028     * Resolve the layout parameters depending on the resolved layout direction
11029     *
11030     * @hide
11031     */
11032    public void resolveLayoutParams() {
11033        if (mLayoutParams != null) {
11034            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11035        }
11036    }
11037
11038    /**
11039     * Set the scrolled position of your view. This will cause a call to
11040     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11041     * invalidated.
11042     * @param x the x position to scroll to
11043     * @param y the y position to scroll to
11044     */
11045    public void scrollTo(int x, int y) {
11046        if (mScrollX != x || mScrollY != y) {
11047            int oldX = mScrollX;
11048            int oldY = mScrollY;
11049            mScrollX = x;
11050            mScrollY = y;
11051            invalidateParentCaches();
11052            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11053            if (!awakenScrollBars()) {
11054                postInvalidateOnAnimation();
11055            }
11056        }
11057    }
11058
11059    /**
11060     * Move the scrolled position of your view. This will cause a call to
11061     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11062     * invalidated.
11063     * @param x the amount of pixels to scroll by horizontally
11064     * @param y the amount of pixels to scroll by vertically
11065     */
11066    public void scrollBy(int x, int y) {
11067        scrollTo(mScrollX + x, mScrollY + y);
11068    }
11069
11070    /**
11071     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11072     * animation to fade the scrollbars out after a default delay. If a subclass
11073     * provides animated scrolling, the start delay should equal the duration
11074     * of the scrolling animation.</p>
11075     *
11076     * <p>The animation starts only if at least one of the scrollbars is
11077     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11078     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11079     * this method returns true, and false otherwise. If the animation is
11080     * started, this method calls {@link #invalidate()}; in that case the
11081     * caller should not call {@link #invalidate()}.</p>
11082     *
11083     * <p>This method should be invoked every time a subclass directly updates
11084     * the scroll parameters.</p>
11085     *
11086     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11087     * and {@link #scrollTo(int, int)}.</p>
11088     *
11089     * @return true if the animation is played, false otherwise
11090     *
11091     * @see #awakenScrollBars(int)
11092     * @see #scrollBy(int, int)
11093     * @see #scrollTo(int, int)
11094     * @see #isHorizontalScrollBarEnabled()
11095     * @see #isVerticalScrollBarEnabled()
11096     * @see #setHorizontalScrollBarEnabled(boolean)
11097     * @see #setVerticalScrollBarEnabled(boolean)
11098     */
11099    protected boolean awakenScrollBars() {
11100        return mScrollCache != null &&
11101                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11102    }
11103
11104    /**
11105     * Trigger the scrollbars to draw.
11106     * This method differs from awakenScrollBars() only in its default duration.
11107     * initialAwakenScrollBars() will show the scroll bars for longer than
11108     * usual to give the user more of a chance to notice them.
11109     *
11110     * @return true if the animation is played, false otherwise.
11111     */
11112    private boolean initialAwakenScrollBars() {
11113        return mScrollCache != null &&
11114                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11115    }
11116
11117    /**
11118     * <p>
11119     * Trigger the scrollbars to draw. When invoked this method starts an
11120     * animation to fade the scrollbars out after a fixed delay. If a subclass
11121     * provides animated scrolling, the start delay should equal the duration of
11122     * the scrolling animation.
11123     * </p>
11124     *
11125     * <p>
11126     * The animation starts only if at least one of the scrollbars is enabled,
11127     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11128     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11129     * this method returns true, and false otherwise. If the animation is
11130     * started, this method calls {@link #invalidate()}; in that case the caller
11131     * should not call {@link #invalidate()}.
11132     * </p>
11133     *
11134     * <p>
11135     * This method should be invoked everytime a subclass directly updates the
11136     * scroll parameters.
11137     * </p>
11138     *
11139     * @param startDelay the delay, in milliseconds, after which the animation
11140     *        should start; when the delay is 0, the animation starts
11141     *        immediately
11142     * @return true if the animation is played, false otherwise
11143     *
11144     * @see #scrollBy(int, int)
11145     * @see #scrollTo(int, int)
11146     * @see #isHorizontalScrollBarEnabled()
11147     * @see #isVerticalScrollBarEnabled()
11148     * @see #setHorizontalScrollBarEnabled(boolean)
11149     * @see #setVerticalScrollBarEnabled(boolean)
11150     */
11151    protected boolean awakenScrollBars(int startDelay) {
11152        return awakenScrollBars(startDelay, true);
11153    }
11154
11155    /**
11156     * <p>
11157     * Trigger the scrollbars to draw. When invoked this method starts an
11158     * animation to fade the scrollbars out after a fixed delay. If a subclass
11159     * provides animated scrolling, the start delay should equal the duration of
11160     * the scrolling animation.
11161     * </p>
11162     *
11163     * <p>
11164     * The animation starts only if at least one of the scrollbars is enabled,
11165     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11166     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11167     * this method returns true, and false otherwise. If the animation is
11168     * started, this method calls {@link #invalidate()} if the invalidate parameter
11169     * is set to true; in that case the caller
11170     * should not call {@link #invalidate()}.
11171     * </p>
11172     *
11173     * <p>
11174     * This method should be invoked everytime a subclass directly updates the
11175     * scroll parameters.
11176     * </p>
11177     *
11178     * @param startDelay the delay, in milliseconds, after which the animation
11179     *        should start; when the delay is 0, the animation starts
11180     *        immediately
11181     *
11182     * @param invalidate Wheter this method should call invalidate
11183     *
11184     * @return true if the animation is played, false otherwise
11185     *
11186     * @see #scrollBy(int, int)
11187     * @see #scrollTo(int, int)
11188     * @see #isHorizontalScrollBarEnabled()
11189     * @see #isVerticalScrollBarEnabled()
11190     * @see #setHorizontalScrollBarEnabled(boolean)
11191     * @see #setVerticalScrollBarEnabled(boolean)
11192     */
11193    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11194        final ScrollabilityCache scrollCache = mScrollCache;
11195
11196        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11197            return false;
11198        }
11199
11200        if (scrollCache.scrollBar == null) {
11201            scrollCache.scrollBar = new ScrollBarDrawable();
11202        }
11203
11204        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11205
11206            if (invalidate) {
11207                // Invalidate to show the scrollbars
11208                postInvalidateOnAnimation();
11209            }
11210
11211            if (scrollCache.state == ScrollabilityCache.OFF) {
11212                // FIXME: this is copied from WindowManagerService.
11213                // We should get this value from the system when it
11214                // is possible to do so.
11215                final int KEY_REPEAT_FIRST_DELAY = 750;
11216                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11217            }
11218
11219            // Tell mScrollCache when we should start fading. This may
11220            // extend the fade start time if one was already scheduled
11221            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11222            scrollCache.fadeStartTime = fadeStartTime;
11223            scrollCache.state = ScrollabilityCache.ON;
11224
11225            // Schedule our fader to run, unscheduling any old ones first
11226            if (mAttachInfo != null) {
11227                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11228                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11229            }
11230
11231            return true;
11232        }
11233
11234        return false;
11235    }
11236
11237    /**
11238     * Do not invalidate views which are not visible and which are not running an animation. They
11239     * will not get drawn and they should not set dirty flags as if they will be drawn
11240     */
11241    private boolean skipInvalidate() {
11242        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11243                (!(mParent instanceof ViewGroup) ||
11244                        !((ViewGroup) mParent).isViewTransitioning(this));
11245    }
11246
11247    /**
11248     * Mark the area defined by dirty as needing to be drawn. If the view is
11249     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11250     * point in the future.
11251     * <p>
11252     * This must be called from a UI thread. To call from a non-UI thread, call
11253     * {@link #postInvalidate()}.
11254     * <p>
11255     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11256     * {@code dirty}.
11257     *
11258     * @param dirty the rectangle representing the bounds of the dirty region
11259     */
11260    public void invalidate(Rect dirty) {
11261        final int scrollX = mScrollX;
11262        final int scrollY = mScrollY;
11263        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11264                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11265    }
11266
11267    /**
11268     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11269     * coordinates of the dirty rect are relative to the view. If the view is
11270     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11271     * point in the future.
11272     * <p>
11273     * This must be called from a UI thread. To call from a non-UI thread, call
11274     * {@link #postInvalidate()}.
11275     *
11276     * @param l the left position of the dirty region
11277     * @param t the top position of the dirty region
11278     * @param r the right position of the dirty region
11279     * @param b the bottom position of the dirty region
11280     */
11281    public void invalidate(int l, int t, int r, int b) {
11282        final int scrollX = mScrollX;
11283        final int scrollY = mScrollY;
11284        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11285    }
11286
11287    /**
11288     * Invalidate the whole view. If the view is visible,
11289     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11290     * the future.
11291     * <p>
11292     * This must be called from a UI thread. To call from a non-UI thread, call
11293     * {@link #postInvalidate()}.
11294     */
11295    public void invalidate() {
11296        invalidate(true);
11297    }
11298
11299    /**
11300     * This is where the invalidate() work actually happens. A full invalidate()
11301     * causes the drawing cache to be invalidated, but this function can be
11302     * called with invalidateCache set to false to skip that invalidation step
11303     * for cases that do not need it (for example, a component that remains at
11304     * the same dimensions with the same content).
11305     *
11306     * @param invalidateCache Whether the drawing cache for this view should be
11307     *            invalidated as well. This is usually true for a full
11308     *            invalidate, but may be set to false if the View's contents or
11309     *            dimensions have not changed.
11310     */
11311    void invalidate(boolean invalidateCache) {
11312        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11313    }
11314
11315    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11316            boolean fullInvalidate) {
11317        if (skipInvalidate()) {
11318            return;
11319        }
11320
11321        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11322                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11323                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11324                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11325            if (fullInvalidate) {
11326                mLastIsOpaque = isOpaque();
11327                mPrivateFlags &= ~PFLAG_DRAWN;
11328            }
11329
11330            mPrivateFlags |= PFLAG_DIRTY;
11331
11332            if (invalidateCache) {
11333                mPrivateFlags |= PFLAG_INVALIDATED;
11334                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11335            }
11336
11337            // Propagate the damage rectangle to the parent view.
11338            final AttachInfo ai = mAttachInfo;
11339            final ViewParent p = mParent;
11340            if (p != null && ai != null && l < r && t < b) {
11341                final Rect damage = ai.mTmpInvalRect;
11342                damage.set(l, t, r, b);
11343                p.invalidateChild(this, damage);
11344            }
11345
11346            // Damage the entire projection receiver, if necessary.
11347            if (mBackground != null && mBackground.isProjected()) {
11348                final View receiver = getProjectionReceiver();
11349                if (receiver != null) {
11350                    receiver.damageInParent();
11351                }
11352            }
11353
11354            // Damage the entire IsolatedZVolume recieving this view's shadow.
11355            if (isHardwareAccelerated() && getZ() != 0) {
11356                damageShadowReceiver();
11357            }
11358        }
11359    }
11360
11361    /**
11362     * @return this view's projection receiver, or {@code null} if none exists
11363     */
11364    private View getProjectionReceiver() {
11365        ViewParent p = getParent();
11366        while (p != null && p instanceof View) {
11367            final View v = (View) p;
11368            if (v.isProjectionReceiver()) {
11369                return v;
11370            }
11371            p = p.getParent();
11372        }
11373
11374        return null;
11375    }
11376
11377    /**
11378     * @return whether the view is a projection receiver
11379     */
11380    private boolean isProjectionReceiver() {
11381        return mBackground != null;
11382    }
11383
11384    /**
11385     * Damage area of the screen that can be covered by this View's shadow.
11386     *
11387     * This method will guarantee that any changes to shadows cast by a View
11388     * are damaged on the screen for future redraw.
11389     */
11390    private void damageShadowReceiver() {
11391        final AttachInfo ai = mAttachInfo;
11392        if (ai != null) {
11393            ViewParent p = getParent();
11394            if (p != null && p instanceof ViewGroup) {
11395                final ViewGroup vg = (ViewGroup) p;
11396                vg.damageInParent();
11397            }
11398        }
11399    }
11400
11401    /**
11402     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11403     * set any flags or handle all of the cases handled by the default invalidation methods.
11404     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11405     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11406     * walk up the hierarchy, transforming the dirty rect as necessary.
11407     *
11408     * The method also handles normal invalidation logic if display list properties are not
11409     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11410     * backup approach, to handle these cases used in the various property-setting methods.
11411     *
11412     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11413     * are not being used in this view
11414     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11415     * list properties are not being used in this view
11416     */
11417    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11418        if (!isHardwareAccelerated()
11419                || !mRenderNode.isValid()
11420                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11421            if (invalidateParent) {
11422                invalidateParentCaches();
11423            }
11424            if (forceRedraw) {
11425                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11426            }
11427            invalidate(false);
11428        } else {
11429            damageInParent();
11430        }
11431        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11432            damageShadowReceiver();
11433        }
11434    }
11435
11436    /**
11437     * Tells the parent view to damage this view's bounds.
11438     *
11439     * @hide
11440     */
11441    protected void damageInParent() {
11442        final AttachInfo ai = mAttachInfo;
11443        final ViewParent p = mParent;
11444        if (p != null && ai != null) {
11445            final Rect r = ai.mTmpInvalRect;
11446            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11447            if (mParent instanceof ViewGroup) {
11448                ((ViewGroup) mParent).damageChild(this, r);
11449            } else {
11450                mParent.invalidateChild(this, r);
11451            }
11452        }
11453    }
11454
11455    /**
11456     * Utility method to transform a given Rect by the current matrix of this view.
11457     */
11458    void transformRect(final Rect rect) {
11459        if (!getMatrix().isIdentity()) {
11460            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11461            boundingRect.set(rect);
11462            getMatrix().mapRect(boundingRect);
11463            rect.set((int) Math.floor(boundingRect.left),
11464                    (int) Math.floor(boundingRect.top),
11465                    (int) Math.ceil(boundingRect.right),
11466                    (int) Math.ceil(boundingRect.bottom));
11467        }
11468    }
11469
11470    /**
11471     * Used to indicate that the parent of this view should clear its caches. This functionality
11472     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11473     * which is necessary when various parent-managed properties of the view change, such as
11474     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11475     * clears the parent caches and does not causes an invalidate event.
11476     *
11477     * @hide
11478     */
11479    protected void invalidateParentCaches() {
11480        if (mParent instanceof View) {
11481            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11482        }
11483    }
11484
11485    /**
11486     * Used to indicate that the parent of this view should be invalidated. This functionality
11487     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11488     * which is necessary when various parent-managed properties of the view change, such as
11489     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11490     * an invalidation event to the parent.
11491     *
11492     * @hide
11493     */
11494    protected void invalidateParentIfNeeded() {
11495        if (isHardwareAccelerated() && mParent instanceof View) {
11496            ((View) mParent).invalidate(true);
11497        }
11498    }
11499
11500    /**
11501     * @hide
11502     */
11503    protected void invalidateParentIfNeededAndWasQuickRejected() {
11504        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11505            // View was rejected last time it was drawn by its parent; this may have changed
11506            invalidateParentIfNeeded();
11507        }
11508    }
11509
11510    /**
11511     * Indicates whether this View is opaque. An opaque View guarantees that it will
11512     * draw all the pixels overlapping its bounds using a fully opaque color.
11513     *
11514     * Subclasses of View should override this method whenever possible to indicate
11515     * whether an instance is opaque. Opaque Views are treated in a special way by
11516     * the View hierarchy, possibly allowing it to perform optimizations during
11517     * invalidate/draw passes.
11518     *
11519     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11520     */
11521    @ViewDebug.ExportedProperty(category = "drawing")
11522    public boolean isOpaque() {
11523        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11524                getFinalAlpha() >= 1.0f;
11525    }
11526
11527    /**
11528     * @hide
11529     */
11530    protected void computeOpaqueFlags() {
11531        // Opaque if:
11532        //   - Has a background
11533        //   - Background is opaque
11534        //   - Doesn't have scrollbars or scrollbars overlay
11535
11536        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11537            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11538        } else {
11539            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11540        }
11541
11542        final int flags = mViewFlags;
11543        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11544                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11545                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11546            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11547        } else {
11548            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11549        }
11550    }
11551
11552    /**
11553     * @hide
11554     */
11555    protected boolean hasOpaqueScrollbars() {
11556        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11557    }
11558
11559    /**
11560     * @return A handler associated with the thread running the View. This
11561     * handler can be used to pump events in the UI events queue.
11562     */
11563    public Handler getHandler() {
11564        final AttachInfo attachInfo = mAttachInfo;
11565        if (attachInfo != null) {
11566            return attachInfo.mHandler;
11567        }
11568        return null;
11569    }
11570
11571    /**
11572     * Gets the view root associated with the View.
11573     * @return The view root, or null if none.
11574     * @hide
11575     */
11576    public ViewRootImpl getViewRootImpl() {
11577        if (mAttachInfo != null) {
11578            return mAttachInfo.mViewRootImpl;
11579        }
11580        return null;
11581    }
11582
11583    /**
11584     * @hide
11585     */
11586    public HardwareRenderer getHardwareRenderer() {
11587        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11588    }
11589
11590    /**
11591     * <p>Causes the Runnable to be added to the message queue.
11592     * The runnable will be run on the user interface thread.</p>
11593     *
11594     * @param action The Runnable that will be executed.
11595     *
11596     * @return Returns true if the Runnable was successfully placed in to the
11597     *         message queue.  Returns false on failure, usually because the
11598     *         looper processing the message queue is exiting.
11599     *
11600     * @see #postDelayed
11601     * @see #removeCallbacks
11602     */
11603    public boolean post(Runnable action) {
11604        final AttachInfo attachInfo = mAttachInfo;
11605        if (attachInfo != null) {
11606            return attachInfo.mHandler.post(action);
11607        }
11608        // Assume that post will succeed later
11609        ViewRootImpl.getRunQueue().post(action);
11610        return true;
11611    }
11612
11613    /**
11614     * <p>Causes the Runnable to be added to the message queue, to be run
11615     * after the specified amount of time elapses.
11616     * The runnable will be run on the user interface thread.</p>
11617     *
11618     * @param action The Runnable that will be executed.
11619     * @param delayMillis The delay (in milliseconds) until the Runnable
11620     *        will be executed.
11621     *
11622     * @return true if the Runnable was successfully placed in to the
11623     *         message queue.  Returns false on failure, usually because the
11624     *         looper processing the message queue is exiting.  Note that a
11625     *         result of true does not mean the Runnable will be processed --
11626     *         if the looper is quit before the delivery time of the message
11627     *         occurs then the message will be dropped.
11628     *
11629     * @see #post
11630     * @see #removeCallbacks
11631     */
11632    public boolean postDelayed(Runnable action, long delayMillis) {
11633        final AttachInfo attachInfo = mAttachInfo;
11634        if (attachInfo != null) {
11635            return attachInfo.mHandler.postDelayed(action, delayMillis);
11636        }
11637        // Assume that post will succeed later
11638        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11639        return true;
11640    }
11641
11642    /**
11643     * <p>Causes the Runnable to execute on the next animation time step.
11644     * The runnable will be run on the user interface thread.</p>
11645     *
11646     * @param action The Runnable that will be executed.
11647     *
11648     * @see #postOnAnimationDelayed
11649     * @see #removeCallbacks
11650     */
11651    public void postOnAnimation(Runnable action) {
11652        final AttachInfo attachInfo = mAttachInfo;
11653        if (attachInfo != null) {
11654            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11655                    Choreographer.CALLBACK_ANIMATION, action, null);
11656        } else {
11657            // Assume that post will succeed later
11658            ViewRootImpl.getRunQueue().post(action);
11659        }
11660    }
11661
11662    /**
11663     * <p>Causes the Runnable to execute on the next animation time step,
11664     * after the specified amount of time elapses.
11665     * The runnable will be run on the user interface thread.</p>
11666     *
11667     * @param action The Runnable that will be executed.
11668     * @param delayMillis The delay (in milliseconds) until the Runnable
11669     *        will be executed.
11670     *
11671     * @see #postOnAnimation
11672     * @see #removeCallbacks
11673     */
11674    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11675        final AttachInfo attachInfo = mAttachInfo;
11676        if (attachInfo != null) {
11677            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11678                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11679        } else {
11680            // Assume that post will succeed later
11681            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11682        }
11683    }
11684
11685    /**
11686     * <p>Removes the specified Runnable from the message queue.</p>
11687     *
11688     * @param action The Runnable to remove from the message handling queue
11689     *
11690     * @return true if this view could ask the Handler to remove the Runnable,
11691     *         false otherwise. When the returned value is true, the Runnable
11692     *         may or may not have been actually removed from the message queue
11693     *         (for instance, if the Runnable was not in the queue already.)
11694     *
11695     * @see #post
11696     * @see #postDelayed
11697     * @see #postOnAnimation
11698     * @see #postOnAnimationDelayed
11699     */
11700    public boolean removeCallbacks(Runnable action) {
11701        if (action != null) {
11702            final AttachInfo attachInfo = mAttachInfo;
11703            if (attachInfo != null) {
11704                attachInfo.mHandler.removeCallbacks(action);
11705                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11706                        Choreographer.CALLBACK_ANIMATION, action, null);
11707            }
11708            // Assume that post will succeed later
11709            ViewRootImpl.getRunQueue().removeCallbacks(action);
11710        }
11711        return true;
11712    }
11713
11714    /**
11715     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11716     * Use this to invalidate the View from a non-UI thread.</p>
11717     *
11718     * <p>This method can be invoked from outside of the UI thread
11719     * only when this View is attached to a window.</p>
11720     *
11721     * @see #invalidate()
11722     * @see #postInvalidateDelayed(long)
11723     */
11724    public void postInvalidate() {
11725        postInvalidateDelayed(0);
11726    }
11727
11728    /**
11729     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11730     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11731     *
11732     * <p>This method can be invoked from outside of the UI thread
11733     * only when this View is attached to a window.</p>
11734     *
11735     * @param left The left coordinate of the rectangle to invalidate.
11736     * @param top The top coordinate of the rectangle to invalidate.
11737     * @param right The right coordinate of the rectangle to invalidate.
11738     * @param bottom The bottom coordinate of the rectangle to invalidate.
11739     *
11740     * @see #invalidate(int, int, int, int)
11741     * @see #invalidate(Rect)
11742     * @see #postInvalidateDelayed(long, int, int, int, int)
11743     */
11744    public void postInvalidate(int left, int top, int right, int bottom) {
11745        postInvalidateDelayed(0, left, top, right, bottom);
11746    }
11747
11748    /**
11749     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11750     * loop. Waits for the specified amount of time.</p>
11751     *
11752     * <p>This method can be invoked from outside of the UI thread
11753     * only when this View is attached to a window.</p>
11754     *
11755     * @param delayMilliseconds the duration in milliseconds to delay the
11756     *         invalidation by
11757     *
11758     * @see #invalidate()
11759     * @see #postInvalidate()
11760     */
11761    public void postInvalidateDelayed(long delayMilliseconds) {
11762        // We try only with the AttachInfo because there's no point in invalidating
11763        // if we are not attached to our window
11764        final AttachInfo attachInfo = mAttachInfo;
11765        if (attachInfo != null) {
11766            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11767        }
11768    }
11769
11770    /**
11771     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11772     * through the event loop. Waits for the specified amount of time.</p>
11773     *
11774     * <p>This method can be invoked from outside of the UI thread
11775     * only when this View is attached to a window.</p>
11776     *
11777     * @param delayMilliseconds the duration in milliseconds to delay the
11778     *         invalidation by
11779     * @param left The left coordinate of the rectangle to invalidate.
11780     * @param top The top coordinate of the rectangle to invalidate.
11781     * @param right The right coordinate of the rectangle to invalidate.
11782     * @param bottom The bottom coordinate of the rectangle to invalidate.
11783     *
11784     * @see #invalidate(int, int, int, int)
11785     * @see #invalidate(Rect)
11786     * @see #postInvalidate(int, int, int, int)
11787     */
11788    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11789            int right, int bottom) {
11790
11791        // We try only with the AttachInfo because there's no point in invalidating
11792        // if we are not attached to our window
11793        final AttachInfo attachInfo = mAttachInfo;
11794        if (attachInfo != null) {
11795            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11796            info.target = this;
11797            info.left = left;
11798            info.top = top;
11799            info.right = right;
11800            info.bottom = bottom;
11801
11802            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11803        }
11804    }
11805
11806    /**
11807     * <p>Cause an invalidate to happen on the next animation time step, typically the
11808     * next display frame.</p>
11809     *
11810     * <p>This method can be invoked from outside of the UI thread
11811     * only when this View is attached to a window.</p>
11812     *
11813     * @see #invalidate()
11814     */
11815    public void postInvalidateOnAnimation() {
11816        // We try only with the AttachInfo because there's no point in invalidating
11817        // if we are not attached to our window
11818        final AttachInfo attachInfo = mAttachInfo;
11819        if (attachInfo != null) {
11820            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11821        }
11822    }
11823
11824    /**
11825     * <p>Cause an invalidate of the specified area to happen on the next animation
11826     * time step, typically the next display frame.</p>
11827     *
11828     * <p>This method can be invoked from outside of the UI thread
11829     * only when this View is attached to a window.</p>
11830     *
11831     * @param left The left coordinate of the rectangle to invalidate.
11832     * @param top The top coordinate of the rectangle to invalidate.
11833     * @param right The right coordinate of the rectangle to invalidate.
11834     * @param bottom The bottom coordinate of the rectangle to invalidate.
11835     *
11836     * @see #invalidate(int, int, int, int)
11837     * @see #invalidate(Rect)
11838     */
11839    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11840        // We try only with the AttachInfo because there's no point in invalidating
11841        // if we are not attached to our window
11842        final AttachInfo attachInfo = mAttachInfo;
11843        if (attachInfo != null) {
11844            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11845            info.target = this;
11846            info.left = left;
11847            info.top = top;
11848            info.right = right;
11849            info.bottom = bottom;
11850
11851            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11852        }
11853    }
11854
11855    /**
11856     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11857     * This event is sent at most once every
11858     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11859     */
11860    private void postSendViewScrolledAccessibilityEventCallback() {
11861        if (mSendViewScrolledAccessibilityEvent == null) {
11862            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11863        }
11864        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11865            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11866            postDelayed(mSendViewScrolledAccessibilityEvent,
11867                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11868        }
11869    }
11870
11871    /**
11872     * Called by a parent to request that a child update its values for mScrollX
11873     * and mScrollY if necessary. This will typically be done if the child is
11874     * animating a scroll using a {@link android.widget.Scroller Scroller}
11875     * object.
11876     */
11877    public void computeScroll() {
11878    }
11879
11880    /**
11881     * <p>Indicate whether the horizontal edges are faded when the view is
11882     * scrolled horizontally.</p>
11883     *
11884     * @return true if the horizontal edges should are faded on scroll, false
11885     *         otherwise
11886     *
11887     * @see #setHorizontalFadingEdgeEnabled(boolean)
11888     *
11889     * @attr ref android.R.styleable#View_requiresFadingEdge
11890     */
11891    public boolean isHorizontalFadingEdgeEnabled() {
11892        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11893    }
11894
11895    /**
11896     * <p>Define whether the horizontal edges should be faded when this view
11897     * is scrolled horizontally.</p>
11898     *
11899     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11900     *                                    be faded when the view is scrolled
11901     *                                    horizontally
11902     *
11903     * @see #isHorizontalFadingEdgeEnabled()
11904     *
11905     * @attr ref android.R.styleable#View_requiresFadingEdge
11906     */
11907    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11908        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11909            if (horizontalFadingEdgeEnabled) {
11910                initScrollCache();
11911            }
11912
11913            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11914        }
11915    }
11916
11917    /**
11918     * <p>Indicate whether the vertical edges are faded when the view is
11919     * scrolled horizontally.</p>
11920     *
11921     * @return true if the vertical edges should are faded on scroll, false
11922     *         otherwise
11923     *
11924     * @see #setVerticalFadingEdgeEnabled(boolean)
11925     *
11926     * @attr ref android.R.styleable#View_requiresFadingEdge
11927     */
11928    public boolean isVerticalFadingEdgeEnabled() {
11929        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11930    }
11931
11932    /**
11933     * <p>Define whether the vertical edges should be faded when this view
11934     * is scrolled vertically.</p>
11935     *
11936     * @param verticalFadingEdgeEnabled true if the vertical edges should
11937     *                                  be faded when the view is scrolled
11938     *                                  vertically
11939     *
11940     * @see #isVerticalFadingEdgeEnabled()
11941     *
11942     * @attr ref android.R.styleable#View_requiresFadingEdge
11943     */
11944    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11945        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11946            if (verticalFadingEdgeEnabled) {
11947                initScrollCache();
11948            }
11949
11950            mViewFlags ^= FADING_EDGE_VERTICAL;
11951        }
11952    }
11953
11954    /**
11955     * Returns the strength, or intensity, of the top faded edge. The strength is
11956     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11957     * returns 0.0 or 1.0 but no value in between.
11958     *
11959     * Subclasses should override this method to provide a smoother fade transition
11960     * when scrolling occurs.
11961     *
11962     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11963     */
11964    protected float getTopFadingEdgeStrength() {
11965        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11966    }
11967
11968    /**
11969     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11970     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11971     * returns 0.0 or 1.0 but no value in between.
11972     *
11973     * Subclasses should override this method to provide a smoother fade transition
11974     * when scrolling occurs.
11975     *
11976     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11977     */
11978    protected float getBottomFadingEdgeStrength() {
11979        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11980                computeVerticalScrollRange() ? 1.0f : 0.0f;
11981    }
11982
11983    /**
11984     * Returns the strength, or intensity, of the left faded edge. The strength is
11985     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11986     * returns 0.0 or 1.0 but no value in between.
11987     *
11988     * Subclasses should override this method to provide a smoother fade transition
11989     * when scrolling occurs.
11990     *
11991     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11992     */
11993    protected float getLeftFadingEdgeStrength() {
11994        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11995    }
11996
11997    /**
11998     * Returns the strength, or intensity, of the right faded edge. The strength is
11999     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12000     * returns 0.0 or 1.0 but no value in between.
12001     *
12002     * Subclasses should override this method to provide a smoother fade transition
12003     * when scrolling occurs.
12004     *
12005     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12006     */
12007    protected float getRightFadingEdgeStrength() {
12008        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12009                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12010    }
12011
12012    /**
12013     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12014     * scrollbar is not drawn by default.</p>
12015     *
12016     * @return true if the horizontal scrollbar should be painted, false
12017     *         otherwise
12018     *
12019     * @see #setHorizontalScrollBarEnabled(boolean)
12020     */
12021    public boolean isHorizontalScrollBarEnabled() {
12022        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12023    }
12024
12025    /**
12026     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12027     * scrollbar is not drawn by default.</p>
12028     *
12029     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12030     *                                   be painted
12031     *
12032     * @see #isHorizontalScrollBarEnabled()
12033     */
12034    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12035        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12036            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12037            computeOpaqueFlags();
12038            resolvePadding();
12039        }
12040    }
12041
12042    /**
12043     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12044     * scrollbar is not drawn by default.</p>
12045     *
12046     * @return true if the vertical scrollbar should be painted, false
12047     *         otherwise
12048     *
12049     * @see #setVerticalScrollBarEnabled(boolean)
12050     */
12051    public boolean isVerticalScrollBarEnabled() {
12052        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12053    }
12054
12055    /**
12056     * <p>Define whether the vertical scrollbar should be drawn or not. The
12057     * scrollbar is not drawn by default.</p>
12058     *
12059     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12060     *                                 be painted
12061     *
12062     * @see #isVerticalScrollBarEnabled()
12063     */
12064    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12065        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12066            mViewFlags ^= SCROLLBARS_VERTICAL;
12067            computeOpaqueFlags();
12068            resolvePadding();
12069        }
12070    }
12071
12072    /**
12073     * @hide
12074     */
12075    protected void recomputePadding() {
12076        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12077    }
12078
12079    /**
12080     * Define whether scrollbars will fade when the view is not scrolling.
12081     *
12082     * @param fadeScrollbars wheter to enable fading
12083     *
12084     * @attr ref android.R.styleable#View_fadeScrollbars
12085     */
12086    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12087        initScrollCache();
12088        final ScrollabilityCache scrollabilityCache = mScrollCache;
12089        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12090        if (fadeScrollbars) {
12091            scrollabilityCache.state = ScrollabilityCache.OFF;
12092        } else {
12093            scrollabilityCache.state = ScrollabilityCache.ON;
12094        }
12095    }
12096
12097    /**
12098     *
12099     * Returns true if scrollbars will fade when this view is not scrolling
12100     *
12101     * @return true if scrollbar fading is enabled
12102     *
12103     * @attr ref android.R.styleable#View_fadeScrollbars
12104     */
12105    public boolean isScrollbarFadingEnabled() {
12106        return mScrollCache != null && mScrollCache.fadeScrollBars;
12107    }
12108
12109    /**
12110     *
12111     * Returns the delay before scrollbars fade.
12112     *
12113     * @return the delay before scrollbars fade
12114     *
12115     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12116     */
12117    public int getScrollBarDefaultDelayBeforeFade() {
12118        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12119                mScrollCache.scrollBarDefaultDelayBeforeFade;
12120    }
12121
12122    /**
12123     * Define the delay before scrollbars fade.
12124     *
12125     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12126     *
12127     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12128     */
12129    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12130        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12131    }
12132
12133    /**
12134     *
12135     * Returns the scrollbar fade duration.
12136     *
12137     * @return the scrollbar fade duration
12138     *
12139     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12140     */
12141    public int getScrollBarFadeDuration() {
12142        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12143                mScrollCache.scrollBarFadeDuration;
12144    }
12145
12146    /**
12147     * Define the scrollbar fade duration.
12148     *
12149     * @param scrollBarFadeDuration - the scrollbar fade duration
12150     *
12151     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12152     */
12153    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12154        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12155    }
12156
12157    /**
12158     *
12159     * Returns the scrollbar size.
12160     *
12161     * @return the scrollbar size
12162     *
12163     * @attr ref android.R.styleable#View_scrollbarSize
12164     */
12165    public int getScrollBarSize() {
12166        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12167                mScrollCache.scrollBarSize;
12168    }
12169
12170    /**
12171     * Define the scrollbar size.
12172     *
12173     * @param scrollBarSize - the scrollbar size
12174     *
12175     * @attr ref android.R.styleable#View_scrollbarSize
12176     */
12177    public void setScrollBarSize(int scrollBarSize) {
12178        getScrollCache().scrollBarSize = scrollBarSize;
12179    }
12180
12181    /**
12182     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12183     * inset. When inset, they add to the padding of the view. And the scrollbars
12184     * can be drawn inside the padding area or on the edge of the view. For example,
12185     * if a view has a background drawable and you want to draw the scrollbars
12186     * inside the padding specified by the drawable, you can use
12187     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12188     * appear at the edge of the view, ignoring the padding, then you can use
12189     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12190     * @param style the style of the scrollbars. Should be one of
12191     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12192     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12193     * @see #SCROLLBARS_INSIDE_OVERLAY
12194     * @see #SCROLLBARS_INSIDE_INSET
12195     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12196     * @see #SCROLLBARS_OUTSIDE_INSET
12197     *
12198     * @attr ref android.R.styleable#View_scrollbarStyle
12199     */
12200    public void setScrollBarStyle(@ScrollBarStyle int style) {
12201        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12202            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12203            computeOpaqueFlags();
12204            resolvePadding();
12205        }
12206    }
12207
12208    /**
12209     * <p>Returns the current scrollbar style.</p>
12210     * @return the current scrollbar style
12211     * @see #SCROLLBARS_INSIDE_OVERLAY
12212     * @see #SCROLLBARS_INSIDE_INSET
12213     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12214     * @see #SCROLLBARS_OUTSIDE_INSET
12215     *
12216     * @attr ref android.R.styleable#View_scrollbarStyle
12217     */
12218    @ViewDebug.ExportedProperty(mapping = {
12219            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12220            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12221            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12222            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12223    })
12224    @ScrollBarStyle
12225    public int getScrollBarStyle() {
12226        return mViewFlags & SCROLLBARS_STYLE_MASK;
12227    }
12228
12229    /**
12230     * <p>Compute the horizontal range that the horizontal scrollbar
12231     * represents.</p>
12232     *
12233     * <p>The range is expressed in arbitrary units that must be the same as the
12234     * units used by {@link #computeHorizontalScrollExtent()} and
12235     * {@link #computeHorizontalScrollOffset()}.</p>
12236     *
12237     * <p>The default range is the drawing width of this view.</p>
12238     *
12239     * @return the total horizontal range represented by the horizontal
12240     *         scrollbar
12241     *
12242     * @see #computeHorizontalScrollExtent()
12243     * @see #computeHorizontalScrollOffset()
12244     * @see android.widget.ScrollBarDrawable
12245     */
12246    protected int computeHorizontalScrollRange() {
12247        return getWidth();
12248    }
12249
12250    /**
12251     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12252     * within the horizontal range. This value is used to compute the position
12253     * of the thumb within the scrollbar's track.</p>
12254     *
12255     * <p>The range is expressed in arbitrary units that must be the same as the
12256     * units used by {@link #computeHorizontalScrollRange()} and
12257     * {@link #computeHorizontalScrollExtent()}.</p>
12258     *
12259     * <p>The default offset is the scroll offset of this view.</p>
12260     *
12261     * @return the horizontal offset of the scrollbar's thumb
12262     *
12263     * @see #computeHorizontalScrollRange()
12264     * @see #computeHorizontalScrollExtent()
12265     * @see android.widget.ScrollBarDrawable
12266     */
12267    protected int computeHorizontalScrollOffset() {
12268        return mScrollX;
12269    }
12270
12271    /**
12272     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12273     * within the horizontal range. This value is used to compute the length
12274     * of the thumb within the scrollbar's track.</p>
12275     *
12276     * <p>The range is expressed in arbitrary units that must be the same as the
12277     * units used by {@link #computeHorizontalScrollRange()} and
12278     * {@link #computeHorizontalScrollOffset()}.</p>
12279     *
12280     * <p>The default extent is the drawing width of this view.</p>
12281     *
12282     * @return the horizontal extent of the scrollbar's thumb
12283     *
12284     * @see #computeHorizontalScrollRange()
12285     * @see #computeHorizontalScrollOffset()
12286     * @see android.widget.ScrollBarDrawable
12287     */
12288    protected int computeHorizontalScrollExtent() {
12289        return getWidth();
12290    }
12291
12292    /**
12293     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12294     *
12295     * <p>The range is expressed in arbitrary units that must be the same as the
12296     * units used by {@link #computeVerticalScrollExtent()} and
12297     * {@link #computeVerticalScrollOffset()}.</p>
12298     *
12299     * @return the total vertical range represented by the vertical scrollbar
12300     *
12301     * <p>The default range is the drawing height of this view.</p>
12302     *
12303     * @see #computeVerticalScrollExtent()
12304     * @see #computeVerticalScrollOffset()
12305     * @see android.widget.ScrollBarDrawable
12306     */
12307    protected int computeVerticalScrollRange() {
12308        return getHeight();
12309    }
12310
12311    /**
12312     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12313     * within the horizontal range. This value is used to compute the position
12314     * of the thumb within the scrollbar's track.</p>
12315     *
12316     * <p>The range is expressed in arbitrary units that must be the same as the
12317     * units used by {@link #computeVerticalScrollRange()} and
12318     * {@link #computeVerticalScrollExtent()}.</p>
12319     *
12320     * <p>The default offset is the scroll offset of this view.</p>
12321     *
12322     * @return the vertical offset of the scrollbar's thumb
12323     *
12324     * @see #computeVerticalScrollRange()
12325     * @see #computeVerticalScrollExtent()
12326     * @see android.widget.ScrollBarDrawable
12327     */
12328    protected int computeVerticalScrollOffset() {
12329        return mScrollY;
12330    }
12331
12332    /**
12333     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12334     * within the vertical range. This value is used to compute the length
12335     * of the thumb within the scrollbar's track.</p>
12336     *
12337     * <p>The range is expressed in arbitrary units that must be the same as the
12338     * units used by {@link #computeVerticalScrollRange()} and
12339     * {@link #computeVerticalScrollOffset()}.</p>
12340     *
12341     * <p>The default extent is the drawing height of this view.</p>
12342     *
12343     * @return the vertical extent of the scrollbar's thumb
12344     *
12345     * @see #computeVerticalScrollRange()
12346     * @see #computeVerticalScrollOffset()
12347     * @see android.widget.ScrollBarDrawable
12348     */
12349    protected int computeVerticalScrollExtent() {
12350        return getHeight();
12351    }
12352
12353    /**
12354     * Check if this view can be scrolled horizontally in a certain direction.
12355     *
12356     * @param direction Negative to check scrolling left, positive to check scrolling right.
12357     * @return true if this view can be scrolled in the specified direction, false otherwise.
12358     */
12359    public boolean canScrollHorizontally(int direction) {
12360        final int offset = computeHorizontalScrollOffset();
12361        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12362        if (range == 0) return false;
12363        if (direction < 0) {
12364            return offset > 0;
12365        } else {
12366            return offset < range - 1;
12367        }
12368    }
12369
12370    /**
12371     * Check if this view can be scrolled vertically in a certain direction.
12372     *
12373     * @param direction Negative to check scrolling up, positive to check scrolling down.
12374     * @return true if this view can be scrolled in the specified direction, false otherwise.
12375     */
12376    public boolean canScrollVertically(int direction) {
12377        final int offset = computeVerticalScrollOffset();
12378        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12379        if (range == 0) return false;
12380        if (direction < 0) {
12381            return offset > 0;
12382        } else {
12383            return offset < range - 1;
12384        }
12385    }
12386
12387    /**
12388     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12389     * scrollbars are painted only if they have been awakened first.</p>
12390     *
12391     * @param canvas the canvas on which to draw the scrollbars
12392     *
12393     * @see #awakenScrollBars(int)
12394     */
12395    protected final void onDrawScrollBars(Canvas canvas) {
12396        // scrollbars are drawn only when the animation is running
12397        final ScrollabilityCache cache = mScrollCache;
12398        if (cache != null) {
12399
12400            int state = cache.state;
12401
12402            if (state == ScrollabilityCache.OFF) {
12403                return;
12404            }
12405
12406            boolean invalidate = false;
12407
12408            if (state == ScrollabilityCache.FADING) {
12409                // We're fading -- get our fade interpolation
12410                if (cache.interpolatorValues == null) {
12411                    cache.interpolatorValues = new float[1];
12412                }
12413
12414                float[] values = cache.interpolatorValues;
12415
12416                // Stops the animation if we're done
12417                if (cache.scrollBarInterpolator.timeToValues(values) ==
12418                        Interpolator.Result.FREEZE_END) {
12419                    cache.state = ScrollabilityCache.OFF;
12420                } else {
12421                    cache.scrollBar.setAlpha(Math.round(values[0]));
12422                }
12423
12424                // This will make the scroll bars inval themselves after
12425                // drawing. We only want this when we're fading so that
12426                // we prevent excessive redraws
12427                invalidate = true;
12428            } else {
12429                // We're just on -- but we may have been fading before so
12430                // reset alpha
12431                cache.scrollBar.setAlpha(255);
12432            }
12433
12434
12435            final int viewFlags = mViewFlags;
12436
12437            final boolean drawHorizontalScrollBar =
12438                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12439            final boolean drawVerticalScrollBar =
12440                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12441                && !isVerticalScrollBarHidden();
12442
12443            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12444                final int width = mRight - mLeft;
12445                final int height = mBottom - mTop;
12446
12447                final ScrollBarDrawable scrollBar = cache.scrollBar;
12448
12449                final int scrollX = mScrollX;
12450                final int scrollY = mScrollY;
12451                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12452
12453                int left;
12454                int top;
12455                int right;
12456                int bottom;
12457
12458                if (drawHorizontalScrollBar) {
12459                    int size = scrollBar.getSize(false);
12460                    if (size <= 0) {
12461                        size = cache.scrollBarSize;
12462                    }
12463
12464                    scrollBar.setParameters(computeHorizontalScrollRange(),
12465                                            computeHorizontalScrollOffset(),
12466                                            computeHorizontalScrollExtent(), false);
12467                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12468                            getVerticalScrollbarWidth() : 0;
12469                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12470                    left = scrollX + (mPaddingLeft & inside);
12471                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12472                    bottom = top + size;
12473                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12474                    if (invalidate) {
12475                        invalidate(left, top, right, bottom);
12476                    }
12477                }
12478
12479                if (drawVerticalScrollBar) {
12480                    int size = scrollBar.getSize(true);
12481                    if (size <= 0) {
12482                        size = cache.scrollBarSize;
12483                    }
12484
12485                    scrollBar.setParameters(computeVerticalScrollRange(),
12486                                            computeVerticalScrollOffset(),
12487                                            computeVerticalScrollExtent(), true);
12488                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12489                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12490                        verticalScrollbarPosition = isLayoutRtl() ?
12491                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12492                    }
12493                    switch (verticalScrollbarPosition) {
12494                        default:
12495                        case SCROLLBAR_POSITION_RIGHT:
12496                            left = scrollX + width - size - (mUserPaddingRight & inside);
12497                            break;
12498                        case SCROLLBAR_POSITION_LEFT:
12499                            left = scrollX + (mUserPaddingLeft & inside);
12500                            break;
12501                    }
12502                    top = scrollY + (mPaddingTop & inside);
12503                    right = left + size;
12504                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12505                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12506                    if (invalidate) {
12507                        invalidate(left, top, right, bottom);
12508                    }
12509                }
12510            }
12511        }
12512    }
12513
12514    /**
12515     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12516     * FastScroller is visible.
12517     * @return whether to temporarily hide the vertical scrollbar
12518     * @hide
12519     */
12520    protected boolean isVerticalScrollBarHidden() {
12521        return false;
12522    }
12523
12524    /**
12525     * <p>Draw the horizontal scrollbar if
12526     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12527     *
12528     * @param canvas the canvas on which to draw the scrollbar
12529     * @param scrollBar the scrollbar's drawable
12530     *
12531     * @see #isHorizontalScrollBarEnabled()
12532     * @see #computeHorizontalScrollRange()
12533     * @see #computeHorizontalScrollExtent()
12534     * @see #computeHorizontalScrollOffset()
12535     * @see android.widget.ScrollBarDrawable
12536     * @hide
12537     */
12538    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12539            int l, int t, int r, int b) {
12540        scrollBar.setBounds(l, t, r, b);
12541        scrollBar.draw(canvas);
12542    }
12543
12544    /**
12545     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12546     * returns true.</p>
12547     *
12548     * @param canvas the canvas on which to draw the scrollbar
12549     * @param scrollBar the scrollbar's drawable
12550     *
12551     * @see #isVerticalScrollBarEnabled()
12552     * @see #computeVerticalScrollRange()
12553     * @see #computeVerticalScrollExtent()
12554     * @see #computeVerticalScrollOffset()
12555     * @see android.widget.ScrollBarDrawable
12556     * @hide
12557     */
12558    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12559            int l, int t, int r, int b) {
12560        scrollBar.setBounds(l, t, r, b);
12561        scrollBar.draw(canvas);
12562    }
12563
12564    /**
12565     * Implement this to do your drawing.
12566     *
12567     * @param canvas the canvas on which the background will be drawn
12568     */
12569    protected void onDraw(Canvas canvas) {
12570    }
12571
12572    /*
12573     * Caller is responsible for calling requestLayout if necessary.
12574     * (This allows addViewInLayout to not request a new layout.)
12575     */
12576    void assignParent(ViewParent parent) {
12577        if (mParent == null) {
12578            mParent = parent;
12579        } else if (parent == null) {
12580            mParent = null;
12581        } else {
12582            throw new RuntimeException("view " + this + " being added, but"
12583                    + " it already has a parent");
12584        }
12585    }
12586
12587    /**
12588     * This is called when the view is attached to a window.  At this point it
12589     * has a Surface and will start drawing.  Note that this function is
12590     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12591     * however it may be called any time before the first onDraw -- including
12592     * before or after {@link #onMeasure(int, int)}.
12593     *
12594     * @see #onDetachedFromWindow()
12595     */
12596    protected void onAttachedToWindow() {
12597        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12598            mParent.requestTransparentRegion(this);
12599        }
12600
12601        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12602            initialAwakenScrollBars();
12603            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12604        }
12605
12606        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12607
12608        jumpDrawablesToCurrentState();
12609
12610        resetSubtreeAccessibilityStateChanged();
12611
12612        if (isFocused()) {
12613            InputMethodManager imm = InputMethodManager.peekInstance();
12614            imm.focusIn(this);
12615        }
12616    }
12617
12618    /**
12619     * Resolve all RTL related properties.
12620     *
12621     * @return true if resolution of RTL properties has been done
12622     *
12623     * @hide
12624     */
12625    public boolean resolveRtlPropertiesIfNeeded() {
12626        if (!needRtlPropertiesResolution()) return false;
12627
12628        // Order is important here: LayoutDirection MUST be resolved first
12629        if (!isLayoutDirectionResolved()) {
12630            resolveLayoutDirection();
12631            resolveLayoutParams();
12632        }
12633        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12634        if (!isTextDirectionResolved()) {
12635            resolveTextDirection();
12636        }
12637        if (!isTextAlignmentResolved()) {
12638            resolveTextAlignment();
12639        }
12640        // Should resolve Drawables before Padding because we need the layout direction of the
12641        // Drawable to correctly resolve Padding.
12642        if (!isDrawablesResolved()) {
12643            resolveDrawables();
12644        }
12645        if (!isPaddingResolved()) {
12646            resolvePadding();
12647        }
12648        onRtlPropertiesChanged(getLayoutDirection());
12649        return true;
12650    }
12651
12652    /**
12653     * Reset resolution of all RTL related properties.
12654     *
12655     * @hide
12656     */
12657    public void resetRtlProperties() {
12658        resetResolvedLayoutDirection();
12659        resetResolvedTextDirection();
12660        resetResolvedTextAlignment();
12661        resetResolvedPadding();
12662        resetResolvedDrawables();
12663    }
12664
12665    /**
12666     * @see #onScreenStateChanged(int)
12667     */
12668    void dispatchScreenStateChanged(int screenState) {
12669        onScreenStateChanged(screenState);
12670    }
12671
12672    /**
12673     * This method is called whenever the state of the screen this view is
12674     * attached to changes. A state change will usually occurs when the screen
12675     * turns on or off (whether it happens automatically or the user does it
12676     * manually.)
12677     *
12678     * @param screenState The new state of the screen. Can be either
12679     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12680     */
12681    public void onScreenStateChanged(int screenState) {
12682    }
12683
12684    /**
12685     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12686     */
12687    private boolean hasRtlSupport() {
12688        return mContext.getApplicationInfo().hasRtlSupport();
12689    }
12690
12691    /**
12692     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12693     * RTL not supported)
12694     */
12695    private boolean isRtlCompatibilityMode() {
12696        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12697        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12698    }
12699
12700    /**
12701     * @return true if RTL properties need resolution.
12702     *
12703     */
12704    private boolean needRtlPropertiesResolution() {
12705        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12706    }
12707
12708    /**
12709     * Called when any RTL property (layout direction or text direction or text alignment) has
12710     * been changed.
12711     *
12712     * Subclasses need to override this method to take care of cached information that depends on the
12713     * resolved layout direction, or to inform child views that inherit their layout direction.
12714     *
12715     * The default implementation does nothing.
12716     *
12717     * @param layoutDirection the direction of the layout
12718     *
12719     * @see #LAYOUT_DIRECTION_LTR
12720     * @see #LAYOUT_DIRECTION_RTL
12721     */
12722    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12723    }
12724
12725    /**
12726     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12727     * that the parent directionality can and will be resolved before its children.
12728     *
12729     * @return true if resolution has been done, false otherwise.
12730     *
12731     * @hide
12732     */
12733    public boolean resolveLayoutDirection() {
12734        // Clear any previous layout direction resolution
12735        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12736
12737        if (hasRtlSupport()) {
12738            // Set resolved depending on layout direction
12739            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12740                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12741                case LAYOUT_DIRECTION_INHERIT:
12742                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12743                    // later to get the correct resolved value
12744                    if (!canResolveLayoutDirection()) return false;
12745
12746                    // Parent has not yet resolved, LTR is still the default
12747                    try {
12748                        if (!mParent.isLayoutDirectionResolved()) return false;
12749
12750                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12751                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12752                        }
12753                    } catch (AbstractMethodError e) {
12754                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12755                                " does not fully implement ViewParent", e);
12756                    }
12757                    break;
12758                case LAYOUT_DIRECTION_RTL:
12759                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12760                    break;
12761                case LAYOUT_DIRECTION_LOCALE:
12762                    if((LAYOUT_DIRECTION_RTL ==
12763                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12764                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12765                    }
12766                    break;
12767                default:
12768                    // Nothing to do, LTR by default
12769            }
12770        }
12771
12772        // Set to resolved
12773        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12774        return true;
12775    }
12776
12777    /**
12778     * Check if layout direction resolution can be done.
12779     *
12780     * @return true if layout direction resolution can be done otherwise return false.
12781     */
12782    public boolean canResolveLayoutDirection() {
12783        switch (getRawLayoutDirection()) {
12784            case LAYOUT_DIRECTION_INHERIT:
12785                if (mParent != null) {
12786                    try {
12787                        return mParent.canResolveLayoutDirection();
12788                    } catch (AbstractMethodError e) {
12789                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12790                                " does not fully implement ViewParent", e);
12791                    }
12792                }
12793                return false;
12794
12795            default:
12796                return true;
12797        }
12798    }
12799
12800    /**
12801     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12802     * {@link #onMeasure(int, int)}.
12803     *
12804     * @hide
12805     */
12806    public void resetResolvedLayoutDirection() {
12807        // Reset the current resolved bits
12808        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12809    }
12810
12811    /**
12812     * @return true if the layout direction is inherited.
12813     *
12814     * @hide
12815     */
12816    public boolean isLayoutDirectionInherited() {
12817        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12818    }
12819
12820    /**
12821     * @return true if layout direction has been resolved.
12822     */
12823    public boolean isLayoutDirectionResolved() {
12824        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12825    }
12826
12827    /**
12828     * Return if padding has been resolved
12829     *
12830     * @hide
12831     */
12832    boolean isPaddingResolved() {
12833        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12834    }
12835
12836    /**
12837     * Resolves padding depending on layout direction, if applicable, and
12838     * recomputes internal padding values to adjust for scroll bars.
12839     *
12840     * @hide
12841     */
12842    public void resolvePadding() {
12843        final int resolvedLayoutDirection = getLayoutDirection();
12844
12845        if (!isRtlCompatibilityMode()) {
12846            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12847            // If start / end padding are defined, they will be resolved (hence overriding) to
12848            // left / right or right / left depending on the resolved layout direction.
12849            // If start / end padding are not defined, use the left / right ones.
12850            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12851                Rect padding = sThreadLocal.get();
12852                if (padding == null) {
12853                    padding = new Rect();
12854                    sThreadLocal.set(padding);
12855                }
12856                mBackground.getPadding(padding);
12857                if (!mLeftPaddingDefined) {
12858                    mUserPaddingLeftInitial = padding.left;
12859                }
12860                if (!mRightPaddingDefined) {
12861                    mUserPaddingRightInitial = padding.right;
12862                }
12863            }
12864            switch (resolvedLayoutDirection) {
12865                case LAYOUT_DIRECTION_RTL:
12866                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12867                        mUserPaddingRight = mUserPaddingStart;
12868                    } else {
12869                        mUserPaddingRight = mUserPaddingRightInitial;
12870                    }
12871                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12872                        mUserPaddingLeft = mUserPaddingEnd;
12873                    } else {
12874                        mUserPaddingLeft = mUserPaddingLeftInitial;
12875                    }
12876                    break;
12877                case LAYOUT_DIRECTION_LTR:
12878                default:
12879                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12880                        mUserPaddingLeft = mUserPaddingStart;
12881                    } else {
12882                        mUserPaddingLeft = mUserPaddingLeftInitial;
12883                    }
12884                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12885                        mUserPaddingRight = mUserPaddingEnd;
12886                    } else {
12887                        mUserPaddingRight = mUserPaddingRightInitial;
12888                    }
12889            }
12890
12891            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12892        }
12893
12894        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12895        onRtlPropertiesChanged(resolvedLayoutDirection);
12896
12897        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12898    }
12899
12900    /**
12901     * Reset the resolved layout direction.
12902     *
12903     * @hide
12904     */
12905    public void resetResolvedPadding() {
12906        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12907    }
12908
12909    /**
12910     * This is called when the view is detached from a window.  At this point it
12911     * no longer has a surface for drawing.
12912     *
12913     * @see #onAttachedToWindow()
12914     */
12915    protected void onDetachedFromWindow() {
12916    }
12917
12918    /**
12919     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12920     * after onDetachedFromWindow().
12921     *
12922     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12923     * The super method should be called at the end of the overriden method to ensure
12924     * subclasses are destroyed first
12925     *
12926     * @hide
12927     */
12928    protected void onDetachedFromWindowInternal() {
12929        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12930        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12931
12932        removeUnsetPressCallback();
12933        removeLongPressCallback();
12934        removePerformClickCallback();
12935        removeSendViewScrolledAccessibilityEventCallback();
12936        stopNestedScroll();
12937
12938        destroyDrawingCache();
12939
12940        cleanupDraw();
12941        mCurrentAnimation = null;
12942    }
12943
12944    private void cleanupDraw() {
12945        resetDisplayList();
12946        if (mAttachInfo != null) {
12947            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12948        }
12949    }
12950
12951    /**
12952     * This method ensures the hardware renderer is in a valid state
12953     * before executing the specified action.
12954     *
12955     * This method will attempt to set a valid state even if the window
12956     * the renderer is attached to was destroyed.
12957     *
12958     * This method is not guaranteed to work. If the hardware renderer
12959     * does not exist or cannot be put in a valid state, this method
12960     * will not executed the specified action.
12961     *
12962     * The specified action is executed synchronously.
12963     *
12964     * @param action The action to execute after the renderer is in a valid state
12965     *
12966     * @return True if the specified Runnable was executed, false otherwise
12967     *
12968     * @hide
12969     */
12970    public boolean executeHardwareAction(Runnable action) {
12971        //noinspection SimplifiableIfStatement
12972        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12973            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12974        }
12975        return false;
12976    }
12977
12978    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12979    }
12980
12981    /**
12982     * @return The number of times this view has been attached to a window
12983     */
12984    protected int getWindowAttachCount() {
12985        return mWindowAttachCount;
12986    }
12987
12988    /**
12989     * Retrieve a unique token identifying the window this view is attached to.
12990     * @return Return the window's token for use in
12991     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12992     */
12993    public IBinder getWindowToken() {
12994        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12995    }
12996
12997    /**
12998     * Retrieve the {@link WindowId} for the window this view is
12999     * currently attached to.
13000     */
13001    public WindowId getWindowId() {
13002        if (mAttachInfo == null) {
13003            return null;
13004        }
13005        if (mAttachInfo.mWindowId == null) {
13006            try {
13007                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13008                        mAttachInfo.mWindowToken);
13009                mAttachInfo.mWindowId = new WindowId(
13010                        mAttachInfo.mIWindowId);
13011            } catch (RemoteException e) {
13012            }
13013        }
13014        return mAttachInfo.mWindowId;
13015    }
13016
13017    /**
13018     * Retrieve a unique token identifying the top-level "real" window of
13019     * the window that this view is attached to.  That is, this is like
13020     * {@link #getWindowToken}, except if the window this view in is a panel
13021     * window (attached to another containing window), then the token of
13022     * the containing window is returned instead.
13023     *
13024     * @return Returns the associated window token, either
13025     * {@link #getWindowToken()} or the containing window's token.
13026     */
13027    public IBinder getApplicationWindowToken() {
13028        AttachInfo ai = mAttachInfo;
13029        if (ai != null) {
13030            IBinder appWindowToken = ai.mPanelParentWindowToken;
13031            if (appWindowToken == null) {
13032                appWindowToken = ai.mWindowToken;
13033            }
13034            return appWindowToken;
13035        }
13036        return null;
13037    }
13038
13039    /**
13040     * Gets the logical display to which the view's window has been attached.
13041     *
13042     * @return The logical display, or null if the view is not currently attached to a window.
13043     */
13044    public Display getDisplay() {
13045        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13046    }
13047
13048    /**
13049     * Retrieve private session object this view hierarchy is using to
13050     * communicate with the window manager.
13051     * @return the session object to communicate with the window manager
13052     */
13053    /*package*/ IWindowSession getWindowSession() {
13054        return mAttachInfo != null ? mAttachInfo.mSession : null;
13055    }
13056
13057    /**
13058     * @param info the {@link android.view.View.AttachInfo} to associated with
13059     *        this view
13060     */
13061    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13062        //System.out.println("Attached! " + this);
13063        mAttachInfo = info;
13064        if (mOverlay != null) {
13065            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13066        }
13067        mWindowAttachCount++;
13068        // We will need to evaluate the drawable state at least once.
13069        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13070        if (mFloatingTreeObserver != null) {
13071            info.mTreeObserver.merge(mFloatingTreeObserver);
13072            mFloatingTreeObserver = null;
13073        }
13074        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13075            mAttachInfo.mScrollContainers.add(this);
13076            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13077        }
13078        performCollectViewAttributes(mAttachInfo, visibility);
13079        onAttachedToWindow();
13080
13081        ListenerInfo li = mListenerInfo;
13082        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13083                li != null ? li.mOnAttachStateChangeListeners : null;
13084        if (listeners != null && listeners.size() > 0) {
13085            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13086            // perform the dispatching. The iterator is a safe guard against listeners that
13087            // could mutate the list by calling the various add/remove methods. This prevents
13088            // the array from being modified while we iterate it.
13089            for (OnAttachStateChangeListener listener : listeners) {
13090                listener.onViewAttachedToWindow(this);
13091            }
13092        }
13093
13094        int vis = info.mWindowVisibility;
13095        if (vis != GONE) {
13096            onWindowVisibilityChanged(vis);
13097        }
13098        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13099            // If nobody has evaluated the drawable state yet, then do it now.
13100            refreshDrawableState();
13101        }
13102        needGlobalAttributesUpdate(false);
13103    }
13104
13105    void dispatchDetachedFromWindow() {
13106        AttachInfo info = mAttachInfo;
13107        if (info != null) {
13108            int vis = info.mWindowVisibility;
13109            if (vis != GONE) {
13110                onWindowVisibilityChanged(GONE);
13111            }
13112        }
13113
13114        onDetachedFromWindow();
13115        onDetachedFromWindowInternal();
13116
13117        ListenerInfo li = mListenerInfo;
13118        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13119                li != null ? li.mOnAttachStateChangeListeners : null;
13120        if (listeners != null && listeners.size() > 0) {
13121            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13122            // perform the dispatching. The iterator is a safe guard against listeners that
13123            // could mutate the list by calling the various add/remove methods. This prevents
13124            // the array from being modified while we iterate it.
13125            for (OnAttachStateChangeListener listener : listeners) {
13126                listener.onViewDetachedFromWindow(this);
13127            }
13128        }
13129
13130        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13131            mAttachInfo.mScrollContainers.remove(this);
13132            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13133        }
13134
13135        mAttachInfo = null;
13136        if (mOverlay != null) {
13137            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13138        }
13139    }
13140
13141    /**
13142     * Cancel any deferred high-level input events that were previously posted to the event queue.
13143     *
13144     * <p>Many views post high-level events such as click handlers to the event queue
13145     * to run deferred in order to preserve a desired user experience - clearing visible
13146     * pressed states before executing, etc. This method will abort any events of this nature
13147     * that are currently in flight.</p>
13148     *
13149     * <p>Custom views that generate their own high-level deferred input events should override
13150     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13151     *
13152     * <p>This will also cancel pending input events for any child views.</p>
13153     *
13154     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13155     * This will not impact newer events posted after this call that may occur as a result of
13156     * lower-level input events still waiting in the queue. If you are trying to prevent
13157     * double-submitted  events for the duration of some sort of asynchronous transaction
13158     * you should also take other steps to protect against unexpected double inputs e.g. calling
13159     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13160     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13161     */
13162    public final void cancelPendingInputEvents() {
13163        dispatchCancelPendingInputEvents();
13164    }
13165
13166    /**
13167     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13168     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13169     */
13170    void dispatchCancelPendingInputEvents() {
13171        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13172        onCancelPendingInputEvents();
13173        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13174            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13175                    " did not call through to super.onCancelPendingInputEvents()");
13176        }
13177    }
13178
13179    /**
13180     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13181     * a parent view.
13182     *
13183     * <p>This method is responsible for removing any pending high-level input events that were
13184     * posted to the event queue to run later. Custom view classes that post their own deferred
13185     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13186     * {@link android.os.Handler} should override this method, call
13187     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13188     * </p>
13189     */
13190    public void onCancelPendingInputEvents() {
13191        removePerformClickCallback();
13192        cancelLongPress();
13193        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13194    }
13195
13196    /**
13197     * Store this view hierarchy's frozen state into the given container.
13198     *
13199     * @param container The SparseArray in which to save the view's state.
13200     *
13201     * @see #restoreHierarchyState(android.util.SparseArray)
13202     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13203     * @see #onSaveInstanceState()
13204     */
13205    public void saveHierarchyState(SparseArray<Parcelable> container) {
13206        dispatchSaveInstanceState(container);
13207    }
13208
13209    /**
13210     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13211     * this view and its children. May be overridden to modify how freezing happens to a
13212     * view's children; for example, some views may want to not store state for their children.
13213     *
13214     * @param container The SparseArray in which to save the view's state.
13215     *
13216     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13217     * @see #saveHierarchyState(android.util.SparseArray)
13218     * @see #onSaveInstanceState()
13219     */
13220    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13221        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13222            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13223            Parcelable state = onSaveInstanceState();
13224            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13225                throw new IllegalStateException(
13226                        "Derived class did not call super.onSaveInstanceState()");
13227            }
13228            if (state != null) {
13229                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13230                // + ": " + state);
13231                container.put(mID, state);
13232            }
13233        }
13234    }
13235
13236    /**
13237     * Hook allowing a view to generate a representation of its internal state
13238     * that can later be used to create a new instance with that same state.
13239     * This state should only contain information that is not persistent or can
13240     * not be reconstructed later. For example, you will never store your
13241     * current position on screen because that will be computed again when a
13242     * new instance of the view is placed in its view hierarchy.
13243     * <p>
13244     * Some examples of things you may store here: the current cursor position
13245     * in a text view (but usually not the text itself since that is stored in a
13246     * content provider or other persistent storage), the currently selected
13247     * item in a list view.
13248     *
13249     * @return Returns a Parcelable object containing the view's current dynamic
13250     *         state, or null if there is nothing interesting to save. The
13251     *         default implementation returns null.
13252     * @see #onRestoreInstanceState(android.os.Parcelable)
13253     * @see #saveHierarchyState(android.util.SparseArray)
13254     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13255     * @see #setSaveEnabled(boolean)
13256     */
13257    protected Parcelable onSaveInstanceState() {
13258        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13259        return BaseSavedState.EMPTY_STATE;
13260    }
13261
13262    /**
13263     * Restore this view hierarchy's frozen state from the given container.
13264     *
13265     * @param container The SparseArray which holds previously frozen states.
13266     *
13267     * @see #saveHierarchyState(android.util.SparseArray)
13268     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13269     * @see #onRestoreInstanceState(android.os.Parcelable)
13270     */
13271    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13272        dispatchRestoreInstanceState(container);
13273    }
13274
13275    /**
13276     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13277     * state for this view and its children. May be overridden to modify how restoring
13278     * happens to a view's children; for example, some views may want to not store state
13279     * for their children.
13280     *
13281     * @param container The SparseArray which holds previously saved state.
13282     *
13283     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13284     * @see #restoreHierarchyState(android.util.SparseArray)
13285     * @see #onRestoreInstanceState(android.os.Parcelable)
13286     */
13287    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13288        if (mID != NO_ID) {
13289            Parcelable state = container.get(mID);
13290            if (state != null) {
13291                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13292                // + ": " + state);
13293                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13294                onRestoreInstanceState(state);
13295                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13296                    throw new IllegalStateException(
13297                            "Derived class did not call super.onRestoreInstanceState()");
13298                }
13299            }
13300        }
13301    }
13302
13303    /**
13304     * Hook allowing a view to re-apply a representation of its internal state that had previously
13305     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13306     * null state.
13307     *
13308     * @param state The frozen state that had previously been returned by
13309     *        {@link #onSaveInstanceState}.
13310     *
13311     * @see #onSaveInstanceState()
13312     * @see #restoreHierarchyState(android.util.SparseArray)
13313     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13314     */
13315    protected void onRestoreInstanceState(Parcelable state) {
13316        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13317        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13318            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13319                    + "received " + state.getClass().toString() + " instead. This usually happens "
13320                    + "when two views of different type have the same id in the same hierarchy. "
13321                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13322                    + "other views do not use the same id.");
13323        }
13324    }
13325
13326    /**
13327     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13328     *
13329     * @return the drawing start time in milliseconds
13330     */
13331    public long getDrawingTime() {
13332        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13333    }
13334
13335    /**
13336     * <p>Enables or disables the duplication of the parent's state into this view. When
13337     * duplication is enabled, this view gets its drawable state from its parent rather
13338     * than from its own internal properties.</p>
13339     *
13340     * <p>Note: in the current implementation, setting this property to true after the
13341     * view was added to a ViewGroup might have no effect at all. This property should
13342     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13343     *
13344     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13345     * property is enabled, an exception will be thrown.</p>
13346     *
13347     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13348     * parent, these states should not be affected by this method.</p>
13349     *
13350     * @param enabled True to enable duplication of the parent's drawable state, false
13351     *                to disable it.
13352     *
13353     * @see #getDrawableState()
13354     * @see #isDuplicateParentStateEnabled()
13355     */
13356    public void setDuplicateParentStateEnabled(boolean enabled) {
13357        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13358    }
13359
13360    /**
13361     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13362     *
13363     * @return True if this view's drawable state is duplicated from the parent,
13364     *         false otherwise
13365     *
13366     * @see #getDrawableState()
13367     * @see #setDuplicateParentStateEnabled(boolean)
13368     */
13369    public boolean isDuplicateParentStateEnabled() {
13370        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13371    }
13372
13373    /**
13374     * <p>Specifies the type of layer backing this view. The layer can be
13375     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13376     * {@link #LAYER_TYPE_HARDWARE}.</p>
13377     *
13378     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13379     * instance that controls how the layer is composed on screen. The following
13380     * properties of the paint are taken into account when composing the layer:</p>
13381     * <ul>
13382     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13383     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13384     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13385     * </ul>
13386     *
13387     * <p>If this view has an alpha value set to < 1.0 by calling
13388     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13389     * by this view's alpha value.</p>
13390     *
13391     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13392     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13393     * for more information on when and how to use layers.</p>
13394     *
13395     * @param layerType The type of layer to use with this view, must be one of
13396     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13397     *        {@link #LAYER_TYPE_HARDWARE}
13398     * @param paint The paint used to compose the layer. This argument is optional
13399     *        and can be null. It is ignored when the layer type is
13400     *        {@link #LAYER_TYPE_NONE}
13401     *
13402     * @see #getLayerType()
13403     * @see #LAYER_TYPE_NONE
13404     * @see #LAYER_TYPE_SOFTWARE
13405     * @see #LAYER_TYPE_HARDWARE
13406     * @see #setAlpha(float)
13407     *
13408     * @attr ref android.R.styleable#View_layerType
13409     */
13410    public void setLayerType(int layerType, Paint paint) {
13411        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13412            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13413                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13414        }
13415
13416        boolean typeChanged = mRenderNode.setLayerType(layerType);
13417
13418        if (!typeChanged) {
13419            setLayerPaint(paint);
13420            return;
13421        }
13422
13423        // Destroy any previous software drawing cache if needed
13424        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13425            destroyDrawingCache();
13426            invalidateParentCaches();
13427            invalidate(true);
13428        }
13429
13430        mLayerType = layerType;
13431        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13432        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13433        mRenderNode.setLayerPaint(mLayerPaint);
13434
13435        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13436            // LAYER_TYPE_SOFTWARE is handled by View:draw(), so need to invalidate()
13437            invalidateParentCaches();
13438            invalidate(true);
13439        } else {
13440            invalidateViewProperty(false, false);
13441        }
13442    }
13443
13444    /**
13445     * Updates the {@link Paint} object used with the current layer (used only if the current
13446     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13447     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13448     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13449     * ensure that the view gets redrawn immediately.
13450     *
13451     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13452     * instance that controls how the layer is composed on screen. The following
13453     * properties of the paint are taken into account when composing the layer:</p>
13454     * <ul>
13455     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13456     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13457     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13458     * </ul>
13459     *
13460     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13461     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13462     *
13463     * @param paint The paint used to compose the layer. This argument is optional
13464     *        and can be null. It is ignored when the layer type is
13465     *        {@link #LAYER_TYPE_NONE}
13466     *
13467     * @see #setLayerType(int, android.graphics.Paint)
13468     */
13469    public void setLayerPaint(Paint paint) {
13470        int layerType = getLayerType();
13471        if (layerType != LAYER_TYPE_NONE) {
13472            mLayerPaint = paint == null ? new Paint() : paint;
13473            if (layerType == LAYER_TYPE_HARDWARE) {
13474                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13475                    invalidateViewProperty(false, false);
13476                }
13477            } else {
13478                invalidate();
13479            }
13480        }
13481    }
13482
13483    /**
13484     * Indicates whether this view has a static layer. A view with layer type
13485     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13486     * dynamic.
13487     */
13488    boolean hasStaticLayer() {
13489        return true;
13490    }
13491
13492    /**
13493     * Indicates what type of layer is currently associated with this view. By default
13494     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13495     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13496     * for more information on the different types of layers.
13497     *
13498     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13499     *         {@link #LAYER_TYPE_HARDWARE}
13500     *
13501     * @see #setLayerType(int, android.graphics.Paint)
13502     * @see #buildLayer()
13503     * @see #LAYER_TYPE_NONE
13504     * @see #LAYER_TYPE_SOFTWARE
13505     * @see #LAYER_TYPE_HARDWARE
13506     */
13507    public int getLayerType() {
13508        return mLayerType;
13509    }
13510
13511    /**
13512     * Forces this view's layer to be created and this view to be rendered
13513     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13514     * invoking this method will have no effect.
13515     *
13516     * This method can for instance be used to render a view into its layer before
13517     * starting an animation. If this view is complex, rendering into the layer
13518     * before starting the animation will avoid skipping frames.
13519     *
13520     * @throws IllegalStateException If this view is not attached to a window
13521     *
13522     * @see #setLayerType(int, android.graphics.Paint)
13523     */
13524    public void buildLayer() {
13525        if (mLayerType == LAYER_TYPE_NONE) return;
13526
13527        final AttachInfo attachInfo = mAttachInfo;
13528        if (attachInfo == null) {
13529            throw new IllegalStateException("This view must be attached to a window first");
13530        }
13531
13532        if (getWidth() == 0 || getHeight() == 0) {
13533            return;
13534        }
13535
13536        switch (mLayerType) {
13537            case LAYER_TYPE_HARDWARE:
13538                // The only part of a hardware layer we can build in response to
13539                // this call is to ensure the display list is up to date.
13540                // The actual rendering of the display list into the layer must
13541                // be done at playback time
13542                updateDisplayListIfDirty();
13543                break;
13544            case LAYER_TYPE_SOFTWARE:
13545                buildDrawingCache(true);
13546                break;
13547        }
13548    }
13549
13550    /**
13551     * If this View draws with a HardwareLayer, returns it.
13552     * Otherwise returns null
13553     *
13554     * TODO: Only TextureView uses this, can we eliminate it?
13555     */
13556    HardwareLayer getHardwareLayer() {
13557        return null;
13558    }
13559
13560    /**
13561     * Destroys all hardware rendering resources. This method is invoked
13562     * when the system needs to reclaim resources. Upon execution of this
13563     * method, you should free any OpenGL resources created by the view.
13564     *
13565     * Note: you <strong>must</strong> call
13566     * <code>super.destroyHardwareResources()</code> when overriding
13567     * this method.
13568     *
13569     * @hide
13570     */
13571    protected void destroyHardwareResources() {
13572        resetDisplayList();
13573    }
13574
13575    /**
13576     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13577     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13578     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13579     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13580     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13581     * null.</p>
13582     *
13583     * <p>Enabling the drawing cache is similar to
13584     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13585     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13586     * drawing cache has no effect on rendering because the system uses a different mechanism
13587     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13588     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13589     * for information on how to enable software and hardware layers.</p>
13590     *
13591     * <p>This API can be used to manually generate
13592     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13593     * {@link #getDrawingCache()}.</p>
13594     *
13595     * @param enabled true to enable the drawing cache, false otherwise
13596     *
13597     * @see #isDrawingCacheEnabled()
13598     * @see #getDrawingCache()
13599     * @see #buildDrawingCache()
13600     * @see #setLayerType(int, android.graphics.Paint)
13601     */
13602    public void setDrawingCacheEnabled(boolean enabled) {
13603        mCachingFailed = false;
13604        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13605    }
13606
13607    /**
13608     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13609     *
13610     * @return true if the drawing cache is enabled
13611     *
13612     * @see #setDrawingCacheEnabled(boolean)
13613     * @see #getDrawingCache()
13614     */
13615    @ViewDebug.ExportedProperty(category = "drawing")
13616    public boolean isDrawingCacheEnabled() {
13617        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13618    }
13619
13620    /**
13621     * Debugging utility which recursively outputs the dirty state of a view and its
13622     * descendants.
13623     *
13624     * @hide
13625     */
13626    @SuppressWarnings({"UnusedDeclaration"})
13627    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13628        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13629                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13630                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13631                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13632        if (clear) {
13633            mPrivateFlags &= clearMask;
13634        }
13635        if (this instanceof ViewGroup) {
13636            ViewGroup parent = (ViewGroup) this;
13637            final int count = parent.getChildCount();
13638            for (int i = 0; i < count; i++) {
13639                final View child = parent.getChildAt(i);
13640                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13641            }
13642        }
13643    }
13644
13645    /**
13646     * This method is used by ViewGroup to cause its children to restore or recreate their
13647     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13648     * to recreate its own display list, which would happen if it went through the normal
13649     * draw/dispatchDraw mechanisms.
13650     *
13651     * @hide
13652     */
13653    protected void dispatchGetDisplayList() {}
13654
13655    /**
13656     * A view that is not attached or hardware accelerated cannot create a display list.
13657     * This method checks these conditions and returns the appropriate result.
13658     *
13659     * @return true if view has the ability to create a display list, false otherwise.
13660     *
13661     * @hide
13662     */
13663    public boolean canHaveDisplayList() {
13664        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13665    }
13666
13667    private void updateDisplayListIfDirty() {
13668        final RenderNode renderNode = mRenderNode;
13669        if (!canHaveDisplayList()) {
13670            // can't populate RenderNode, don't try
13671            return;
13672        }
13673
13674        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13675                || !renderNode.isValid()
13676                || (mRecreateDisplayList)) {
13677            // Don't need to recreate the display list, just need to tell our
13678            // children to restore/recreate theirs
13679            if (renderNode.isValid()
13680                    && !mRecreateDisplayList) {
13681                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13682                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13683                dispatchGetDisplayList();
13684
13685                return; // no work needed
13686            }
13687
13688            // If we got here, we're recreating it. Mark it as such to ensure that
13689            // we copy in child display lists into ours in drawChild()
13690            mRecreateDisplayList = true;
13691
13692            int width = mRight - mLeft;
13693            int height = mBottom - mTop;
13694            int layerType = getLayerType();
13695
13696            final HardwareCanvas canvas = renderNode.start(width, height);
13697
13698            try {
13699                final HardwareLayer layer = getHardwareLayer();
13700                if (layer != null && layer.isValid()) {
13701                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13702                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13703                    buildDrawingCache(true);
13704                    Bitmap cache = getDrawingCache(true);
13705                    if (cache != null) {
13706                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13707                    }
13708                } else {
13709                    computeScroll();
13710
13711                    canvas.translate(-mScrollX, -mScrollY);
13712                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13713                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13714
13715                    // Fast path for layouts with no backgrounds
13716                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13717                        dispatchDraw(canvas);
13718                        if (mOverlay != null && !mOverlay.isEmpty()) {
13719                            mOverlay.getOverlayView().draw(canvas);
13720                        }
13721                    } else {
13722                        draw(canvas);
13723                    }
13724                }
13725            } finally {
13726                renderNode.end(canvas);
13727                setDisplayListProperties(renderNode);
13728            }
13729        } else {
13730            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13731            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13732        }
13733    }
13734
13735    /**
13736     * Returns a RenderNode with View draw content recorded, which can be
13737     * used to draw this view again without executing its draw method.
13738     *
13739     * @return A RenderNode ready to replay, or null if caching is not enabled.
13740     *
13741     * @hide
13742     */
13743    public RenderNode getDisplayList() {
13744        updateDisplayListIfDirty();
13745        return mRenderNode;
13746    }
13747
13748    private void resetDisplayList() {
13749        if (mRenderNode.isValid()) {
13750            mRenderNode.destroyDisplayListData();
13751        }
13752
13753        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
13754            mBackgroundDisplayList.destroyDisplayListData();
13755        }
13756    }
13757
13758    /**
13759     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13760     *
13761     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13762     *
13763     * @see #getDrawingCache(boolean)
13764     */
13765    public Bitmap getDrawingCache() {
13766        return getDrawingCache(false);
13767    }
13768
13769    /**
13770     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13771     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13772     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13773     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13774     * request the drawing cache by calling this method and draw it on screen if the
13775     * returned bitmap is not null.</p>
13776     *
13777     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13778     * this method will create a bitmap of the same size as this view. Because this bitmap
13779     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13780     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13781     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13782     * size than the view. This implies that your application must be able to handle this
13783     * size.</p>
13784     *
13785     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13786     *        the current density of the screen when the application is in compatibility
13787     *        mode.
13788     *
13789     * @return A bitmap representing this view or null if cache is disabled.
13790     *
13791     * @see #setDrawingCacheEnabled(boolean)
13792     * @see #isDrawingCacheEnabled()
13793     * @see #buildDrawingCache(boolean)
13794     * @see #destroyDrawingCache()
13795     */
13796    public Bitmap getDrawingCache(boolean autoScale) {
13797        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13798            return null;
13799        }
13800        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13801            buildDrawingCache(autoScale);
13802        }
13803        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13804    }
13805
13806    /**
13807     * <p>Frees the resources used by the drawing cache. If you call
13808     * {@link #buildDrawingCache()} manually without calling
13809     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13810     * should cleanup the cache with this method afterwards.</p>
13811     *
13812     * @see #setDrawingCacheEnabled(boolean)
13813     * @see #buildDrawingCache()
13814     * @see #getDrawingCache()
13815     */
13816    public void destroyDrawingCache() {
13817        if (mDrawingCache != null) {
13818            mDrawingCache.recycle();
13819            mDrawingCache = null;
13820        }
13821        if (mUnscaledDrawingCache != null) {
13822            mUnscaledDrawingCache.recycle();
13823            mUnscaledDrawingCache = null;
13824        }
13825    }
13826
13827    /**
13828     * Setting a solid background color for the drawing cache's bitmaps will improve
13829     * performance and memory usage. Note, though that this should only be used if this
13830     * view will always be drawn on top of a solid color.
13831     *
13832     * @param color The background color to use for the drawing cache's bitmap
13833     *
13834     * @see #setDrawingCacheEnabled(boolean)
13835     * @see #buildDrawingCache()
13836     * @see #getDrawingCache()
13837     */
13838    public void setDrawingCacheBackgroundColor(int color) {
13839        if (color != mDrawingCacheBackgroundColor) {
13840            mDrawingCacheBackgroundColor = color;
13841            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13842        }
13843    }
13844
13845    /**
13846     * @see #setDrawingCacheBackgroundColor(int)
13847     *
13848     * @return The background color to used for the drawing cache's bitmap
13849     */
13850    public int getDrawingCacheBackgroundColor() {
13851        return mDrawingCacheBackgroundColor;
13852    }
13853
13854    /**
13855     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13856     *
13857     * @see #buildDrawingCache(boolean)
13858     */
13859    public void buildDrawingCache() {
13860        buildDrawingCache(false);
13861    }
13862
13863    /**
13864     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13865     *
13866     * <p>If you call {@link #buildDrawingCache()} manually without calling
13867     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13868     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13869     *
13870     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13871     * this method will create a bitmap of the same size as this view. Because this bitmap
13872     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13873     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13874     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13875     * size than the view. This implies that your application must be able to handle this
13876     * size.</p>
13877     *
13878     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13879     * you do not need the drawing cache bitmap, calling this method will increase memory
13880     * usage and cause the view to be rendered in software once, thus negatively impacting
13881     * performance.</p>
13882     *
13883     * @see #getDrawingCache()
13884     * @see #destroyDrawingCache()
13885     */
13886    public void buildDrawingCache(boolean autoScale) {
13887        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13888                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13889            mCachingFailed = false;
13890
13891            int width = mRight - mLeft;
13892            int height = mBottom - mTop;
13893
13894            final AttachInfo attachInfo = mAttachInfo;
13895            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13896
13897            if (autoScale && scalingRequired) {
13898                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13899                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13900            }
13901
13902            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13903            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13904            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13905
13906            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13907            final long drawingCacheSize =
13908                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13909            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13910                if (width > 0 && height > 0) {
13911                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13912                            + projectedBitmapSize + " bytes, only "
13913                            + drawingCacheSize + " available");
13914                }
13915                destroyDrawingCache();
13916                mCachingFailed = true;
13917                return;
13918            }
13919
13920            boolean clear = true;
13921            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13922
13923            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13924                Bitmap.Config quality;
13925                if (!opaque) {
13926                    // Never pick ARGB_4444 because it looks awful
13927                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13928                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13929                        case DRAWING_CACHE_QUALITY_AUTO:
13930                        case DRAWING_CACHE_QUALITY_LOW:
13931                        case DRAWING_CACHE_QUALITY_HIGH:
13932                        default:
13933                            quality = Bitmap.Config.ARGB_8888;
13934                            break;
13935                    }
13936                } else {
13937                    // Optimization for translucent windows
13938                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13939                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13940                }
13941
13942                // Try to cleanup memory
13943                if (bitmap != null) bitmap.recycle();
13944
13945                try {
13946                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13947                            width, height, quality);
13948                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13949                    if (autoScale) {
13950                        mDrawingCache = bitmap;
13951                    } else {
13952                        mUnscaledDrawingCache = bitmap;
13953                    }
13954                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13955                } catch (OutOfMemoryError e) {
13956                    // If there is not enough memory to create the bitmap cache, just
13957                    // ignore the issue as bitmap caches are not required to draw the
13958                    // view hierarchy
13959                    if (autoScale) {
13960                        mDrawingCache = null;
13961                    } else {
13962                        mUnscaledDrawingCache = null;
13963                    }
13964                    mCachingFailed = true;
13965                    return;
13966                }
13967
13968                clear = drawingCacheBackgroundColor != 0;
13969            }
13970
13971            Canvas canvas;
13972            if (attachInfo != null) {
13973                canvas = attachInfo.mCanvas;
13974                if (canvas == null) {
13975                    canvas = new Canvas();
13976                }
13977                canvas.setBitmap(bitmap);
13978                // Temporarily clobber the cached Canvas in case one of our children
13979                // is also using a drawing cache. Without this, the children would
13980                // steal the canvas by attaching their own bitmap to it and bad, bad
13981                // thing would happen (invisible views, corrupted drawings, etc.)
13982                attachInfo.mCanvas = null;
13983            } else {
13984                // This case should hopefully never or seldom happen
13985                canvas = new Canvas(bitmap);
13986            }
13987
13988            if (clear) {
13989                bitmap.eraseColor(drawingCacheBackgroundColor);
13990            }
13991
13992            computeScroll();
13993            final int restoreCount = canvas.save();
13994
13995            if (autoScale && scalingRequired) {
13996                final float scale = attachInfo.mApplicationScale;
13997                canvas.scale(scale, scale);
13998            }
13999
14000            canvas.translate(-mScrollX, -mScrollY);
14001
14002            mPrivateFlags |= PFLAG_DRAWN;
14003            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14004                    mLayerType != LAYER_TYPE_NONE) {
14005                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14006            }
14007
14008            // Fast path for layouts with no backgrounds
14009            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14010                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14011                dispatchDraw(canvas);
14012                if (mOverlay != null && !mOverlay.isEmpty()) {
14013                    mOverlay.getOverlayView().draw(canvas);
14014                }
14015            } else {
14016                draw(canvas);
14017            }
14018
14019            canvas.restoreToCount(restoreCount);
14020            canvas.setBitmap(null);
14021
14022            if (attachInfo != null) {
14023                // Restore the cached Canvas for our siblings
14024                attachInfo.mCanvas = canvas;
14025            }
14026        }
14027    }
14028
14029    /**
14030     * Create a snapshot of the view into a bitmap.  We should probably make
14031     * some form of this public, but should think about the API.
14032     */
14033    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14034        int width = mRight - mLeft;
14035        int height = mBottom - mTop;
14036
14037        final AttachInfo attachInfo = mAttachInfo;
14038        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14039        width = (int) ((width * scale) + 0.5f);
14040        height = (int) ((height * scale) + 0.5f);
14041
14042        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14043                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14044        if (bitmap == null) {
14045            throw new OutOfMemoryError();
14046        }
14047
14048        Resources resources = getResources();
14049        if (resources != null) {
14050            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14051        }
14052
14053        Canvas canvas;
14054        if (attachInfo != null) {
14055            canvas = attachInfo.mCanvas;
14056            if (canvas == null) {
14057                canvas = new Canvas();
14058            }
14059            canvas.setBitmap(bitmap);
14060            // Temporarily clobber the cached Canvas in case one of our children
14061            // is also using a drawing cache. Without this, the children would
14062            // steal the canvas by attaching their own bitmap to it and bad, bad
14063            // things would happen (invisible views, corrupted drawings, etc.)
14064            attachInfo.mCanvas = null;
14065        } else {
14066            // This case should hopefully never or seldom happen
14067            canvas = new Canvas(bitmap);
14068        }
14069
14070        if ((backgroundColor & 0xff000000) != 0) {
14071            bitmap.eraseColor(backgroundColor);
14072        }
14073
14074        computeScroll();
14075        final int restoreCount = canvas.save();
14076        canvas.scale(scale, scale);
14077        canvas.translate(-mScrollX, -mScrollY);
14078
14079        // Temporarily remove the dirty mask
14080        int flags = mPrivateFlags;
14081        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14082
14083        // Fast path for layouts with no backgrounds
14084        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14085            dispatchDraw(canvas);
14086            if (mOverlay != null && !mOverlay.isEmpty()) {
14087                mOverlay.getOverlayView().draw(canvas);
14088            }
14089        } else {
14090            draw(canvas);
14091        }
14092
14093        mPrivateFlags = flags;
14094
14095        canvas.restoreToCount(restoreCount);
14096        canvas.setBitmap(null);
14097
14098        if (attachInfo != null) {
14099            // Restore the cached Canvas for our siblings
14100            attachInfo.mCanvas = canvas;
14101        }
14102
14103        return bitmap;
14104    }
14105
14106    /**
14107     * Indicates whether this View is currently in edit mode. A View is usually
14108     * in edit mode when displayed within a developer tool. For instance, if
14109     * this View is being drawn by a visual user interface builder, this method
14110     * should return true.
14111     *
14112     * Subclasses should check the return value of this method to provide
14113     * different behaviors if their normal behavior might interfere with the
14114     * host environment. For instance: the class spawns a thread in its
14115     * constructor, the drawing code relies on device-specific features, etc.
14116     *
14117     * This method is usually checked in the drawing code of custom widgets.
14118     *
14119     * @return True if this View is in edit mode, false otherwise.
14120     */
14121    public boolean isInEditMode() {
14122        return false;
14123    }
14124
14125    /**
14126     * If the View draws content inside its padding and enables fading edges,
14127     * it needs to support padding offsets. Padding offsets are added to the
14128     * fading edges to extend the length of the fade so that it covers pixels
14129     * drawn inside the padding.
14130     *
14131     * Subclasses of this class should override this method if they need
14132     * to draw content inside the padding.
14133     *
14134     * @return True if padding offset must be applied, false otherwise.
14135     *
14136     * @see #getLeftPaddingOffset()
14137     * @see #getRightPaddingOffset()
14138     * @see #getTopPaddingOffset()
14139     * @see #getBottomPaddingOffset()
14140     *
14141     * @since CURRENT
14142     */
14143    protected boolean isPaddingOffsetRequired() {
14144        return false;
14145    }
14146
14147    /**
14148     * Amount by which to extend the left fading region. Called only when
14149     * {@link #isPaddingOffsetRequired()} returns true.
14150     *
14151     * @return The left padding offset in pixels.
14152     *
14153     * @see #isPaddingOffsetRequired()
14154     *
14155     * @since CURRENT
14156     */
14157    protected int getLeftPaddingOffset() {
14158        return 0;
14159    }
14160
14161    /**
14162     * Amount by which to extend the right fading region. Called only when
14163     * {@link #isPaddingOffsetRequired()} returns true.
14164     *
14165     * @return The right padding offset in pixels.
14166     *
14167     * @see #isPaddingOffsetRequired()
14168     *
14169     * @since CURRENT
14170     */
14171    protected int getRightPaddingOffset() {
14172        return 0;
14173    }
14174
14175    /**
14176     * Amount by which to extend the top fading region. Called only when
14177     * {@link #isPaddingOffsetRequired()} returns true.
14178     *
14179     * @return The top padding offset in pixels.
14180     *
14181     * @see #isPaddingOffsetRequired()
14182     *
14183     * @since CURRENT
14184     */
14185    protected int getTopPaddingOffset() {
14186        return 0;
14187    }
14188
14189    /**
14190     * Amount by which to extend the bottom fading region. Called only when
14191     * {@link #isPaddingOffsetRequired()} returns true.
14192     *
14193     * @return The bottom padding offset in pixels.
14194     *
14195     * @see #isPaddingOffsetRequired()
14196     *
14197     * @since CURRENT
14198     */
14199    protected int getBottomPaddingOffset() {
14200        return 0;
14201    }
14202
14203    /**
14204     * @hide
14205     * @param offsetRequired
14206     */
14207    protected int getFadeTop(boolean offsetRequired) {
14208        int top = mPaddingTop;
14209        if (offsetRequired) top += getTopPaddingOffset();
14210        return top;
14211    }
14212
14213    /**
14214     * @hide
14215     * @param offsetRequired
14216     */
14217    protected int getFadeHeight(boolean offsetRequired) {
14218        int padding = mPaddingTop;
14219        if (offsetRequired) padding += getTopPaddingOffset();
14220        return mBottom - mTop - mPaddingBottom - padding;
14221    }
14222
14223    /**
14224     * <p>Indicates whether this view is attached to a hardware accelerated
14225     * window or not.</p>
14226     *
14227     * <p>Even if this method returns true, it does not mean that every call
14228     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14229     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14230     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14231     * window is hardware accelerated,
14232     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14233     * return false, and this method will return true.</p>
14234     *
14235     * @return True if the view is attached to a window and the window is
14236     *         hardware accelerated; false in any other case.
14237     */
14238    public boolean isHardwareAccelerated() {
14239        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14240    }
14241
14242    /**
14243     * Sets a rectangular area on this view to which the view will be clipped
14244     * when it is drawn. Setting the value to null will remove the clip bounds
14245     * and the view will draw normally, using its full bounds.
14246     *
14247     * @param clipBounds The rectangular area, in the local coordinates of
14248     * this view, to which future drawing operations will be clipped.
14249     */
14250    public void setClipBounds(Rect clipBounds) {
14251        if (clipBounds != null) {
14252            if (clipBounds.equals(mClipBounds)) {
14253                return;
14254            }
14255            if (mClipBounds == null) {
14256                invalidate();
14257                mClipBounds = new Rect(clipBounds);
14258            } else {
14259                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14260                        Math.min(mClipBounds.top, clipBounds.top),
14261                        Math.max(mClipBounds.right, clipBounds.right),
14262                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14263                mClipBounds.set(clipBounds);
14264            }
14265        } else {
14266            if (mClipBounds != null) {
14267                invalidate();
14268                mClipBounds = null;
14269            }
14270        }
14271    }
14272
14273    /**
14274     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14275     *
14276     * @return A copy of the current clip bounds if clip bounds are set,
14277     * otherwise null.
14278     */
14279    public Rect getClipBounds() {
14280        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14281    }
14282
14283    /**
14284     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14285     * case of an active Animation being run on the view.
14286     */
14287    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14288            Animation a, boolean scalingRequired) {
14289        Transformation invalidationTransform;
14290        final int flags = parent.mGroupFlags;
14291        final boolean initialized = a.isInitialized();
14292        if (!initialized) {
14293            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14294            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14295            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14296            onAnimationStart();
14297        }
14298
14299        final Transformation t = parent.getChildTransformation();
14300        boolean more = a.getTransformation(drawingTime, t, 1f);
14301        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14302            if (parent.mInvalidationTransformation == null) {
14303                parent.mInvalidationTransformation = new Transformation();
14304            }
14305            invalidationTransform = parent.mInvalidationTransformation;
14306            a.getTransformation(drawingTime, invalidationTransform, 1f);
14307        } else {
14308            invalidationTransform = t;
14309        }
14310
14311        if (more) {
14312            if (!a.willChangeBounds()) {
14313                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14314                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14315                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14316                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14317                    // The child need to draw an animation, potentially offscreen, so
14318                    // make sure we do not cancel invalidate requests
14319                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14320                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14321                }
14322            } else {
14323                if (parent.mInvalidateRegion == null) {
14324                    parent.mInvalidateRegion = new RectF();
14325                }
14326                final RectF region = parent.mInvalidateRegion;
14327                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14328                        invalidationTransform);
14329
14330                // The child need to draw an animation, potentially offscreen, so
14331                // make sure we do not cancel invalidate requests
14332                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14333
14334                final int left = mLeft + (int) region.left;
14335                final int top = mTop + (int) region.top;
14336                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14337                        top + (int) (region.height() + .5f));
14338            }
14339        }
14340        return more;
14341    }
14342
14343    /**
14344     * This method is called by getDisplayList() when a display list is recorded for a View.
14345     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14346     */
14347    void setDisplayListProperties(RenderNode renderNode) {
14348        if (renderNode != null) {
14349            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14350            if (mParent instanceof ViewGroup) {
14351                renderNode.setClipToBounds(
14352                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14353            }
14354            float alpha = 1;
14355            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14356                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14357                ViewGroup parentVG = (ViewGroup) mParent;
14358                final Transformation t = parentVG.getChildTransformation();
14359                if (parentVG.getChildStaticTransformation(this, t)) {
14360                    final int transformType = t.getTransformationType();
14361                    if (transformType != Transformation.TYPE_IDENTITY) {
14362                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14363                            alpha = t.getAlpha();
14364                        }
14365                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14366                            renderNode.setStaticMatrix(t.getMatrix());
14367                        }
14368                    }
14369                }
14370            }
14371            if (mTransformationInfo != null) {
14372                alpha *= getFinalAlpha();
14373                if (alpha < 1) {
14374                    final int multipliedAlpha = (int) (255 * alpha);
14375                    if (onSetAlpha(multipliedAlpha)) {
14376                        alpha = 1;
14377                    }
14378                }
14379                renderNode.setAlpha(alpha);
14380            } else if (alpha < 1) {
14381                renderNode.setAlpha(alpha);
14382            }
14383        }
14384    }
14385
14386    /**
14387     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14388     * This draw() method is an implementation detail and is not intended to be overridden or
14389     * to be called from anywhere else other than ViewGroup.drawChild().
14390     */
14391    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14392        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14393        boolean more = false;
14394        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14395        final int flags = parent.mGroupFlags;
14396
14397        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14398            parent.getChildTransformation().clear();
14399            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14400        }
14401
14402        Transformation transformToApply = null;
14403        boolean concatMatrix = false;
14404
14405        boolean scalingRequired = false;
14406        boolean caching;
14407        int layerType = getLayerType();
14408
14409        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14410        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14411                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14412            caching = true;
14413            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14414            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14415        } else {
14416            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14417        }
14418
14419        final Animation a = getAnimation();
14420        if (a != null) {
14421            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14422            concatMatrix = a.willChangeTransformationMatrix();
14423            if (concatMatrix) {
14424                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14425            }
14426            transformToApply = parent.getChildTransformation();
14427        } else {
14428            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14429                // No longer animating: clear out old animation matrix
14430                mRenderNode.setAnimationMatrix(null);
14431                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14432            }
14433            if (!useDisplayListProperties &&
14434                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14435                final Transformation t = parent.getChildTransformation();
14436                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14437                if (hasTransform) {
14438                    final int transformType = t.getTransformationType();
14439                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14440                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14441                }
14442            }
14443        }
14444
14445        concatMatrix |= !childHasIdentityMatrix;
14446
14447        // Sets the flag as early as possible to allow draw() implementations
14448        // to call invalidate() successfully when doing animations
14449        mPrivateFlags |= PFLAG_DRAWN;
14450
14451        if (!concatMatrix &&
14452                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14453                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14454                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14455                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14456            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14457            return more;
14458        }
14459        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14460
14461        if (hardwareAccelerated) {
14462            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14463            // retain the flag's value temporarily in the mRecreateDisplayList flag
14464            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14465            mPrivateFlags &= ~PFLAG_INVALIDATED;
14466        }
14467
14468        RenderNode displayList = null;
14469        Bitmap cache = null;
14470        boolean hasDisplayList = false;
14471        if (caching) {
14472            if (!hardwareAccelerated) {
14473                if (layerType != LAYER_TYPE_NONE) {
14474                    layerType = LAYER_TYPE_SOFTWARE;
14475                    buildDrawingCache(true);
14476                }
14477                cache = getDrawingCache(true);
14478            } else {
14479                switch (layerType) {
14480                    case LAYER_TYPE_SOFTWARE:
14481                        if (useDisplayListProperties) {
14482                            hasDisplayList = canHaveDisplayList();
14483                        } else {
14484                            buildDrawingCache(true);
14485                            cache = getDrawingCache(true);
14486                        }
14487                        break;
14488                    case LAYER_TYPE_HARDWARE:
14489                        if (useDisplayListProperties) {
14490                            hasDisplayList = canHaveDisplayList();
14491                        }
14492                        break;
14493                    case LAYER_TYPE_NONE:
14494                        // Delay getting the display list until animation-driven alpha values are
14495                        // set up and possibly passed on to the view
14496                        hasDisplayList = canHaveDisplayList();
14497                        break;
14498                }
14499            }
14500        }
14501        useDisplayListProperties &= hasDisplayList;
14502        if (useDisplayListProperties) {
14503            displayList = getDisplayList();
14504            if (!displayList.isValid()) {
14505                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14506                // to getDisplayList(), the display list will be marked invalid and we should not
14507                // try to use it again.
14508                displayList = null;
14509                hasDisplayList = false;
14510                useDisplayListProperties = false;
14511            }
14512        }
14513
14514        int sx = 0;
14515        int sy = 0;
14516        if (!hasDisplayList) {
14517            computeScroll();
14518            sx = mScrollX;
14519            sy = mScrollY;
14520        }
14521
14522        final boolean hasNoCache = cache == null || hasDisplayList;
14523        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14524                layerType != LAYER_TYPE_HARDWARE;
14525
14526        int restoreTo = -1;
14527        if (!useDisplayListProperties || transformToApply != null) {
14528            restoreTo = canvas.save();
14529        }
14530        if (offsetForScroll) {
14531            canvas.translate(mLeft - sx, mTop - sy);
14532        } else {
14533            if (!useDisplayListProperties) {
14534                canvas.translate(mLeft, mTop);
14535            }
14536            if (scalingRequired) {
14537                if (useDisplayListProperties) {
14538                    // TODO: Might not need this if we put everything inside the DL
14539                    restoreTo = canvas.save();
14540                }
14541                // mAttachInfo cannot be null, otherwise scalingRequired == false
14542                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14543                canvas.scale(scale, scale);
14544            }
14545        }
14546
14547        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14548        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14549                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14550            if (transformToApply != null || !childHasIdentityMatrix) {
14551                int transX = 0;
14552                int transY = 0;
14553
14554                if (offsetForScroll) {
14555                    transX = -sx;
14556                    transY = -sy;
14557                }
14558
14559                if (transformToApply != null) {
14560                    if (concatMatrix) {
14561                        if (useDisplayListProperties) {
14562                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14563                        } else {
14564                            // Undo the scroll translation, apply the transformation matrix,
14565                            // then redo the scroll translate to get the correct result.
14566                            canvas.translate(-transX, -transY);
14567                            canvas.concat(transformToApply.getMatrix());
14568                            canvas.translate(transX, transY);
14569                        }
14570                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14571                    }
14572
14573                    float transformAlpha = transformToApply.getAlpha();
14574                    if (transformAlpha < 1) {
14575                        alpha *= transformAlpha;
14576                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14577                    }
14578                }
14579
14580                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14581                    canvas.translate(-transX, -transY);
14582                    canvas.concat(getMatrix());
14583                    canvas.translate(transX, transY);
14584                }
14585            }
14586
14587            // Deal with alpha if it is or used to be <1
14588            if (alpha < 1 ||
14589                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14590                if (alpha < 1) {
14591                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14592                } else {
14593                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14594                }
14595                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14596                if (hasNoCache) {
14597                    final int multipliedAlpha = (int) (255 * alpha);
14598                    if (!onSetAlpha(multipliedAlpha)) {
14599                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14600                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14601                                layerType != LAYER_TYPE_NONE) {
14602                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14603                        }
14604                        if (useDisplayListProperties) {
14605                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14606                        } else  if (layerType == LAYER_TYPE_NONE) {
14607                            final int scrollX = hasDisplayList ? 0 : sx;
14608                            final int scrollY = hasDisplayList ? 0 : sy;
14609                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14610                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14611                        }
14612                    } else {
14613                        // Alpha is handled by the child directly, clobber the layer's alpha
14614                        mPrivateFlags |= PFLAG_ALPHA_SET;
14615                    }
14616                }
14617            }
14618        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14619            onSetAlpha(255);
14620            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14621        }
14622
14623        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14624                !useDisplayListProperties && cache == null) {
14625            if (offsetForScroll) {
14626                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14627            } else {
14628                if (!scalingRequired || cache == null) {
14629                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14630                } else {
14631                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14632                }
14633            }
14634        }
14635
14636        if (!useDisplayListProperties && hasDisplayList) {
14637            displayList = getDisplayList();
14638            if (!displayList.isValid()) {
14639                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14640                // to getDisplayList(), the display list will be marked invalid and we should not
14641                // try to use it again.
14642                displayList = null;
14643                hasDisplayList = false;
14644            }
14645        }
14646
14647        if (hasNoCache) {
14648            boolean layerRendered = false;
14649            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14650                final HardwareLayer layer = getHardwareLayer();
14651                if (layer != null && layer.isValid()) {
14652                    mLayerPaint.setAlpha((int) (alpha * 255));
14653                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14654                    layerRendered = true;
14655                } else {
14656                    final int scrollX = hasDisplayList ? 0 : sx;
14657                    final int scrollY = hasDisplayList ? 0 : sy;
14658                    canvas.saveLayer(scrollX, scrollY,
14659                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14660                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14661                }
14662            }
14663
14664            if (!layerRendered) {
14665                if (!hasDisplayList) {
14666                    // Fast path for layouts with no backgrounds
14667                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14668                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14669                        dispatchDraw(canvas);
14670                    } else {
14671                        draw(canvas);
14672                    }
14673                } else {
14674                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14675                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14676                }
14677            }
14678        } else if (cache != null) {
14679            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14680            Paint cachePaint;
14681
14682            if (layerType == LAYER_TYPE_NONE) {
14683                cachePaint = parent.mCachePaint;
14684                if (cachePaint == null) {
14685                    cachePaint = new Paint();
14686                    cachePaint.setDither(false);
14687                    parent.mCachePaint = cachePaint;
14688                }
14689                if (alpha < 1) {
14690                    cachePaint.setAlpha((int) (alpha * 255));
14691                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14692                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14693                    cachePaint.setAlpha(255);
14694                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14695                }
14696            } else {
14697                cachePaint = mLayerPaint;
14698                cachePaint.setAlpha((int) (alpha * 255));
14699            }
14700            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14701        }
14702
14703        if (restoreTo >= 0) {
14704            canvas.restoreToCount(restoreTo);
14705        }
14706
14707        if (a != null && !more) {
14708            if (!hardwareAccelerated && !a.getFillAfter()) {
14709                onSetAlpha(255);
14710            }
14711            parent.finishAnimatingView(this, a);
14712        }
14713
14714        if (more && hardwareAccelerated) {
14715            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14716                // alpha animations should cause the child to recreate its display list
14717                invalidate(true);
14718            }
14719        }
14720
14721        mRecreateDisplayList = false;
14722
14723        return more;
14724    }
14725
14726    /**
14727     * Manually render this view (and all of its children) to the given Canvas.
14728     * The view must have already done a full layout before this function is
14729     * called.  When implementing a view, implement
14730     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14731     * If you do need to override this method, call the superclass version.
14732     *
14733     * @param canvas The Canvas to which the View is rendered.
14734     */
14735    public void draw(Canvas canvas) {
14736        if (mClipBounds != null) {
14737            canvas.clipRect(mClipBounds);
14738        }
14739        final int privateFlags = mPrivateFlags;
14740        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14741                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14742        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14743
14744        /*
14745         * Draw traversal performs several drawing steps which must be executed
14746         * in the appropriate order:
14747         *
14748         *      1. Draw the background
14749         *      2. If necessary, save the canvas' layers to prepare for fading
14750         *      3. Draw view's content
14751         *      4. Draw children
14752         *      5. If necessary, draw the fading edges and restore layers
14753         *      6. Draw decorations (scrollbars for instance)
14754         */
14755
14756        // Step 1, draw the background, if needed
14757        int saveCount;
14758
14759        if (!dirtyOpaque) {
14760            drawBackground(canvas);
14761        }
14762
14763        // skip step 2 & 5 if possible (common case)
14764        final int viewFlags = mViewFlags;
14765        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14766        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14767        if (!verticalEdges && !horizontalEdges) {
14768            // Step 3, draw the content
14769            if (!dirtyOpaque) onDraw(canvas);
14770
14771            // Step 4, draw the children
14772            dispatchDraw(canvas);
14773
14774            // Step 6, draw decorations (scrollbars)
14775            onDrawScrollBars(canvas);
14776
14777            if (mOverlay != null && !mOverlay.isEmpty()) {
14778                mOverlay.getOverlayView().dispatchDraw(canvas);
14779            }
14780
14781            // we're done...
14782            return;
14783        }
14784
14785        /*
14786         * Here we do the full fledged routine...
14787         * (this is an uncommon case where speed matters less,
14788         * this is why we repeat some of the tests that have been
14789         * done above)
14790         */
14791
14792        boolean drawTop = false;
14793        boolean drawBottom = false;
14794        boolean drawLeft = false;
14795        boolean drawRight = false;
14796
14797        float topFadeStrength = 0.0f;
14798        float bottomFadeStrength = 0.0f;
14799        float leftFadeStrength = 0.0f;
14800        float rightFadeStrength = 0.0f;
14801
14802        // Step 2, save the canvas' layers
14803        int paddingLeft = mPaddingLeft;
14804
14805        final boolean offsetRequired = isPaddingOffsetRequired();
14806        if (offsetRequired) {
14807            paddingLeft += getLeftPaddingOffset();
14808        }
14809
14810        int left = mScrollX + paddingLeft;
14811        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14812        int top = mScrollY + getFadeTop(offsetRequired);
14813        int bottom = top + getFadeHeight(offsetRequired);
14814
14815        if (offsetRequired) {
14816            right += getRightPaddingOffset();
14817            bottom += getBottomPaddingOffset();
14818        }
14819
14820        final ScrollabilityCache scrollabilityCache = mScrollCache;
14821        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14822        int length = (int) fadeHeight;
14823
14824        // clip the fade length if top and bottom fades overlap
14825        // overlapping fades produce odd-looking artifacts
14826        if (verticalEdges && (top + length > bottom - length)) {
14827            length = (bottom - top) / 2;
14828        }
14829
14830        // also clip horizontal fades if necessary
14831        if (horizontalEdges && (left + length > right - length)) {
14832            length = (right - left) / 2;
14833        }
14834
14835        if (verticalEdges) {
14836            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14837            drawTop = topFadeStrength * fadeHeight > 1.0f;
14838            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14839            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14840        }
14841
14842        if (horizontalEdges) {
14843            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14844            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14845            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14846            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14847        }
14848
14849        saveCount = canvas.getSaveCount();
14850
14851        int solidColor = getSolidColor();
14852        if (solidColor == 0) {
14853            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14854
14855            if (drawTop) {
14856                canvas.saveLayer(left, top, right, top + length, null, flags);
14857            }
14858
14859            if (drawBottom) {
14860                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14861            }
14862
14863            if (drawLeft) {
14864                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14865            }
14866
14867            if (drawRight) {
14868                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14869            }
14870        } else {
14871            scrollabilityCache.setFadeColor(solidColor);
14872        }
14873
14874        // Step 3, draw the content
14875        if (!dirtyOpaque) onDraw(canvas);
14876
14877        // Step 4, draw the children
14878        dispatchDraw(canvas);
14879
14880        // Step 5, draw the fade effect and restore layers
14881        final Paint p = scrollabilityCache.paint;
14882        final Matrix matrix = scrollabilityCache.matrix;
14883        final Shader fade = scrollabilityCache.shader;
14884
14885        if (drawTop) {
14886            matrix.setScale(1, fadeHeight * topFadeStrength);
14887            matrix.postTranslate(left, top);
14888            fade.setLocalMatrix(matrix);
14889            canvas.drawRect(left, top, right, top + length, p);
14890        }
14891
14892        if (drawBottom) {
14893            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14894            matrix.postRotate(180);
14895            matrix.postTranslate(left, bottom);
14896            fade.setLocalMatrix(matrix);
14897            canvas.drawRect(left, bottom - length, right, bottom, p);
14898        }
14899
14900        if (drawLeft) {
14901            matrix.setScale(1, fadeHeight * leftFadeStrength);
14902            matrix.postRotate(-90);
14903            matrix.postTranslate(left, top);
14904            fade.setLocalMatrix(matrix);
14905            canvas.drawRect(left, top, left + length, bottom, p);
14906        }
14907
14908        if (drawRight) {
14909            matrix.setScale(1, fadeHeight * rightFadeStrength);
14910            matrix.postRotate(90);
14911            matrix.postTranslate(right, top);
14912            fade.setLocalMatrix(matrix);
14913            canvas.drawRect(right - length, top, right, bottom, p);
14914        }
14915
14916        canvas.restoreToCount(saveCount);
14917
14918        // Step 6, draw decorations (scrollbars)
14919        onDrawScrollBars(canvas);
14920
14921        if (mOverlay != null && !mOverlay.isEmpty()) {
14922            mOverlay.getOverlayView().dispatchDraw(canvas);
14923        }
14924    }
14925
14926    /**
14927     * Draws the background onto the specified canvas.
14928     *
14929     * @param canvas Canvas on which to draw the background
14930     */
14931    private void drawBackground(Canvas canvas) {
14932        final Drawable background = mBackground;
14933        if (background == null) {
14934            return;
14935        }
14936
14937        if (mBackgroundSizeChanged) {
14938            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14939            mBackgroundSizeChanged = false;
14940            queryOutlineFromBackgroundIfUndefined();
14941        }
14942
14943        // Attempt to use a display list if requested.
14944        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14945                && mAttachInfo.mHardwareRenderer != null) {
14946            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
14947
14948            final RenderNode displayList = mBackgroundDisplayList;
14949            if (displayList != null && displayList.isValid()) {
14950                setBackgroundDisplayListProperties(displayList);
14951                ((HardwareCanvas) canvas).drawDisplayList(displayList);
14952                return;
14953            }
14954        }
14955
14956        final int scrollX = mScrollX;
14957        final int scrollY = mScrollY;
14958        if ((scrollX | scrollY) == 0) {
14959            background.draw(canvas);
14960        } else {
14961            canvas.translate(scrollX, scrollY);
14962            background.draw(canvas);
14963            canvas.translate(-scrollX, -scrollY);
14964        }
14965    }
14966
14967    /**
14968     * Set up background drawable display list properties.
14969     *
14970     * @param displayList Valid display list for the background drawable
14971     */
14972    private void setBackgroundDisplayListProperties(RenderNode displayList) {
14973        displayList.setTranslationX(mScrollX);
14974        displayList.setTranslationY(mScrollY);
14975    }
14976
14977    /**
14978     * Creates a new display list or updates the existing display list for the
14979     * specified Drawable.
14980     *
14981     * @param drawable Drawable for which to create a display list
14982     * @param displayList Existing display list, or {@code null}
14983     * @return A valid display list for the specified drawable
14984     */
14985    private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) {
14986        if (displayList == null) {
14987            displayList = RenderNode.create(drawable.getClass().getName());
14988        }
14989
14990        final Rect bounds = drawable.getBounds();
14991        final int width = bounds.width();
14992        final int height = bounds.height();
14993        final HardwareCanvas canvas = displayList.start(width, height);
14994        try {
14995            drawable.draw(canvas);
14996        } finally {
14997            displayList.end(canvas);
14998        }
14999
15000        // Set up drawable properties that are view-independent.
15001        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15002        displayList.setProjectBackwards(drawable.isProjected());
15003        displayList.setProjectionReceiver(true);
15004        displayList.setClipToBounds(false);
15005        return displayList;
15006    }
15007
15008    /**
15009     * Returns the overlay for this view, creating it if it does not yet exist.
15010     * Adding drawables to the overlay will cause them to be displayed whenever
15011     * the view itself is redrawn. Objects in the overlay should be actively
15012     * managed: remove them when they should not be displayed anymore. The
15013     * overlay will always have the same size as its host view.
15014     *
15015     * <p>Note: Overlays do not currently work correctly with {@link
15016     * SurfaceView} or {@link TextureView}; contents in overlays for these
15017     * types of views may not display correctly.</p>
15018     *
15019     * @return The ViewOverlay object for this view.
15020     * @see ViewOverlay
15021     */
15022    public ViewOverlay getOverlay() {
15023        if (mOverlay == null) {
15024            mOverlay = new ViewOverlay(mContext, this);
15025        }
15026        return mOverlay;
15027    }
15028
15029    /**
15030     * Override this if your view is known to always be drawn on top of a solid color background,
15031     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15032     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15033     * should be set to 0xFF.
15034     *
15035     * @see #setVerticalFadingEdgeEnabled(boolean)
15036     * @see #setHorizontalFadingEdgeEnabled(boolean)
15037     *
15038     * @return The known solid color background for this view, or 0 if the color may vary
15039     */
15040    @ViewDebug.ExportedProperty(category = "drawing")
15041    public int getSolidColor() {
15042        return 0;
15043    }
15044
15045    /**
15046     * Build a human readable string representation of the specified view flags.
15047     *
15048     * @param flags the view flags to convert to a string
15049     * @return a String representing the supplied flags
15050     */
15051    private static String printFlags(int flags) {
15052        String output = "";
15053        int numFlags = 0;
15054        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15055            output += "TAKES_FOCUS";
15056            numFlags++;
15057        }
15058
15059        switch (flags & VISIBILITY_MASK) {
15060        case INVISIBLE:
15061            if (numFlags > 0) {
15062                output += " ";
15063            }
15064            output += "INVISIBLE";
15065            // USELESS HERE numFlags++;
15066            break;
15067        case GONE:
15068            if (numFlags > 0) {
15069                output += " ";
15070            }
15071            output += "GONE";
15072            // USELESS HERE numFlags++;
15073            break;
15074        default:
15075            break;
15076        }
15077        return output;
15078    }
15079
15080    /**
15081     * Build a human readable string representation of the specified private
15082     * view flags.
15083     *
15084     * @param privateFlags the private view flags to convert to a string
15085     * @return a String representing the supplied flags
15086     */
15087    private static String printPrivateFlags(int privateFlags) {
15088        String output = "";
15089        int numFlags = 0;
15090
15091        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15092            output += "WANTS_FOCUS";
15093            numFlags++;
15094        }
15095
15096        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15097            if (numFlags > 0) {
15098                output += " ";
15099            }
15100            output += "FOCUSED";
15101            numFlags++;
15102        }
15103
15104        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15105            if (numFlags > 0) {
15106                output += " ";
15107            }
15108            output += "SELECTED";
15109            numFlags++;
15110        }
15111
15112        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15113            if (numFlags > 0) {
15114                output += " ";
15115            }
15116            output += "IS_ROOT_NAMESPACE";
15117            numFlags++;
15118        }
15119
15120        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15121            if (numFlags > 0) {
15122                output += " ";
15123            }
15124            output += "HAS_BOUNDS";
15125            numFlags++;
15126        }
15127
15128        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15129            if (numFlags > 0) {
15130                output += " ";
15131            }
15132            output += "DRAWN";
15133            // USELESS HERE numFlags++;
15134        }
15135        return output;
15136    }
15137
15138    /**
15139     * <p>Indicates whether or not this view's layout will be requested during
15140     * the next hierarchy layout pass.</p>
15141     *
15142     * @return true if the layout will be forced during next layout pass
15143     */
15144    public boolean isLayoutRequested() {
15145        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15146    }
15147
15148    /**
15149     * Return true if o is a ViewGroup that is laying out using optical bounds.
15150     * @hide
15151     */
15152    public static boolean isLayoutModeOptical(Object o) {
15153        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15154    }
15155
15156    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15157        Insets parentInsets = mParent instanceof View ?
15158                ((View) mParent).getOpticalInsets() : Insets.NONE;
15159        Insets childInsets = getOpticalInsets();
15160        return setFrame(
15161                left   + parentInsets.left - childInsets.left,
15162                top    + parentInsets.top  - childInsets.top,
15163                right  + parentInsets.left + childInsets.right,
15164                bottom + parentInsets.top  + childInsets.bottom);
15165    }
15166
15167    /**
15168     * Assign a size and position to a view and all of its
15169     * descendants
15170     *
15171     * <p>This is the second phase of the layout mechanism.
15172     * (The first is measuring). In this phase, each parent calls
15173     * layout on all of its children to position them.
15174     * This is typically done using the child measurements
15175     * that were stored in the measure pass().</p>
15176     *
15177     * <p>Derived classes should not override this method.
15178     * Derived classes with children should override
15179     * onLayout. In that method, they should
15180     * call layout on each of their children.</p>
15181     *
15182     * @param l Left position, relative to parent
15183     * @param t Top position, relative to parent
15184     * @param r Right position, relative to parent
15185     * @param b Bottom position, relative to parent
15186     */
15187    @SuppressWarnings({"unchecked"})
15188    public void layout(int l, int t, int r, int b) {
15189        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15190            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15191            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15192        }
15193
15194        int oldL = mLeft;
15195        int oldT = mTop;
15196        int oldB = mBottom;
15197        int oldR = mRight;
15198
15199        boolean changed = isLayoutModeOptical(mParent) ?
15200                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15201
15202        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15203            onLayout(changed, l, t, r, b);
15204            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15205
15206            ListenerInfo li = mListenerInfo;
15207            if (li != null && li.mOnLayoutChangeListeners != null) {
15208                ArrayList<OnLayoutChangeListener> listenersCopy =
15209                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15210                int numListeners = listenersCopy.size();
15211                for (int i = 0; i < numListeners; ++i) {
15212                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15213                }
15214            }
15215        }
15216
15217        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15218        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15219    }
15220
15221    /**
15222     * Called from layout when this view should
15223     * assign a size and position to each of its children.
15224     *
15225     * Derived classes with children should override
15226     * this method and call layout on each of
15227     * their children.
15228     * @param changed This is a new size or position for this view
15229     * @param left Left position, relative to parent
15230     * @param top Top position, relative to parent
15231     * @param right Right position, relative to parent
15232     * @param bottom Bottom position, relative to parent
15233     */
15234    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15235    }
15236
15237    /**
15238     * Assign a size and position to this view.
15239     *
15240     * This is called from layout.
15241     *
15242     * @param left Left position, relative to parent
15243     * @param top Top position, relative to parent
15244     * @param right Right position, relative to parent
15245     * @param bottom Bottom position, relative to parent
15246     * @return true if the new size and position are different than the
15247     *         previous ones
15248     * {@hide}
15249     */
15250    protected boolean setFrame(int left, int top, int right, int bottom) {
15251        boolean changed = false;
15252
15253        if (DBG) {
15254            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15255                    + right + "," + bottom + ")");
15256        }
15257
15258        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15259            changed = true;
15260
15261            // Remember our drawn bit
15262            int drawn = mPrivateFlags & PFLAG_DRAWN;
15263
15264            int oldWidth = mRight - mLeft;
15265            int oldHeight = mBottom - mTop;
15266            int newWidth = right - left;
15267            int newHeight = bottom - top;
15268            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15269
15270            // Invalidate our old position
15271            invalidate(sizeChanged);
15272
15273            mLeft = left;
15274            mTop = top;
15275            mRight = right;
15276            mBottom = bottom;
15277            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15278
15279            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15280
15281
15282            if (sizeChanged) {
15283                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15284            }
15285
15286            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15287                // If we are visible, force the DRAWN bit to on so that
15288                // this invalidate will go through (at least to our parent).
15289                // This is because someone may have invalidated this view
15290                // before this call to setFrame came in, thereby clearing
15291                // the DRAWN bit.
15292                mPrivateFlags |= PFLAG_DRAWN;
15293                invalidate(sizeChanged);
15294                // parent display list may need to be recreated based on a change in the bounds
15295                // of any child
15296                invalidateParentCaches();
15297            }
15298
15299            // Reset drawn bit to original value (invalidate turns it off)
15300            mPrivateFlags |= drawn;
15301
15302            mBackgroundSizeChanged = true;
15303
15304            notifySubtreeAccessibilityStateChangedIfNeeded();
15305        }
15306        return changed;
15307    }
15308
15309    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15310        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15311        if (mOverlay != null) {
15312            mOverlay.getOverlayView().setRight(newWidth);
15313            mOverlay.getOverlayView().setBottom(newHeight);
15314        }
15315    }
15316
15317    /**
15318     * Finalize inflating a view from XML.  This is called as the last phase
15319     * of inflation, after all child views have been added.
15320     *
15321     * <p>Even if the subclass overrides onFinishInflate, they should always be
15322     * sure to call the super method, so that we get called.
15323     */
15324    protected void onFinishInflate() {
15325    }
15326
15327    /**
15328     * Returns the resources associated with this view.
15329     *
15330     * @return Resources object.
15331     */
15332    public Resources getResources() {
15333        return mResources;
15334    }
15335
15336    /**
15337     * Invalidates the specified Drawable.
15338     *
15339     * @param drawable the drawable to invalidate
15340     */
15341    @Override
15342    public void invalidateDrawable(@NonNull Drawable drawable) {
15343        if (verifyDrawable(drawable)) {
15344            final Rect dirty = drawable.getDirtyBounds();
15345            final int scrollX = mScrollX;
15346            final int scrollY = mScrollY;
15347
15348            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15349                    dirty.right + scrollX, dirty.bottom + scrollY);
15350
15351            if (drawable == mBackground) {
15352                queryOutlineFromBackgroundIfUndefined();
15353            }
15354        }
15355    }
15356
15357    /**
15358     * Schedules an action on a drawable to occur at a specified time.
15359     *
15360     * @param who the recipient of the action
15361     * @param what the action to run on the drawable
15362     * @param when the time at which the action must occur. Uses the
15363     *        {@link SystemClock#uptimeMillis} timebase.
15364     */
15365    @Override
15366    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15367        if (verifyDrawable(who) && what != null) {
15368            final long delay = when - SystemClock.uptimeMillis();
15369            if (mAttachInfo != null) {
15370                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15371                        Choreographer.CALLBACK_ANIMATION, what, who,
15372                        Choreographer.subtractFrameDelay(delay));
15373            } else {
15374                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15375            }
15376        }
15377    }
15378
15379    /**
15380     * Cancels a scheduled action on a drawable.
15381     *
15382     * @param who the recipient of the action
15383     * @param what the action to cancel
15384     */
15385    @Override
15386    public void unscheduleDrawable(Drawable who, Runnable what) {
15387        if (verifyDrawable(who) && what != null) {
15388            if (mAttachInfo != null) {
15389                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15390                        Choreographer.CALLBACK_ANIMATION, what, who);
15391            }
15392            ViewRootImpl.getRunQueue().removeCallbacks(what);
15393        }
15394    }
15395
15396    /**
15397     * Unschedule any events associated with the given Drawable.  This can be
15398     * used when selecting a new Drawable into a view, so that the previous
15399     * one is completely unscheduled.
15400     *
15401     * @param who The Drawable to unschedule.
15402     *
15403     * @see #drawableStateChanged
15404     */
15405    public void unscheduleDrawable(Drawable who) {
15406        if (mAttachInfo != null && who != null) {
15407            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15408                    Choreographer.CALLBACK_ANIMATION, null, who);
15409        }
15410    }
15411
15412    /**
15413     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15414     * that the View directionality can and will be resolved before its Drawables.
15415     *
15416     * Will call {@link View#onResolveDrawables} when resolution is done.
15417     *
15418     * @hide
15419     */
15420    protected void resolveDrawables() {
15421        // Drawables resolution may need to happen before resolving the layout direction (which is
15422        // done only during the measure() call).
15423        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15424        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15425        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15426        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15427        // direction to be resolved as its resolved value will be the same as its raw value.
15428        if (!isLayoutDirectionResolved() &&
15429                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15430            return;
15431        }
15432
15433        final int layoutDirection = isLayoutDirectionResolved() ?
15434                getLayoutDirection() : getRawLayoutDirection();
15435
15436        if (mBackground != null) {
15437            mBackground.setLayoutDirection(layoutDirection);
15438        }
15439        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15440        onResolveDrawables(layoutDirection);
15441    }
15442
15443    /**
15444     * Called when layout direction has been resolved.
15445     *
15446     * The default implementation does nothing.
15447     *
15448     * @param layoutDirection The resolved layout direction.
15449     *
15450     * @see #LAYOUT_DIRECTION_LTR
15451     * @see #LAYOUT_DIRECTION_RTL
15452     *
15453     * @hide
15454     */
15455    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15456    }
15457
15458    /**
15459     * @hide
15460     */
15461    protected void resetResolvedDrawables() {
15462        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15463    }
15464
15465    private boolean isDrawablesResolved() {
15466        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15467    }
15468
15469    /**
15470     * If your view subclass is displaying its own Drawable objects, it should
15471     * override this function and return true for any Drawable it is
15472     * displaying.  This allows animations for those drawables to be
15473     * scheduled.
15474     *
15475     * <p>Be sure to call through to the super class when overriding this
15476     * function.
15477     *
15478     * @param who The Drawable to verify.  Return true if it is one you are
15479     *            displaying, else return the result of calling through to the
15480     *            super class.
15481     *
15482     * @return boolean If true than the Drawable is being displayed in the
15483     *         view; else false and it is not allowed to animate.
15484     *
15485     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15486     * @see #drawableStateChanged()
15487     */
15488    protected boolean verifyDrawable(Drawable who) {
15489        return who == mBackground;
15490    }
15491
15492    /**
15493     * This function is called whenever the state of the view changes in such
15494     * a way that it impacts the state of drawables being shown.
15495     * <p>
15496     * If the View has a StateListAnimator, it will also be called to run necessary state
15497     * change animations.
15498     * <p>
15499     * Be sure to call through to the superclass when overriding this function.
15500     *
15501     * @see Drawable#setState(int[])
15502     */
15503    protected void drawableStateChanged() {
15504        final Drawable d = mBackground;
15505        if (d != null && d.isStateful()) {
15506            d.setState(getDrawableState());
15507        }
15508
15509        if (mStateListAnimator != null) {
15510            mStateListAnimator.setState(getDrawableState());
15511        }
15512    }
15513
15514    /**
15515     * Call this to force a view to update its drawable state. This will cause
15516     * drawableStateChanged to be called on this view. Views that are interested
15517     * in the new state should call getDrawableState.
15518     *
15519     * @see #drawableStateChanged
15520     * @see #getDrawableState
15521     */
15522    public void refreshDrawableState() {
15523        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15524        drawableStateChanged();
15525
15526        ViewParent parent = mParent;
15527        if (parent != null) {
15528            parent.childDrawableStateChanged(this);
15529        }
15530    }
15531
15532    /**
15533     * Return an array of resource IDs of the drawable states representing the
15534     * current state of the view.
15535     *
15536     * @return The current drawable state
15537     *
15538     * @see Drawable#setState(int[])
15539     * @see #drawableStateChanged()
15540     * @see #onCreateDrawableState(int)
15541     */
15542    public final int[] getDrawableState() {
15543        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15544            return mDrawableState;
15545        } else {
15546            mDrawableState = onCreateDrawableState(0);
15547            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15548            return mDrawableState;
15549        }
15550    }
15551
15552    /**
15553     * Generate the new {@link android.graphics.drawable.Drawable} state for
15554     * this view. This is called by the view
15555     * system when the cached Drawable state is determined to be invalid.  To
15556     * retrieve the current state, you should use {@link #getDrawableState}.
15557     *
15558     * @param extraSpace if non-zero, this is the number of extra entries you
15559     * would like in the returned array in which you can place your own
15560     * states.
15561     *
15562     * @return Returns an array holding the current {@link Drawable} state of
15563     * the view.
15564     *
15565     * @see #mergeDrawableStates(int[], int[])
15566     */
15567    protected int[] onCreateDrawableState(int extraSpace) {
15568        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15569                mParent instanceof View) {
15570            return ((View) mParent).onCreateDrawableState(extraSpace);
15571        }
15572
15573        int[] drawableState;
15574
15575        int privateFlags = mPrivateFlags;
15576
15577        int viewStateIndex = 0;
15578        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15579        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15580        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15581        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15582        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15583        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15584        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15585                HardwareRenderer.isAvailable()) {
15586            // This is set if HW acceleration is requested, even if the current
15587            // process doesn't allow it.  This is just to allow app preview
15588            // windows to better match their app.
15589            viewStateIndex |= VIEW_STATE_ACCELERATED;
15590        }
15591        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15592
15593        final int privateFlags2 = mPrivateFlags2;
15594        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15595        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15596
15597        drawableState = VIEW_STATE_SETS[viewStateIndex];
15598
15599        //noinspection ConstantIfStatement
15600        if (false) {
15601            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15602            Log.i("View", toString()
15603                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15604                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15605                    + " fo=" + hasFocus()
15606                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15607                    + " wf=" + hasWindowFocus()
15608                    + ": " + Arrays.toString(drawableState));
15609        }
15610
15611        if (extraSpace == 0) {
15612            return drawableState;
15613        }
15614
15615        final int[] fullState;
15616        if (drawableState != null) {
15617            fullState = new int[drawableState.length + extraSpace];
15618            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15619        } else {
15620            fullState = new int[extraSpace];
15621        }
15622
15623        return fullState;
15624    }
15625
15626    /**
15627     * Merge your own state values in <var>additionalState</var> into the base
15628     * state values <var>baseState</var> that were returned by
15629     * {@link #onCreateDrawableState(int)}.
15630     *
15631     * @param baseState The base state values returned by
15632     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15633     * own additional state values.
15634     *
15635     * @param additionalState The additional state values you would like
15636     * added to <var>baseState</var>; this array is not modified.
15637     *
15638     * @return As a convenience, the <var>baseState</var> array you originally
15639     * passed into the function is returned.
15640     *
15641     * @see #onCreateDrawableState(int)
15642     */
15643    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15644        final int N = baseState.length;
15645        int i = N - 1;
15646        while (i >= 0 && baseState[i] == 0) {
15647            i--;
15648        }
15649        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15650        return baseState;
15651    }
15652
15653    /**
15654     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15655     * on all Drawable objects associated with this view.
15656     * <p>
15657     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15658     * attached to this view.
15659     */
15660    public void jumpDrawablesToCurrentState() {
15661        if (mBackground != null) {
15662            mBackground.jumpToCurrentState();
15663        }
15664        if (mStateListAnimator != null) {
15665            mStateListAnimator.jumpToCurrentState();
15666        }
15667    }
15668
15669    /**
15670     * Sets the background color for this view.
15671     * @param color the color of the background
15672     */
15673    @RemotableViewMethod
15674    public void setBackgroundColor(int color) {
15675        if (mBackground instanceof ColorDrawable) {
15676            ((ColorDrawable) mBackground.mutate()).setColor(color);
15677            computeOpaqueFlags();
15678            mBackgroundResource = 0;
15679        } else {
15680            setBackground(new ColorDrawable(color));
15681        }
15682    }
15683
15684    /**
15685     * Set the background to a given resource. The resource should refer to
15686     * a Drawable object or 0 to remove the background.
15687     * @param resid The identifier of the resource.
15688     *
15689     * @attr ref android.R.styleable#View_background
15690     */
15691    @RemotableViewMethod
15692    public void setBackgroundResource(int resid) {
15693        if (resid != 0 && resid == mBackgroundResource) {
15694            return;
15695        }
15696
15697        Drawable d= null;
15698        if (resid != 0) {
15699            d = mContext.getDrawable(resid);
15700        }
15701        setBackground(d);
15702
15703        mBackgroundResource = resid;
15704    }
15705
15706    /**
15707     * Set the background to a given Drawable, or remove the background. If the
15708     * background has padding, this View's padding is set to the background's
15709     * padding. However, when a background is removed, this View's padding isn't
15710     * touched. If setting the padding is desired, please use
15711     * {@link #setPadding(int, int, int, int)}.
15712     *
15713     * @param background The Drawable to use as the background, or null to remove the
15714     *        background
15715     */
15716    public void setBackground(Drawable background) {
15717        //noinspection deprecation
15718        setBackgroundDrawable(background);
15719    }
15720
15721    /**
15722     * @deprecated use {@link #setBackground(Drawable)} instead
15723     */
15724    @Deprecated
15725    public void setBackgroundDrawable(Drawable background) {
15726        computeOpaqueFlags();
15727
15728        if (background == mBackground) {
15729            return;
15730        }
15731
15732        boolean requestLayout = false;
15733
15734        mBackgroundResource = 0;
15735
15736        /*
15737         * Regardless of whether we're setting a new background or not, we want
15738         * to clear the previous drawable.
15739         */
15740        if (mBackground != null) {
15741            mBackground.setCallback(null);
15742            unscheduleDrawable(mBackground);
15743        }
15744
15745        if (background != null) {
15746            Rect padding = sThreadLocal.get();
15747            if (padding == null) {
15748                padding = new Rect();
15749                sThreadLocal.set(padding);
15750            }
15751            resetResolvedDrawables();
15752            background.setLayoutDirection(getLayoutDirection());
15753            if (background.getPadding(padding)) {
15754                resetResolvedPadding();
15755                switch (background.getLayoutDirection()) {
15756                    case LAYOUT_DIRECTION_RTL:
15757                        mUserPaddingLeftInitial = padding.right;
15758                        mUserPaddingRightInitial = padding.left;
15759                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15760                        break;
15761                    case LAYOUT_DIRECTION_LTR:
15762                    default:
15763                        mUserPaddingLeftInitial = padding.left;
15764                        mUserPaddingRightInitial = padding.right;
15765                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15766                }
15767                mLeftPaddingDefined = false;
15768                mRightPaddingDefined = false;
15769            }
15770
15771            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15772            // if it has a different minimum size, we should layout again
15773            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15774                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15775                requestLayout = true;
15776            }
15777
15778            background.setCallback(this);
15779            if (background.isStateful()) {
15780                background.setState(getDrawableState());
15781            }
15782            background.setVisible(getVisibility() == VISIBLE, false);
15783            mBackground = background;
15784
15785            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15786                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15787                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15788                requestLayout = true;
15789            }
15790        } else {
15791            /* Remove the background */
15792            mBackground = null;
15793
15794            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15795                /*
15796                 * This view ONLY drew the background before and we're removing
15797                 * the background, so now it won't draw anything
15798                 * (hence we SKIP_DRAW)
15799                 */
15800                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15801                mPrivateFlags |= PFLAG_SKIP_DRAW;
15802            }
15803
15804            /*
15805             * When the background is set, we try to apply its padding to this
15806             * View. When the background is removed, we don't touch this View's
15807             * padding. This is noted in the Javadocs. Hence, we don't need to
15808             * requestLayout(), the invalidate() below is sufficient.
15809             */
15810
15811            // The old background's minimum size could have affected this
15812            // View's layout, so let's requestLayout
15813            requestLayout = true;
15814        }
15815
15816        computeOpaqueFlags();
15817
15818        if (requestLayout) {
15819            requestLayout();
15820        }
15821
15822        mBackgroundSizeChanged = true;
15823        invalidate(true);
15824    }
15825
15826    /**
15827     * Gets the background drawable
15828     *
15829     * @return The drawable used as the background for this view, if any.
15830     *
15831     * @see #setBackground(Drawable)
15832     *
15833     * @attr ref android.R.styleable#View_background
15834     */
15835    public Drawable getBackground() {
15836        return mBackground;
15837    }
15838
15839    /**
15840     * Sets the padding. The view may add on the space required to display
15841     * the scrollbars, depending on the style and visibility of the scrollbars.
15842     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15843     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15844     * from the values set in this call.
15845     *
15846     * @attr ref android.R.styleable#View_padding
15847     * @attr ref android.R.styleable#View_paddingBottom
15848     * @attr ref android.R.styleable#View_paddingLeft
15849     * @attr ref android.R.styleable#View_paddingRight
15850     * @attr ref android.R.styleable#View_paddingTop
15851     * @param left the left padding in pixels
15852     * @param top the top padding in pixels
15853     * @param right the right padding in pixels
15854     * @param bottom the bottom padding in pixels
15855     */
15856    public void setPadding(int left, int top, int right, int bottom) {
15857        resetResolvedPadding();
15858
15859        mUserPaddingStart = UNDEFINED_PADDING;
15860        mUserPaddingEnd = UNDEFINED_PADDING;
15861
15862        mUserPaddingLeftInitial = left;
15863        mUserPaddingRightInitial = right;
15864
15865        mLeftPaddingDefined = true;
15866        mRightPaddingDefined = true;
15867
15868        internalSetPadding(left, top, right, bottom);
15869    }
15870
15871    /**
15872     * @hide
15873     */
15874    protected void internalSetPadding(int left, int top, int right, int bottom) {
15875        mUserPaddingLeft = left;
15876        mUserPaddingRight = right;
15877        mUserPaddingBottom = bottom;
15878
15879        final int viewFlags = mViewFlags;
15880        boolean changed = false;
15881
15882        // Common case is there are no scroll bars.
15883        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15884            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15885                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15886                        ? 0 : getVerticalScrollbarWidth();
15887                switch (mVerticalScrollbarPosition) {
15888                    case SCROLLBAR_POSITION_DEFAULT:
15889                        if (isLayoutRtl()) {
15890                            left += offset;
15891                        } else {
15892                            right += offset;
15893                        }
15894                        break;
15895                    case SCROLLBAR_POSITION_RIGHT:
15896                        right += offset;
15897                        break;
15898                    case SCROLLBAR_POSITION_LEFT:
15899                        left += offset;
15900                        break;
15901                }
15902            }
15903            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15904                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15905                        ? 0 : getHorizontalScrollbarHeight();
15906            }
15907        }
15908
15909        if (mPaddingLeft != left) {
15910            changed = true;
15911            mPaddingLeft = left;
15912        }
15913        if (mPaddingTop != top) {
15914            changed = true;
15915            mPaddingTop = top;
15916        }
15917        if (mPaddingRight != right) {
15918            changed = true;
15919            mPaddingRight = right;
15920        }
15921        if (mPaddingBottom != bottom) {
15922            changed = true;
15923            mPaddingBottom = bottom;
15924        }
15925
15926        if (changed) {
15927            requestLayout();
15928        }
15929    }
15930
15931    /**
15932     * Sets the relative padding. The view may add on the space required to display
15933     * the scrollbars, depending on the style and visibility of the scrollbars.
15934     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15935     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15936     * from the values set in this call.
15937     *
15938     * @attr ref android.R.styleable#View_padding
15939     * @attr ref android.R.styleable#View_paddingBottom
15940     * @attr ref android.R.styleable#View_paddingStart
15941     * @attr ref android.R.styleable#View_paddingEnd
15942     * @attr ref android.R.styleable#View_paddingTop
15943     * @param start the start padding in pixels
15944     * @param top the top padding in pixels
15945     * @param end the end padding in pixels
15946     * @param bottom the bottom padding in pixels
15947     */
15948    public void setPaddingRelative(int start, int top, int end, int bottom) {
15949        resetResolvedPadding();
15950
15951        mUserPaddingStart = start;
15952        mUserPaddingEnd = end;
15953        mLeftPaddingDefined = true;
15954        mRightPaddingDefined = true;
15955
15956        switch(getLayoutDirection()) {
15957            case LAYOUT_DIRECTION_RTL:
15958                mUserPaddingLeftInitial = end;
15959                mUserPaddingRightInitial = start;
15960                internalSetPadding(end, top, start, bottom);
15961                break;
15962            case LAYOUT_DIRECTION_LTR:
15963            default:
15964                mUserPaddingLeftInitial = start;
15965                mUserPaddingRightInitial = end;
15966                internalSetPadding(start, top, end, bottom);
15967        }
15968    }
15969
15970    /**
15971     * Returns the top padding of this view.
15972     *
15973     * @return the top padding in pixels
15974     */
15975    public int getPaddingTop() {
15976        return mPaddingTop;
15977    }
15978
15979    /**
15980     * Returns the bottom padding of this view. If there are inset and enabled
15981     * scrollbars, this value may include the space required to display the
15982     * scrollbars as well.
15983     *
15984     * @return the bottom padding in pixels
15985     */
15986    public int getPaddingBottom() {
15987        return mPaddingBottom;
15988    }
15989
15990    /**
15991     * Returns the left padding of this view. If there are inset and enabled
15992     * scrollbars, this value may include the space required to display the
15993     * scrollbars as well.
15994     *
15995     * @return the left padding in pixels
15996     */
15997    public int getPaddingLeft() {
15998        if (!isPaddingResolved()) {
15999            resolvePadding();
16000        }
16001        return mPaddingLeft;
16002    }
16003
16004    /**
16005     * Returns the start padding of this view depending on its resolved layout direction.
16006     * If there are inset and enabled scrollbars, this value may include the space
16007     * required to display the scrollbars as well.
16008     *
16009     * @return the start padding in pixels
16010     */
16011    public int getPaddingStart() {
16012        if (!isPaddingResolved()) {
16013            resolvePadding();
16014        }
16015        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16016                mPaddingRight : mPaddingLeft;
16017    }
16018
16019    /**
16020     * Returns the right padding of this view. If there are inset and enabled
16021     * scrollbars, this value may include the space required to display the
16022     * scrollbars as well.
16023     *
16024     * @return the right padding in pixels
16025     */
16026    public int getPaddingRight() {
16027        if (!isPaddingResolved()) {
16028            resolvePadding();
16029        }
16030        return mPaddingRight;
16031    }
16032
16033    /**
16034     * Returns the end padding of this view depending on its resolved layout direction.
16035     * If there are inset and enabled scrollbars, this value may include the space
16036     * required to display the scrollbars as well.
16037     *
16038     * @return the end padding in pixels
16039     */
16040    public int getPaddingEnd() {
16041        if (!isPaddingResolved()) {
16042            resolvePadding();
16043        }
16044        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16045                mPaddingLeft : mPaddingRight;
16046    }
16047
16048    /**
16049     * Return if the padding as been set thru relative values
16050     * {@link #setPaddingRelative(int, int, int, int)} or thru
16051     * @attr ref android.R.styleable#View_paddingStart or
16052     * @attr ref android.R.styleable#View_paddingEnd
16053     *
16054     * @return true if the padding is relative or false if it is not.
16055     */
16056    public boolean isPaddingRelative() {
16057        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16058    }
16059
16060    Insets computeOpticalInsets() {
16061        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16062    }
16063
16064    /**
16065     * @hide
16066     */
16067    public void resetPaddingToInitialValues() {
16068        if (isRtlCompatibilityMode()) {
16069            mPaddingLeft = mUserPaddingLeftInitial;
16070            mPaddingRight = mUserPaddingRightInitial;
16071            return;
16072        }
16073        if (isLayoutRtl()) {
16074            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16075            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16076        } else {
16077            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16078            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16079        }
16080    }
16081
16082    /**
16083     * @hide
16084     */
16085    public Insets getOpticalInsets() {
16086        if (mLayoutInsets == null) {
16087            mLayoutInsets = computeOpticalInsets();
16088        }
16089        return mLayoutInsets;
16090    }
16091
16092    /**
16093     * Set this view's optical insets.
16094     *
16095     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16096     * property. Views that compute their own optical insets should call it as part of measurement.
16097     * This method does not request layout. If you are setting optical insets outside of
16098     * measure/layout itself you will want to call requestLayout() yourself.
16099     * </p>
16100     * @hide
16101     */
16102    public void setOpticalInsets(Insets insets) {
16103        mLayoutInsets = insets;
16104    }
16105
16106    /**
16107     * Changes the selection state of this view. A view can be selected or not.
16108     * Note that selection is not the same as focus. Views are typically
16109     * selected in the context of an AdapterView like ListView or GridView;
16110     * the selected view is the view that is highlighted.
16111     *
16112     * @param selected true if the view must be selected, false otherwise
16113     */
16114    public void setSelected(boolean selected) {
16115        //noinspection DoubleNegation
16116        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16117            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16118            if (!selected) resetPressedState();
16119            invalidate(true);
16120            refreshDrawableState();
16121            dispatchSetSelected(selected);
16122            notifyViewAccessibilityStateChangedIfNeeded(
16123                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16124        }
16125    }
16126
16127    /**
16128     * Dispatch setSelected to all of this View's children.
16129     *
16130     * @see #setSelected(boolean)
16131     *
16132     * @param selected The new selected state
16133     */
16134    protected void dispatchSetSelected(boolean selected) {
16135    }
16136
16137    /**
16138     * Indicates the selection state of this view.
16139     *
16140     * @return true if the view is selected, false otherwise
16141     */
16142    @ViewDebug.ExportedProperty
16143    public boolean isSelected() {
16144        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16145    }
16146
16147    /**
16148     * Changes the activated state of this view. A view can be activated or not.
16149     * Note that activation is not the same as selection.  Selection is
16150     * a transient property, representing the view (hierarchy) the user is
16151     * currently interacting with.  Activation is a longer-term state that the
16152     * user can move views in and out of.  For example, in a list view with
16153     * single or multiple selection enabled, the views in the current selection
16154     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16155     * here.)  The activated state is propagated down to children of the view it
16156     * is set on.
16157     *
16158     * @param activated true if the view must be activated, false otherwise
16159     */
16160    public void setActivated(boolean activated) {
16161        //noinspection DoubleNegation
16162        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16163            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16164            invalidate(true);
16165            refreshDrawableState();
16166            dispatchSetActivated(activated);
16167        }
16168    }
16169
16170    /**
16171     * Dispatch setActivated to all of this View's children.
16172     *
16173     * @see #setActivated(boolean)
16174     *
16175     * @param activated The new activated state
16176     */
16177    protected void dispatchSetActivated(boolean activated) {
16178    }
16179
16180    /**
16181     * Indicates the activation state of this view.
16182     *
16183     * @return true if the view is activated, false otherwise
16184     */
16185    @ViewDebug.ExportedProperty
16186    public boolean isActivated() {
16187        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16188    }
16189
16190    /**
16191     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16192     * observer can be used to get notifications when global events, like
16193     * layout, happen.
16194     *
16195     * The returned ViewTreeObserver observer is not guaranteed to remain
16196     * valid for the lifetime of this View. If the caller of this method keeps
16197     * a long-lived reference to ViewTreeObserver, it should always check for
16198     * the return value of {@link ViewTreeObserver#isAlive()}.
16199     *
16200     * @return The ViewTreeObserver for this view's hierarchy.
16201     */
16202    public ViewTreeObserver getViewTreeObserver() {
16203        if (mAttachInfo != null) {
16204            return mAttachInfo.mTreeObserver;
16205        }
16206        if (mFloatingTreeObserver == null) {
16207            mFloatingTreeObserver = new ViewTreeObserver();
16208        }
16209        return mFloatingTreeObserver;
16210    }
16211
16212    /**
16213     * <p>Finds the topmost view in the current view hierarchy.</p>
16214     *
16215     * @return the topmost view containing this view
16216     */
16217    public View getRootView() {
16218        if (mAttachInfo != null) {
16219            final View v = mAttachInfo.mRootView;
16220            if (v != null) {
16221                return v;
16222            }
16223        }
16224
16225        View parent = this;
16226
16227        while (parent.mParent != null && parent.mParent instanceof View) {
16228            parent = (View) parent.mParent;
16229        }
16230
16231        return parent;
16232    }
16233
16234    /**
16235     * Transforms a motion event from view-local coordinates to on-screen
16236     * coordinates.
16237     *
16238     * @param ev the view-local motion event
16239     * @return false if the transformation could not be applied
16240     * @hide
16241     */
16242    public boolean toGlobalMotionEvent(MotionEvent ev) {
16243        final AttachInfo info = mAttachInfo;
16244        if (info == null) {
16245            return false;
16246        }
16247
16248        final Matrix m = info.mTmpMatrix;
16249        m.set(Matrix.IDENTITY_MATRIX);
16250        transformMatrixToGlobal(m);
16251        ev.transform(m);
16252        return true;
16253    }
16254
16255    /**
16256     * Transforms a motion event from on-screen coordinates to view-local
16257     * coordinates.
16258     *
16259     * @param ev the on-screen motion event
16260     * @return false if the transformation could not be applied
16261     * @hide
16262     */
16263    public boolean toLocalMotionEvent(MotionEvent ev) {
16264        final AttachInfo info = mAttachInfo;
16265        if (info == null) {
16266            return false;
16267        }
16268
16269        final Matrix m = info.mTmpMatrix;
16270        m.set(Matrix.IDENTITY_MATRIX);
16271        transformMatrixToLocal(m);
16272        ev.transform(m);
16273        return true;
16274    }
16275
16276    /**
16277     * Modifies the input matrix such that it maps view-local coordinates to
16278     * on-screen coordinates.
16279     *
16280     * @param m input matrix to modify
16281     */
16282    void transformMatrixToGlobal(Matrix m) {
16283        final ViewParent parent = mParent;
16284        if (parent instanceof View) {
16285            final View vp = (View) parent;
16286            vp.transformMatrixToGlobal(m);
16287            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16288        } else if (parent instanceof ViewRootImpl) {
16289            final ViewRootImpl vr = (ViewRootImpl) parent;
16290            vr.transformMatrixToGlobal(m);
16291            m.postTranslate(0, -vr.mCurScrollY);
16292        }
16293
16294        m.postTranslate(mLeft, mTop);
16295
16296        if (!hasIdentityMatrix()) {
16297            m.postConcat(getMatrix());
16298        }
16299    }
16300
16301    /**
16302     * Modifies the input matrix such that it maps on-screen coordinates to
16303     * view-local coordinates.
16304     *
16305     * @param m input matrix to modify
16306     */
16307    void transformMatrixToLocal(Matrix m) {
16308        final ViewParent parent = mParent;
16309        if (parent instanceof View) {
16310            final View vp = (View) parent;
16311            vp.transformMatrixToLocal(m);
16312            m.preTranslate(vp.mScrollX, vp.mScrollY);
16313        } else if (parent instanceof ViewRootImpl) {
16314            final ViewRootImpl vr = (ViewRootImpl) parent;
16315            vr.transformMatrixToLocal(m);
16316            m.preTranslate(0, vr.mCurScrollY);
16317        }
16318
16319        m.preTranslate(-mLeft, -mTop);
16320
16321        if (!hasIdentityMatrix()) {
16322            m.preConcat(getInverseMatrix());
16323        }
16324    }
16325
16326    /**
16327     * <p>Computes the coordinates of this view on the screen. The argument
16328     * must be an array of two integers. After the method returns, the array
16329     * contains the x and y location in that order.</p>
16330     *
16331     * @param location an array of two integers in which to hold the coordinates
16332     */
16333    public void getLocationOnScreen(int[] location) {
16334        getLocationInWindow(location);
16335
16336        final AttachInfo info = mAttachInfo;
16337        if (info != null) {
16338            location[0] += info.mWindowLeft;
16339            location[1] += info.mWindowTop;
16340        }
16341    }
16342
16343    /**
16344     * <p>Computes the coordinates of this view in its window. The argument
16345     * must be an array of two integers. After the method returns, the array
16346     * contains the x and y location in that order.</p>
16347     *
16348     * @param location an array of two integers in which to hold the coordinates
16349     */
16350    public void getLocationInWindow(int[] location) {
16351        if (location == null || location.length < 2) {
16352            throw new IllegalArgumentException("location must be an array of two integers");
16353        }
16354
16355        if (mAttachInfo == null) {
16356            // When the view is not attached to a window, this method does not make sense
16357            location[0] = location[1] = 0;
16358            return;
16359        }
16360
16361        float[] position = mAttachInfo.mTmpTransformLocation;
16362        position[0] = position[1] = 0.0f;
16363
16364        if (!hasIdentityMatrix()) {
16365            getMatrix().mapPoints(position);
16366        }
16367
16368        position[0] += mLeft;
16369        position[1] += mTop;
16370
16371        ViewParent viewParent = mParent;
16372        while (viewParent instanceof View) {
16373            final View view = (View) viewParent;
16374
16375            position[0] -= view.mScrollX;
16376            position[1] -= view.mScrollY;
16377
16378            if (!view.hasIdentityMatrix()) {
16379                view.getMatrix().mapPoints(position);
16380            }
16381
16382            position[0] += view.mLeft;
16383            position[1] += view.mTop;
16384
16385            viewParent = view.mParent;
16386         }
16387
16388        if (viewParent instanceof ViewRootImpl) {
16389            // *cough*
16390            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16391            position[1] -= vr.mCurScrollY;
16392        }
16393
16394        location[0] = (int) (position[0] + 0.5f);
16395        location[1] = (int) (position[1] + 0.5f);
16396    }
16397
16398    /**
16399     * {@hide}
16400     * @param id the id of the view to be found
16401     * @return the view of the specified id, null if cannot be found
16402     */
16403    protected View findViewTraversal(int id) {
16404        if (id == mID) {
16405            return this;
16406        }
16407        return null;
16408    }
16409
16410    /**
16411     * {@hide}
16412     * @param tag the tag of the view to be found
16413     * @return the view of specified tag, null if cannot be found
16414     */
16415    protected View findViewWithTagTraversal(Object tag) {
16416        if (tag != null && tag.equals(mTag)) {
16417            return this;
16418        }
16419        return null;
16420    }
16421
16422    /**
16423     * {@hide}
16424     * @param predicate The predicate to evaluate.
16425     * @param childToSkip If not null, ignores this child during the recursive traversal.
16426     * @return The first view that matches the predicate or null.
16427     */
16428    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16429        if (predicate.apply(this)) {
16430            return this;
16431        }
16432        return null;
16433    }
16434
16435    /**
16436     * Look for a child view with the given id.  If this view has the given
16437     * id, return this view.
16438     *
16439     * @param id The id to search for.
16440     * @return The view that has the given id in the hierarchy or null
16441     */
16442    public final View findViewById(int id) {
16443        if (id < 0) {
16444            return null;
16445        }
16446        return findViewTraversal(id);
16447    }
16448
16449    /**
16450     * Finds a view by its unuque and stable accessibility id.
16451     *
16452     * @param accessibilityId The searched accessibility id.
16453     * @return The found view.
16454     */
16455    final View findViewByAccessibilityId(int accessibilityId) {
16456        if (accessibilityId < 0) {
16457            return null;
16458        }
16459        return findViewByAccessibilityIdTraversal(accessibilityId);
16460    }
16461
16462    /**
16463     * Performs the traversal to find a view by its unuque and stable accessibility id.
16464     *
16465     * <strong>Note:</strong>This method does not stop at the root namespace
16466     * boundary since the user can touch the screen at an arbitrary location
16467     * potentially crossing the root namespace bounday which will send an
16468     * accessibility event to accessibility services and they should be able
16469     * to obtain the event source. Also accessibility ids are guaranteed to be
16470     * unique in the window.
16471     *
16472     * @param accessibilityId The accessibility id.
16473     * @return The found view.
16474     *
16475     * @hide
16476     */
16477    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16478        if (getAccessibilityViewId() == accessibilityId) {
16479            return this;
16480        }
16481        return null;
16482    }
16483
16484    /**
16485     * Look for a child view with the given tag.  If this view has the given
16486     * tag, return this view.
16487     *
16488     * @param tag The tag to search for, using "tag.equals(getTag())".
16489     * @return The View that has the given tag in the hierarchy or null
16490     */
16491    public final View findViewWithTag(Object tag) {
16492        if (tag == null) {
16493            return null;
16494        }
16495        return findViewWithTagTraversal(tag);
16496    }
16497
16498    /**
16499     * {@hide}
16500     * Look for a child view that matches the specified predicate.
16501     * If this view matches the predicate, return this view.
16502     *
16503     * @param predicate The predicate to evaluate.
16504     * @return The first view that matches the predicate or null.
16505     */
16506    public final View findViewByPredicate(Predicate<View> predicate) {
16507        return findViewByPredicateTraversal(predicate, null);
16508    }
16509
16510    /**
16511     * {@hide}
16512     * Look for a child view that matches the specified predicate,
16513     * starting with the specified view and its descendents and then
16514     * recusively searching the ancestors and siblings of that view
16515     * until this view is reached.
16516     *
16517     * This method is useful in cases where the predicate does not match
16518     * a single unique view (perhaps multiple views use the same id)
16519     * and we are trying to find the view that is "closest" in scope to the
16520     * starting view.
16521     *
16522     * @param start The view to start from.
16523     * @param predicate The predicate to evaluate.
16524     * @return The first view that matches the predicate or null.
16525     */
16526    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16527        View childToSkip = null;
16528        for (;;) {
16529            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16530            if (view != null || start == this) {
16531                return view;
16532            }
16533
16534            ViewParent parent = start.getParent();
16535            if (parent == null || !(parent instanceof View)) {
16536                return null;
16537            }
16538
16539            childToSkip = start;
16540            start = (View) parent;
16541        }
16542    }
16543
16544    /**
16545     * Sets the identifier for this view. The identifier does not have to be
16546     * unique in this view's hierarchy. The identifier should be a positive
16547     * number.
16548     *
16549     * @see #NO_ID
16550     * @see #getId()
16551     * @see #findViewById(int)
16552     *
16553     * @param id a number used to identify the view
16554     *
16555     * @attr ref android.R.styleable#View_id
16556     */
16557    public void setId(int id) {
16558        mID = id;
16559        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16560            mID = generateViewId();
16561        }
16562    }
16563
16564    /**
16565     * {@hide}
16566     *
16567     * @param isRoot true if the view belongs to the root namespace, false
16568     *        otherwise
16569     */
16570    public void setIsRootNamespace(boolean isRoot) {
16571        if (isRoot) {
16572            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16573        } else {
16574            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16575        }
16576    }
16577
16578    /**
16579     * {@hide}
16580     *
16581     * @return true if the view belongs to the root namespace, false otherwise
16582     */
16583    public boolean isRootNamespace() {
16584        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16585    }
16586
16587    /**
16588     * Returns this view's identifier.
16589     *
16590     * @return a positive integer used to identify the view or {@link #NO_ID}
16591     *         if the view has no ID
16592     *
16593     * @see #setId(int)
16594     * @see #findViewById(int)
16595     * @attr ref android.R.styleable#View_id
16596     */
16597    @ViewDebug.CapturedViewProperty
16598    public int getId() {
16599        return mID;
16600    }
16601
16602    /**
16603     * Returns this view's tag.
16604     *
16605     * @return the Object stored in this view as a tag, or {@code null} if not
16606     *         set
16607     *
16608     * @see #setTag(Object)
16609     * @see #getTag(int)
16610     */
16611    @ViewDebug.ExportedProperty
16612    public Object getTag() {
16613        return mTag;
16614    }
16615
16616    /**
16617     * Sets the tag associated with this view. A tag can be used to mark
16618     * a view in its hierarchy and does not have to be unique within the
16619     * hierarchy. Tags can also be used to store data within a view without
16620     * resorting to another data structure.
16621     *
16622     * @param tag an Object to tag the view with
16623     *
16624     * @see #getTag()
16625     * @see #setTag(int, Object)
16626     */
16627    public void setTag(final Object tag) {
16628        mTag = tag;
16629    }
16630
16631    /**
16632     * Returns the tag associated with this view and the specified key.
16633     *
16634     * @param key The key identifying the tag
16635     *
16636     * @return the Object stored in this view as a tag, or {@code null} if not
16637     *         set
16638     *
16639     * @see #setTag(int, Object)
16640     * @see #getTag()
16641     */
16642    public Object getTag(int key) {
16643        if (mKeyedTags != null) return mKeyedTags.get(key);
16644        return null;
16645    }
16646
16647    /**
16648     * Sets a tag associated with this view and a key. A tag can be used
16649     * to mark a view in its hierarchy and does not have to be unique within
16650     * the hierarchy. Tags can also be used to store data within a view
16651     * without resorting to another data structure.
16652     *
16653     * The specified key should be an id declared in the resources of the
16654     * application to ensure it is unique (see the <a
16655     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16656     * Keys identified as belonging to
16657     * the Android framework or not associated with any package will cause
16658     * an {@link IllegalArgumentException} to be thrown.
16659     *
16660     * @param key The key identifying the tag
16661     * @param tag An Object to tag the view with
16662     *
16663     * @throws IllegalArgumentException If they specified key is not valid
16664     *
16665     * @see #setTag(Object)
16666     * @see #getTag(int)
16667     */
16668    public void setTag(int key, final Object tag) {
16669        // If the package id is 0x00 or 0x01, it's either an undefined package
16670        // or a framework id
16671        if ((key >>> 24) < 2) {
16672            throw new IllegalArgumentException("The key must be an application-specific "
16673                    + "resource id.");
16674        }
16675
16676        setKeyedTag(key, tag);
16677    }
16678
16679    /**
16680     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16681     * framework id.
16682     *
16683     * @hide
16684     */
16685    public void setTagInternal(int key, Object tag) {
16686        if ((key >>> 24) != 0x1) {
16687            throw new IllegalArgumentException("The key must be a framework-specific "
16688                    + "resource id.");
16689        }
16690
16691        setKeyedTag(key, tag);
16692    }
16693
16694    private void setKeyedTag(int key, Object tag) {
16695        if (mKeyedTags == null) {
16696            mKeyedTags = new SparseArray<Object>(2);
16697        }
16698
16699        mKeyedTags.put(key, tag);
16700    }
16701
16702    /**
16703     * Prints information about this view in the log output, with the tag
16704     * {@link #VIEW_LOG_TAG}.
16705     *
16706     * @hide
16707     */
16708    public void debug() {
16709        debug(0);
16710    }
16711
16712    /**
16713     * Prints information about this view in the log output, with the tag
16714     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16715     * indentation defined by the <code>depth</code>.
16716     *
16717     * @param depth the indentation level
16718     *
16719     * @hide
16720     */
16721    protected void debug(int depth) {
16722        String output = debugIndent(depth - 1);
16723
16724        output += "+ " + this;
16725        int id = getId();
16726        if (id != -1) {
16727            output += " (id=" + id + ")";
16728        }
16729        Object tag = getTag();
16730        if (tag != null) {
16731            output += " (tag=" + tag + ")";
16732        }
16733        Log.d(VIEW_LOG_TAG, output);
16734
16735        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16736            output = debugIndent(depth) + " FOCUSED";
16737            Log.d(VIEW_LOG_TAG, output);
16738        }
16739
16740        output = debugIndent(depth);
16741        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16742                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16743                + "} ";
16744        Log.d(VIEW_LOG_TAG, output);
16745
16746        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16747                || mPaddingBottom != 0) {
16748            output = debugIndent(depth);
16749            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16750                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16751            Log.d(VIEW_LOG_TAG, output);
16752        }
16753
16754        output = debugIndent(depth);
16755        output += "mMeasureWidth=" + mMeasuredWidth +
16756                " mMeasureHeight=" + mMeasuredHeight;
16757        Log.d(VIEW_LOG_TAG, output);
16758
16759        output = debugIndent(depth);
16760        if (mLayoutParams == null) {
16761            output += "BAD! no layout params";
16762        } else {
16763            output = mLayoutParams.debug(output);
16764        }
16765        Log.d(VIEW_LOG_TAG, output);
16766
16767        output = debugIndent(depth);
16768        output += "flags={";
16769        output += View.printFlags(mViewFlags);
16770        output += "}";
16771        Log.d(VIEW_LOG_TAG, output);
16772
16773        output = debugIndent(depth);
16774        output += "privateFlags={";
16775        output += View.printPrivateFlags(mPrivateFlags);
16776        output += "}";
16777        Log.d(VIEW_LOG_TAG, output);
16778    }
16779
16780    /**
16781     * Creates a string of whitespaces used for indentation.
16782     *
16783     * @param depth the indentation level
16784     * @return a String containing (depth * 2 + 3) * 2 white spaces
16785     *
16786     * @hide
16787     */
16788    protected static String debugIndent(int depth) {
16789        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16790        for (int i = 0; i < (depth * 2) + 3; i++) {
16791            spaces.append(' ').append(' ');
16792        }
16793        return spaces.toString();
16794    }
16795
16796    /**
16797     * <p>Return the offset of the widget's text baseline from the widget's top
16798     * boundary. If this widget does not support baseline alignment, this
16799     * method returns -1. </p>
16800     *
16801     * @return the offset of the baseline within the widget's bounds or -1
16802     *         if baseline alignment is not supported
16803     */
16804    @ViewDebug.ExportedProperty(category = "layout")
16805    public int getBaseline() {
16806        return -1;
16807    }
16808
16809    /**
16810     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16811     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16812     * a layout pass.
16813     *
16814     * @return whether the view hierarchy is currently undergoing a layout pass
16815     */
16816    public boolean isInLayout() {
16817        ViewRootImpl viewRoot = getViewRootImpl();
16818        return (viewRoot != null && viewRoot.isInLayout());
16819    }
16820
16821    /**
16822     * Call this when something has changed which has invalidated the
16823     * layout of this view. This will schedule a layout pass of the view
16824     * tree. This should not be called while the view hierarchy is currently in a layout
16825     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16826     * end of the current layout pass (and then layout will run again) or after the current
16827     * frame is drawn and the next layout occurs.
16828     *
16829     * <p>Subclasses which override this method should call the superclass method to
16830     * handle possible request-during-layout errors correctly.</p>
16831     */
16832    public void requestLayout() {
16833        if (mMeasureCache != null) mMeasureCache.clear();
16834
16835        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16836            // Only trigger request-during-layout logic if this is the view requesting it,
16837            // not the views in its parent hierarchy
16838            ViewRootImpl viewRoot = getViewRootImpl();
16839            if (viewRoot != null && viewRoot.isInLayout()) {
16840                if (!viewRoot.requestLayoutDuringLayout(this)) {
16841                    return;
16842                }
16843            }
16844            mAttachInfo.mViewRequestingLayout = this;
16845        }
16846
16847        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16848        mPrivateFlags |= PFLAG_INVALIDATED;
16849
16850        if (mParent != null && !mParent.isLayoutRequested()) {
16851            mParent.requestLayout();
16852        }
16853        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16854            mAttachInfo.mViewRequestingLayout = null;
16855        }
16856    }
16857
16858    /**
16859     * Forces this view to be laid out during the next layout pass.
16860     * This method does not call requestLayout() or forceLayout()
16861     * on the parent.
16862     */
16863    public void forceLayout() {
16864        if (mMeasureCache != null) mMeasureCache.clear();
16865
16866        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16867        mPrivateFlags |= PFLAG_INVALIDATED;
16868    }
16869
16870    /**
16871     * <p>
16872     * This is called to find out how big a view should be. The parent
16873     * supplies constraint information in the width and height parameters.
16874     * </p>
16875     *
16876     * <p>
16877     * The actual measurement work of a view is performed in
16878     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16879     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16880     * </p>
16881     *
16882     *
16883     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16884     *        parent
16885     * @param heightMeasureSpec Vertical space requirements as imposed by the
16886     *        parent
16887     *
16888     * @see #onMeasure(int, int)
16889     */
16890    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16891        boolean optical = isLayoutModeOptical(this);
16892        if (optical != isLayoutModeOptical(mParent)) {
16893            Insets insets = getOpticalInsets();
16894            int oWidth  = insets.left + insets.right;
16895            int oHeight = insets.top  + insets.bottom;
16896            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16897            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16898        }
16899
16900        // Suppress sign extension for the low bytes
16901        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16902        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16903
16904        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16905                widthMeasureSpec != mOldWidthMeasureSpec ||
16906                heightMeasureSpec != mOldHeightMeasureSpec) {
16907
16908            // first clears the measured dimension flag
16909            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16910
16911            resolveRtlPropertiesIfNeeded();
16912
16913            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16914                    mMeasureCache.indexOfKey(key);
16915            if (cacheIndex < 0 || sIgnoreMeasureCache) {
16916                // measure ourselves, this should set the measured dimension flag back
16917                onMeasure(widthMeasureSpec, heightMeasureSpec);
16918                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16919            } else {
16920                long value = mMeasureCache.valueAt(cacheIndex);
16921                // Casting a long to int drops the high 32 bits, no mask needed
16922                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
16923                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16924            }
16925
16926            // flag not set, setMeasuredDimension() was not invoked, we raise
16927            // an exception to warn the developer
16928            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16929                throw new IllegalStateException("onMeasure() did not set the"
16930                        + " measured dimension by calling"
16931                        + " setMeasuredDimension()");
16932            }
16933
16934            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16935        }
16936
16937        mOldWidthMeasureSpec = widthMeasureSpec;
16938        mOldHeightMeasureSpec = heightMeasureSpec;
16939
16940        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16941                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16942    }
16943
16944    /**
16945     * <p>
16946     * Measure the view and its content to determine the measured width and the
16947     * measured height. This method is invoked by {@link #measure(int, int)} and
16948     * should be overriden by subclasses to provide accurate and efficient
16949     * measurement of their contents.
16950     * </p>
16951     *
16952     * <p>
16953     * <strong>CONTRACT:</strong> When overriding this method, you
16954     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16955     * measured width and height of this view. Failure to do so will trigger an
16956     * <code>IllegalStateException</code>, thrown by
16957     * {@link #measure(int, int)}. Calling the superclass'
16958     * {@link #onMeasure(int, int)} is a valid use.
16959     * </p>
16960     *
16961     * <p>
16962     * The base class implementation of measure defaults to the background size,
16963     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16964     * override {@link #onMeasure(int, int)} to provide better measurements of
16965     * their content.
16966     * </p>
16967     *
16968     * <p>
16969     * If this method is overridden, it is the subclass's responsibility to make
16970     * sure the measured height and width are at least the view's minimum height
16971     * and width ({@link #getSuggestedMinimumHeight()} and
16972     * {@link #getSuggestedMinimumWidth()}).
16973     * </p>
16974     *
16975     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16976     *                         The requirements are encoded with
16977     *                         {@link android.view.View.MeasureSpec}.
16978     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16979     *                         The requirements are encoded with
16980     *                         {@link android.view.View.MeasureSpec}.
16981     *
16982     * @see #getMeasuredWidth()
16983     * @see #getMeasuredHeight()
16984     * @see #setMeasuredDimension(int, int)
16985     * @see #getSuggestedMinimumHeight()
16986     * @see #getSuggestedMinimumWidth()
16987     * @see android.view.View.MeasureSpec#getMode(int)
16988     * @see android.view.View.MeasureSpec#getSize(int)
16989     */
16990    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16991        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16992                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16993    }
16994
16995    /**
16996     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16997     * measured width and measured height. Failing to do so will trigger an
16998     * exception at measurement time.</p>
16999     *
17000     * @param measuredWidth The measured width of this view.  May be a complex
17001     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17002     * {@link #MEASURED_STATE_TOO_SMALL}.
17003     * @param measuredHeight The measured height of this view.  May be a complex
17004     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17005     * {@link #MEASURED_STATE_TOO_SMALL}.
17006     */
17007    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17008        boolean optical = isLayoutModeOptical(this);
17009        if (optical != isLayoutModeOptical(mParent)) {
17010            Insets insets = getOpticalInsets();
17011            int opticalWidth  = insets.left + insets.right;
17012            int opticalHeight = insets.top  + insets.bottom;
17013
17014            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17015            measuredHeight += optical ? opticalHeight : -opticalHeight;
17016        }
17017        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17018    }
17019
17020    /**
17021     * Sets the measured dimension without extra processing for things like optical bounds.
17022     * Useful for reapplying consistent values that have already been cooked with adjustments
17023     * for optical bounds, etc. such as those from the measurement cache.
17024     *
17025     * @param measuredWidth The measured width of this view.  May be a complex
17026     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17027     * {@link #MEASURED_STATE_TOO_SMALL}.
17028     * @param measuredHeight The measured height of this view.  May be a complex
17029     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17030     * {@link #MEASURED_STATE_TOO_SMALL}.
17031     */
17032    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17033        mMeasuredWidth = measuredWidth;
17034        mMeasuredHeight = measuredHeight;
17035
17036        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17037    }
17038
17039    /**
17040     * Merge two states as returned by {@link #getMeasuredState()}.
17041     * @param curState The current state as returned from a view or the result
17042     * of combining multiple views.
17043     * @param newState The new view state to combine.
17044     * @return Returns a new integer reflecting the combination of the two
17045     * states.
17046     */
17047    public static int combineMeasuredStates(int curState, int newState) {
17048        return curState | newState;
17049    }
17050
17051    /**
17052     * Version of {@link #resolveSizeAndState(int, int, int)}
17053     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17054     */
17055    public static int resolveSize(int size, int measureSpec) {
17056        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17057    }
17058
17059    /**
17060     * Utility to reconcile a desired size and state, with constraints imposed
17061     * by a MeasureSpec.  Will take the desired size, unless a different size
17062     * is imposed by the constraints.  The returned value is a compound integer,
17063     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17064     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17065     * size is smaller than the size the view wants to be.
17066     *
17067     * @param size How big the view wants to be
17068     * @param measureSpec Constraints imposed by the parent
17069     * @return Size information bit mask as defined by
17070     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17071     */
17072    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17073        int result = size;
17074        int specMode = MeasureSpec.getMode(measureSpec);
17075        int specSize =  MeasureSpec.getSize(measureSpec);
17076        switch (specMode) {
17077        case MeasureSpec.UNSPECIFIED:
17078            result = size;
17079            break;
17080        case MeasureSpec.AT_MOST:
17081            if (specSize < size) {
17082                result = specSize | MEASURED_STATE_TOO_SMALL;
17083            } else {
17084                result = size;
17085            }
17086            break;
17087        case MeasureSpec.EXACTLY:
17088            result = specSize;
17089            break;
17090        }
17091        return result | (childMeasuredState&MEASURED_STATE_MASK);
17092    }
17093
17094    /**
17095     * Utility to return a default size. Uses the supplied size if the
17096     * MeasureSpec imposed no constraints. Will get larger if allowed
17097     * by the MeasureSpec.
17098     *
17099     * @param size Default size for this view
17100     * @param measureSpec Constraints imposed by the parent
17101     * @return The size this view should be.
17102     */
17103    public static int getDefaultSize(int size, int measureSpec) {
17104        int result = size;
17105        int specMode = MeasureSpec.getMode(measureSpec);
17106        int specSize = MeasureSpec.getSize(measureSpec);
17107
17108        switch (specMode) {
17109        case MeasureSpec.UNSPECIFIED:
17110            result = size;
17111            break;
17112        case MeasureSpec.AT_MOST:
17113        case MeasureSpec.EXACTLY:
17114            result = specSize;
17115            break;
17116        }
17117        return result;
17118    }
17119
17120    /**
17121     * Returns the suggested minimum height that the view should use. This
17122     * returns the maximum of the view's minimum height
17123     * and the background's minimum height
17124     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17125     * <p>
17126     * When being used in {@link #onMeasure(int, int)}, the caller should still
17127     * ensure the returned height is within the requirements of the parent.
17128     *
17129     * @return The suggested minimum height of the view.
17130     */
17131    protected int getSuggestedMinimumHeight() {
17132        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17133
17134    }
17135
17136    /**
17137     * Returns the suggested minimum width that the view should use. This
17138     * returns the maximum of the view's minimum width)
17139     * and the background's minimum width
17140     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17141     * <p>
17142     * When being used in {@link #onMeasure(int, int)}, the caller should still
17143     * ensure the returned width is within the requirements of the parent.
17144     *
17145     * @return The suggested minimum width of the view.
17146     */
17147    protected int getSuggestedMinimumWidth() {
17148        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17149    }
17150
17151    /**
17152     * Returns the minimum height of the view.
17153     *
17154     * @return the minimum height the view will try to be.
17155     *
17156     * @see #setMinimumHeight(int)
17157     *
17158     * @attr ref android.R.styleable#View_minHeight
17159     */
17160    public int getMinimumHeight() {
17161        return mMinHeight;
17162    }
17163
17164    /**
17165     * Sets the minimum height of the view. It is not guaranteed the view will
17166     * be able to achieve this minimum height (for example, if its parent layout
17167     * constrains it with less available height).
17168     *
17169     * @param minHeight The minimum height the view will try to be.
17170     *
17171     * @see #getMinimumHeight()
17172     *
17173     * @attr ref android.R.styleable#View_minHeight
17174     */
17175    public void setMinimumHeight(int minHeight) {
17176        mMinHeight = minHeight;
17177        requestLayout();
17178    }
17179
17180    /**
17181     * Returns the minimum width of the view.
17182     *
17183     * @return the minimum width the view will try to be.
17184     *
17185     * @see #setMinimumWidth(int)
17186     *
17187     * @attr ref android.R.styleable#View_minWidth
17188     */
17189    public int getMinimumWidth() {
17190        return mMinWidth;
17191    }
17192
17193    /**
17194     * Sets the minimum width of the view. It is not guaranteed the view will
17195     * be able to achieve this minimum width (for example, if its parent layout
17196     * constrains it with less available width).
17197     *
17198     * @param minWidth The minimum width the view will try to be.
17199     *
17200     * @see #getMinimumWidth()
17201     *
17202     * @attr ref android.R.styleable#View_minWidth
17203     */
17204    public void setMinimumWidth(int minWidth) {
17205        mMinWidth = minWidth;
17206        requestLayout();
17207
17208    }
17209
17210    /**
17211     * Get the animation currently associated with this view.
17212     *
17213     * @return The animation that is currently playing or
17214     *         scheduled to play for this view.
17215     */
17216    public Animation getAnimation() {
17217        return mCurrentAnimation;
17218    }
17219
17220    /**
17221     * Start the specified animation now.
17222     *
17223     * @param animation the animation to start now
17224     */
17225    public void startAnimation(Animation animation) {
17226        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17227        setAnimation(animation);
17228        invalidateParentCaches();
17229        invalidate(true);
17230    }
17231
17232    /**
17233     * Cancels any animations for this view.
17234     */
17235    public void clearAnimation() {
17236        if (mCurrentAnimation != null) {
17237            mCurrentAnimation.detach();
17238        }
17239        mCurrentAnimation = null;
17240        invalidateParentIfNeeded();
17241    }
17242
17243    /**
17244     * Sets the next animation to play for this view.
17245     * If you want the animation to play immediately, use
17246     * {@link #startAnimation(android.view.animation.Animation)} instead.
17247     * This method provides allows fine-grained
17248     * control over the start time and invalidation, but you
17249     * must make sure that 1) the animation has a start time set, and
17250     * 2) the view's parent (which controls animations on its children)
17251     * will be invalidated when the animation is supposed to
17252     * start.
17253     *
17254     * @param animation The next animation, or null.
17255     */
17256    public void setAnimation(Animation animation) {
17257        mCurrentAnimation = animation;
17258
17259        if (animation != null) {
17260            // If the screen is off assume the animation start time is now instead of
17261            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17262            // would cause the animation to start when the screen turns back on
17263            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17264                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17265                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17266            }
17267            animation.reset();
17268        }
17269    }
17270
17271    /**
17272     * Invoked by a parent ViewGroup to notify the start of the animation
17273     * currently associated with this view. If you override this method,
17274     * always call super.onAnimationStart();
17275     *
17276     * @see #setAnimation(android.view.animation.Animation)
17277     * @see #getAnimation()
17278     */
17279    protected void onAnimationStart() {
17280        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17281    }
17282
17283    /**
17284     * Invoked by a parent ViewGroup to notify the end of the animation
17285     * currently associated with this view. If you override this method,
17286     * always call super.onAnimationEnd();
17287     *
17288     * @see #setAnimation(android.view.animation.Animation)
17289     * @see #getAnimation()
17290     */
17291    protected void onAnimationEnd() {
17292        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17293    }
17294
17295    /**
17296     * Invoked if there is a Transform that involves alpha. Subclass that can
17297     * draw themselves with the specified alpha should return true, and then
17298     * respect that alpha when their onDraw() is called. If this returns false
17299     * then the view may be redirected to draw into an offscreen buffer to
17300     * fulfill the request, which will look fine, but may be slower than if the
17301     * subclass handles it internally. The default implementation returns false.
17302     *
17303     * @param alpha The alpha (0..255) to apply to the view's drawing
17304     * @return true if the view can draw with the specified alpha.
17305     */
17306    protected boolean onSetAlpha(int alpha) {
17307        return false;
17308    }
17309
17310    /**
17311     * This is used by the RootView to perform an optimization when
17312     * the view hierarchy contains one or several SurfaceView.
17313     * SurfaceView is always considered transparent, but its children are not,
17314     * therefore all View objects remove themselves from the global transparent
17315     * region (passed as a parameter to this function).
17316     *
17317     * @param region The transparent region for this ViewAncestor (window).
17318     *
17319     * @return Returns true if the effective visibility of the view at this
17320     * point is opaque, regardless of the transparent region; returns false
17321     * if it is possible for underlying windows to be seen behind the view.
17322     *
17323     * {@hide}
17324     */
17325    public boolean gatherTransparentRegion(Region region) {
17326        final AttachInfo attachInfo = mAttachInfo;
17327        if (region != null && attachInfo != null) {
17328            final int pflags = mPrivateFlags;
17329            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17330                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17331                // remove it from the transparent region.
17332                final int[] location = attachInfo.mTransparentLocation;
17333                getLocationInWindow(location);
17334                region.op(location[0], location[1], location[0] + mRight - mLeft,
17335                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17336            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17337                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17338                // exists, so we remove the background drawable's non-transparent
17339                // parts from this transparent region.
17340                applyDrawableToTransparentRegion(mBackground, region);
17341            }
17342        }
17343        return true;
17344    }
17345
17346    /**
17347     * Play a sound effect for this view.
17348     *
17349     * <p>The framework will play sound effects for some built in actions, such as
17350     * clicking, but you may wish to play these effects in your widget,
17351     * for instance, for internal navigation.
17352     *
17353     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17354     * {@link #isSoundEffectsEnabled()} is true.
17355     *
17356     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17357     */
17358    public void playSoundEffect(int soundConstant) {
17359        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17360            return;
17361        }
17362        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17363    }
17364
17365    /**
17366     * BZZZTT!!1!
17367     *
17368     * <p>Provide haptic feedback to the user for this view.
17369     *
17370     * <p>The framework will provide haptic feedback for some built in actions,
17371     * such as long presses, but you may wish to provide feedback for your
17372     * own widget.
17373     *
17374     * <p>The feedback will only be performed if
17375     * {@link #isHapticFeedbackEnabled()} is true.
17376     *
17377     * @param feedbackConstant One of the constants defined in
17378     * {@link HapticFeedbackConstants}
17379     */
17380    public boolean performHapticFeedback(int feedbackConstant) {
17381        return performHapticFeedback(feedbackConstant, 0);
17382    }
17383
17384    /**
17385     * BZZZTT!!1!
17386     *
17387     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17388     *
17389     * @param feedbackConstant One of the constants defined in
17390     * {@link HapticFeedbackConstants}
17391     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17392     */
17393    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17394        if (mAttachInfo == null) {
17395            return false;
17396        }
17397        //noinspection SimplifiableIfStatement
17398        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17399                && !isHapticFeedbackEnabled()) {
17400            return false;
17401        }
17402        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17403                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17404    }
17405
17406    /**
17407     * Request that the visibility of the status bar or other screen/window
17408     * decorations be changed.
17409     *
17410     * <p>This method is used to put the over device UI into temporary modes
17411     * where the user's attention is focused more on the application content,
17412     * by dimming or hiding surrounding system affordances.  This is typically
17413     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17414     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17415     * to be placed behind the action bar (and with these flags other system
17416     * affordances) so that smooth transitions between hiding and showing them
17417     * can be done.
17418     *
17419     * <p>Two representative examples of the use of system UI visibility is
17420     * implementing a content browsing application (like a magazine reader)
17421     * and a video playing application.
17422     *
17423     * <p>The first code shows a typical implementation of a View in a content
17424     * browsing application.  In this implementation, the application goes
17425     * into a content-oriented mode by hiding the status bar and action bar,
17426     * and putting the navigation elements into lights out mode.  The user can
17427     * then interact with content while in this mode.  Such an application should
17428     * provide an easy way for the user to toggle out of the mode (such as to
17429     * check information in the status bar or access notifications).  In the
17430     * implementation here, this is done simply by tapping on the content.
17431     *
17432     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17433     *      content}
17434     *
17435     * <p>This second code sample shows a typical implementation of a View
17436     * in a video playing application.  In this situation, while the video is
17437     * playing the application would like to go into a complete full-screen mode,
17438     * to use as much of the display as possible for the video.  When in this state
17439     * the user can not interact with the application; the system intercepts
17440     * touching on the screen to pop the UI out of full screen mode.  See
17441     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17442     *
17443     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17444     *      content}
17445     *
17446     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17447     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17448     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17449     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17450     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17451     */
17452    public void setSystemUiVisibility(int visibility) {
17453        if (visibility != mSystemUiVisibility) {
17454            mSystemUiVisibility = visibility;
17455            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17456                mParent.recomputeViewAttributes(this);
17457            }
17458        }
17459    }
17460
17461    /**
17462     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17463     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17464     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17465     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17466     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17467     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17468     */
17469    public int getSystemUiVisibility() {
17470        return mSystemUiVisibility;
17471    }
17472
17473    /**
17474     * Returns the current system UI visibility that is currently set for
17475     * the entire window.  This is the combination of the
17476     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17477     * views in the window.
17478     */
17479    public int getWindowSystemUiVisibility() {
17480        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17481    }
17482
17483    /**
17484     * Override to find out when the window's requested system UI visibility
17485     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17486     * This is different from the callbacks received through
17487     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17488     * in that this is only telling you about the local request of the window,
17489     * not the actual values applied by the system.
17490     */
17491    public void onWindowSystemUiVisibilityChanged(int visible) {
17492    }
17493
17494    /**
17495     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17496     * the view hierarchy.
17497     */
17498    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17499        onWindowSystemUiVisibilityChanged(visible);
17500    }
17501
17502    /**
17503     * Set a listener to receive callbacks when the visibility of the system bar changes.
17504     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17505     */
17506    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17507        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17508        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17509            mParent.recomputeViewAttributes(this);
17510        }
17511    }
17512
17513    /**
17514     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17515     * the view hierarchy.
17516     */
17517    public void dispatchSystemUiVisibilityChanged(int visibility) {
17518        ListenerInfo li = mListenerInfo;
17519        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17520            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17521                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17522        }
17523    }
17524
17525    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17526        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17527        if (val != mSystemUiVisibility) {
17528            setSystemUiVisibility(val);
17529            return true;
17530        }
17531        return false;
17532    }
17533
17534    /** @hide */
17535    public void setDisabledSystemUiVisibility(int flags) {
17536        if (mAttachInfo != null) {
17537            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17538                mAttachInfo.mDisabledSystemUiVisibility = flags;
17539                if (mParent != null) {
17540                    mParent.recomputeViewAttributes(this);
17541                }
17542            }
17543        }
17544    }
17545
17546    /**
17547     * Creates an image that the system displays during the drag and drop
17548     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17549     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17550     * appearance as the given View. The default also positions the center of the drag shadow
17551     * directly under the touch point. If no View is provided (the constructor with no parameters
17552     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17553     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17554     * default is an invisible drag shadow.
17555     * <p>
17556     * You are not required to use the View you provide to the constructor as the basis of the
17557     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17558     * anything you want as the drag shadow.
17559     * </p>
17560     * <p>
17561     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17562     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17563     *  size and position of the drag shadow. It uses this data to construct a
17564     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17565     *  so that your application can draw the shadow image in the Canvas.
17566     * </p>
17567     *
17568     * <div class="special reference">
17569     * <h3>Developer Guides</h3>
17570     * <p>For a guide to implementing drag and drop features, read the
17571     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17572     * </div>
17573     */
17574    public static class DragShadowBuilder {
17575        private final WeakReference<View> mView;
17576
17577        /**
17578         * Constructs a shadow image builder based on a View. By default, the resulting drag
17579         * shadow will have the same appearance and dimensions as the View, with the touch point
17580         * over the center of the View.
17581         * @param view A View. Any View in scope can be used.
17582         */
17583        public DragShadowBuilder(View view) {
17584            mView = new WeakReference<View>(view);
17585        }
17586
17587        /**
17588         * Construct a shadow builder object with no associated View.  This
17589         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17590         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17591         * to supply the drag shadow's dimensions and appearance without
17592         * reference to any View object. If they are not overridden, then the result is an
17593         * invisible drag shadow.
17594         */
17595        public DragShadowBuilder() {
17596            mView = new WeakReference<View>(null);
17597        }
17598
17599        /**
17600         * Returns the View object that had been passed to the
17601         * {@link #View.DragShadowBuilder(View)}
17602         * constructor.  If that View parameter was {@code null} or if the
17603         * {@link #View.DragShadowBuilder()}
17604         * constructor was used to instantiate the builder object, this method will return
17605         * null.
17606         *
17607         * @return The View object associate with this builder object.
17608         */
17609        @SuppressWarnings({"JavadocReference"})
17610        final public View getView() {
17611            return mView.get();
17612        }
17613
17614        /**
17615         * Provides the metrics for the shadow image. These include the dimensions of
17616         * the shadow image, and the point within that shadow that should
17617         * be centered under the touch location while dragging.
17618         * <p>
17619         * The default implementation sets the dimensions of the shadow to be the
17620         * same as the dimensions of the View itself and centers the shadow under
17621         * the touch point.
17622         * </p>
17623         *
17624         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17625         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17626         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17627         * image.
17628         *
17629         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17630         * shadow image that should be underneath the touch point during the drag and drop
17631         * operation. Your application must set {@link android.graphics.Point#x} to the
17632         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17633         */
17634        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17635            final View view = mView.get();
17636            if (view != null) {
17637                shadowSize.set(view.getWidth(), view.getHeight());
17638                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17639            } else {
17640                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17641            }
17642        }
17643
17644        /**
17645         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17646         * based on the dimensions it received from the
17647         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17648         *
17649         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17650         */
17651        public void onDrawShadow(Canvas canvas) {
17652            final View view = mView.get();
17653            if (view != null) {
17654                view.draw(canvas);
17655            } else {
17656                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17657            }
17658        }
17659    }
17660
17661    /**
17662     * Starts a drag and drop operation. When your application calls this method, it passes a
17663     * {@link android.view.View.DragShadowBuilder} object to the system. The
17664     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17665     * to get metrics for the drag shadow, and then calls the object's
17666     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17667     * <p>
17668     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17669     *  drag events to all the View objects in your application that are currently visible. It does
17670     *  this either by calling the View object's drag listener (an implementation of
17671     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17672     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17673     *  Both are passed a {@link android.view.DragEvent} object that has a
17674     *  {@link android.view.DragEvent#getAction()} value of
17675     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17676     * </p>
17677     * <p>
17678     * Your application can invoke startDrag() on any attached View object. The View object does not
17679     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17680     * be related to the View the user selected for dragging.
17681     * </p>
17682     * @param data A {@link android.content.ClipData} object pointing to the data to be
17683     * transferred by the drag and drop operation.
17684     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17685     * drag shadow.
17686     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17687     * drop operation. This Object is put into every DragEvent object sent by the system during the
17688     * current drag.
17689     * <p>
17690     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17691     * to the target Views. For example, it can contain flags that differentiate between a
17692     * a copy operation and a move operation.
17693     * </p>
17694     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17695     * so the parameter should be set to 0.
17696     * @return {@code true} if the method completes successfully, or
17697     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17698     * do a drag, and so no drag operation is in progress.
17699     */
17700    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17701            Object myLocalState, int flags) {
17702        if (ViewDebug.DEBUG_DRAG) {
17703            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17704        }
17705        boolean okay = false;
17706
17707        Point shadowSize = new Point();
17708        Point shadowTouchPoint = new Point();
17709        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17710
17711        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17712                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17713            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17714        }
17715
17716        if (ViewDebug.DEBUG_DRAG) {
17717            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17718                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17719        }
17720        Surface surface = new Surface();
17721        try {
17722            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17723                    flags, shadowSize.x, shadowSize.y, surface);
17724            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17725                    + " surface=" + surface);
17726            if (token != null) {
17727                Canvas canvas = surface.lockCanvas(null);
17728                try {
17729                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17730                    shadowBuilder.onDrawShadow(canvas);
17731                } finally {
17732                    surface.unlockCanvasAndPost(canvas);
17733                }
17734
17735                final ViewRootImpl root = getViewRootImpl();
17736
17737                // Cache the local state object for delivery with DragEvents
17738                root.setLocalDragState(myLocalState);
17739
17740                // repurpose 'shadowSize' for the last touch point
17741                root.getLastTouchPoint(shadowSize);
17742
17743                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17744                        shadowSize.x, shadowSize.y,
17745                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17746                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17747
17748                // Off and running!  Release our local surface instance; the drag
17749                // shadow surface is now managed by the system process.
17750                surface.release();
17751            }
17752        } catch (Exception e) {
17753            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17754            surface.destroy();
17755        }
17756
17757        return okay;
17758    }
17759
17760    /**
17761     * Handles drag events sent by the system following a call to
17762     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17763     *<p>
17764     * When the system calls this method, it passes a
17765     * {@link android.view.DragEvent} object. A call to
17766     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17767     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17768     * operation.
17769     * @param event The {@link android.view.DragEvent} sent by the system.
17770     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17771     * in DragEvent, indicating the type of drag event represented by this object.
17772     * @return {@code true} if the method was successful, otherwise {@code false}.
17773     * <p>
17774     *  The method should return {@code true} in response to an action type of
17775     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17776     *  operation.
17777     * </p>
17778     * <p>
17779     *  The method should also return {@code true} in response to an action type of
17780     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17781     *  {@code false} if it didn't.
17782     * </p>
17783     */
17784    public boolean onDragEvent(DragEvent event) {
17785        return false;
17786    }
17787
17788    /**
17789     * Detects if this View is enabled and has a drag event listener.
17790     * If both are true, then it calls the drag event listener with the
17791     * {@link android.view.DragEvent} it received. If the drag event listener returns
17792     * {@code true}, then dispatchDragEvent() returns {@code true}.
17793     * <p>
17794     * For all other cases, the method calls the
17795     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17796     * method and returns its result.
17797     * </p>
17798     * <p>
17799     * This ensures that a drag event is always consumed, even if the View does not have a drag
17800     * event listener. However, if the View has a listener and the listener returns true, then
17801     * onDragEvent() is not called.
17802     * </p>
17803     */
17804    public boolean dispatchDragEvent(DragEvent event) {
17805        ListenerInfo li = mListenerInfo;
17806        //noinspection SimplifiableIfStatement
17807        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17808                && li.mOnDragListener.onDrag(this, event)) {
17809            return true;
17810        }
17811        return onDragEvent(event);
17812    }
17813
17814    boolean canAcceptDrag() {
17815        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17816    }
17817
17818    /**
17819     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17820     * it is ever exposed at all.
17821     * @hide
17822     */
17823    public void onCloseSystemDialogs(String reason) {
17824    }
17825
17826    /**
17827     * Given a Drawable whose bounds have been set to draw into this view,
17828     * update a Region being computed for
17829     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17830     * that any non-transparent parts of the Drawable are removed from the
17831     * given transparent region.
17832     *
17833     * @param dr The Drawable whose transparency is to be applied to the region.
17834     * @param region A Region holding the current transparency information,
17835     * where any parts of the region that are set are considered to be
17836     * transparent.  On return, this region will be modified to have the
17837     * transparency information reduced by the corresponding parts of the
17838     * Drawable that are not transparent.
17839     * {@hide}
17840     */
17841    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17842        if (DBG) {
17843            Log.i("View", "Getting transparent region for: " + this);
17844        }
17845        final Region r = dr.getTransparentRegion();
17846        final Rect db = dr.getBounds();
17847        final AttachInfo attachInfo = mAttachInfo;
17848        if (r != null && attachInfo != null) {
17849            final int w = getRight()-getLeft();
17850            final int h = getBottom()-getTop();
17851            if (db.left > 0) {
17852                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17853                r.op(0, 0, db.left, h, Region.Op.UNION);
17854            }
17855            if (db.right < w) {
17856                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17857                r.op(db.right, 0, w, h, Region.Op.UNION);
17858            }
17859            if (db.top > 0) {
17860                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17861                r.op(0, 0, w, db.top, Region.Op.UNION);
17862            }
17863            if (db.bottom < h) {
17864                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17865                r.op(0, db.bottom, w, h, Region.Op.UNION);
17866            }
17867            final int[] location = attachInfo.mTransparentLocation;
17868            getLocationInWindow(location);
17869            r.translate(location[0], location[1]);
17870            region.op(r, Region.Op.INTERSECT);
17871        } else {
17872            region.op(db, Region.Op.DIFFERENCE);
17873        }
17874    }
17875
17876    private void checkForLongClick(int delayOffset) {
17877        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17878            mHasPerformedLongPress = false;
17879
17880            if (mPendingCheckForLongPress == null) {
17881                mPendingCheckForLongPress = new CheckForLongPress();
17882            }
17883            mPendingCheckForLongPress.rememberWindowAttachCount();
17884            postDelayed(mPendingCheckForLongPress,
17885                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17886        }
17887    }
17888
17889    /**
17890     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17891     * LayoutInflater} class, which provides a full range of options for view inflation.
17892     *
17893     * @param context The Context object for your activity or application.
17894     * @param resource The resource ID to inflate
17895     * @param root A view group that will be the parent.  Used to properly inflate the
17896     * layout_* parameters.
17897     * @see LayoutInflater
17898     */
17899    public static View inflate(Context context, int resource, ViewGroup root) {
17900        LayoutInflater factory = LayoutInflater.from(context);
17901        return factory.inflate(resource, root);
17902    }
17903
17904    /**
17905     * Scroll the view with standard behavior for scrolling beyond the normal
17906     * content boundaries. Views that call this method should override
17907     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17908     * results of an over-scroll operation.
17909     *
17910     * Views can use this method to handle any touch or fling-based scrolling.
17911     *
17912     * @param deltaX Change in X in pixels
17913     * @param deltaY Change in Y in pixels
17914     * @param scrollX Current X scroll value in pixels before applying deltaX
17915     * @param scrollY Current Y scroll value in pixels before applying deltaY
17916     * @param scrollRangeX Maximum content scroll range along the X axis
17917     * @param scrollRangeY Maximum content scroll range along the Y axis
17918     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17919     *          along the X axis.
17920     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17921     *          along the Y axis.
17922     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17923     * @return true if scrolling was clamped to an over-scroll boundary along either
17924     *          axis, false otherwise.
17925     */
17926    @SuppressWarnings({"UnusedParameters"})
17927    protected boolean overScrollBy(int deltaX, int deltaY,
17928            int scrollX, int scrollY,
17929            int scrollRangeX, int scrollRangeY,
17930            int maxOverScrollX, int maxOverScrollY,
17931            boolean isTouchEvent) {
17932        final int overScrollMode = mOverScrollMode;
17933        final boolean canScrollHorizontal =
17934                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17935        final boolean canScrollVertical =
17936                computeVerticalScrollRange() > computeVerticalScrollExtent();
17937        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17938                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17939        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17940                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17941
17942        int newScrollX = scrollX + deltaX;
17943        if (!overScrollHorizontal) {
17944            maxOverScrollX = 0;
17945        }
17946
17947        int newScrollY = scrollY + deltaY;
17948        if (!overScrollVertical) {
17949            maxOverScrollY = 0;
17950        }
17951
17952        // Clamp values if at the limits and record
17953        final int left = -maxOverScrollX;
17954        final int right = maxOverScrollX + scrollRangeX;
17955        final int top = -maxOverScrollY;
17956        final int bottom = maxOverScrollY + scrollRangeY;
17957
17958        boolean clampedX = false;
17959        if (newScrollX > right) {
17960            newScrollX = right;
17961            clampedX = true;
17962        } else if (newScrollX < left) {
17963            newScrollX = left;
17964            clampedX = true;
17965        }
17966
17967        boolean clampedY = false;
17968        if (newScrollY > bottom) {
17969            newScrollY = bottom;
17970            clampedY = true;
17971        } else if (newScrollY < top) {
17972            newScrollY = top;
17973            clampedY = true;
17974        }
17975
17976        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17977
17978        return clampedX || clampedY;
17979    }
17980
17981    /**
17982     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17983     * respond to the results of an over-scroll operation.
17984     *
17985     * @param scrollX New X scroll value in pixels
17986     * @param scrollY New Y scroll value in pixels
17987     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17988     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17989     */
17990    protected void onOverScrolled(int scrollX, int scrollY,
17991            boolean clampedX, boolean clampedY) {
17992        // Intentionally empty.
17993    }
17994
17995    /**
17996     * Returns the over-scroll mode for this view. The result will be
17997     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17998     * (allow over-scrolling only if the view content is larger than the container),
17999     * or {@link #OVER_SCROLL_NEVER}.
18000     *
18001     * @return This view's over-scroll mode.
18002     */
18003    public int getOverScrollMode() {
18004        return mOverScrollMode;
18005    }
18006
18007    /**
18008     * Set the over-scroll mode for this view. Valid over-scroll modes are
18009     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18010     * (allow over-scrolling only if the view content is larger than the container),
18011     * or {@link #OVER_SCROLL_NEVER}.
18012     *
18013     * Setting the over-scroll mode of a view will have an effect only if the
18014     * view is capable of scrolling.
18015     *
18016     * @param overScrollMode The new over-scroll mode for this view.
18017     */
18018    public void setOverScrollMode(int overScrollMode) {
18019        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18020                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18021                overScrollMode != OVER_SCROLL_NEVER) {
18022            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18023        }
18024        mOverScrollMode = overScrollMode;
18025    }
18026
18027    /**
18028     * Enable or disable nested scrolling for this view.
18029     *
18030     * <p>If this property is set to true the view will be permitted to initiate nested
18031     * scrolling operations with a compatible parent view in the current hierarchy. If this
18032     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18033     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18034     * the nested scroll.</p>
18035     *
18036     * @param enabled true to enable nested scrolling, false to disable
18037     *
18038     * @see #isNestedScrollingEnabled()
18039     */
18040    public void setNestedScrollingEnabled(boolean enabled) {
18041        if (enabled) {
18042            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18043        } else {
18044            stopNestedScroll();
18045            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18046        }
18047    }
18048
18049    /**
18050     * Returns true if nested scrolling is enabled for this view.
18051     *
18052     * <p>If nested scrolling is enabled and this View class implementation supports it,
18053     * this view will act as a nested scrolling child view when applicable, forwarding data
18054     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18055     * parent.</p>
18056     *
18057     * @return true if nested scrolling is enabled
18058     *
18059     * @see #setNestedScrollingEnabled(boolean)
18060     */
18061    public boolean isNestedScrollingEnabled() {
18062        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18063                PFLAG3_NESTED_SCROLLING_ENABLED;
18064    }
18065
18066    /**
18067     * Begin a nestable scroll operation along the given axes.
18068     *
18069     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18070     *
18071     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18072     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18073     * In the case of touch scrolling the nested scroll will be terminated automatically in
18074     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18075     * In the event of programmatic scrolling the caller must explicitly call
18076     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18077     *
18078     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18079     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18080     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18081     *
18082     * <p>At each incremental step of the scroll the caller should invoke
18083     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18084     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18085     * parent at least partially consumed the scroll and the caller should adjust the amount it
18086     * scrolls by.</p>
18087     *
18088     * <p>After applying the remainder of the scroll delta the caller should invoke
18089     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18090     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18091     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18092     * </p>
18093     *
18094     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18095     *             {@link #SCROLL_AXIS_VERTICAL}.
18096     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18097     *         the current gesture.
18098     *
18099     * @see #stopNestedScroll()
18100     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18101     * @see #dispatchNestedScroll(int, int, int, int, int[])
18102     */
18103    public boolean startNestedScroll(int axes) {
18104        if (hasNestedScrollingParent()) {
18105            // Already in progress
18106            return true;
18107        }
18108        if (isNestedScrollingEnabled()) {
18109            ViewParent p = getParent();
18110            View child = this;
18111            while (p != null) {
18112                try {
18113                    if (p.onStartNestedScroll(child, this, axes)) {
18114                        mNestedScrollingParent = p;
18115                        p.onNestedScrollAccepted(child, this, axes);
18116                        return true;
18117                    }
18118                } catch (AbstractMethodError e) {
18119                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18120                            "method onStartNestedScroll", e);
18121                    // Allow the search upward to continue
18122                }
18123                if (p instanceof View) {
18124                    child = (View) p;
18125                }
18126                p = p.getParent();
18127            }
18128        }
18129        return false;
18130    }
18131
18132    /**
18133     * Stop a nested scroll in progress.
18134     *
18135     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18136     *
18137     * @see #startNestedScroll(int)
18138     */
18139    public void stopNestedScroll() {
18140        if (mNestedScrollingParent != null) {
18141            mNestedScrollingParent.onStopNestedScroll(this);
18142            mNestedScrollingParent = null;
18143        }
18144    }
18145
18146    /**
18147     * Returns true if this view has a nested scrolling parent.
18148     *
18149     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18150     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18151     *
18152     * @return whether this view has a nested scrolling parent
18153     */
18154    public boolean hasNestedScrollingParent() {
18155        return mNestedScrollingParent != null;
18156    }
18157
18158    /**
18159     * Dispatch one step of a nested scroll in progress.
18160     *
18161     * <p>Implementations of views that support nested scrolling should call this to report
18162     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18163     * is not currently in progress or nested scrolling is not
18164     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18165     *
18166     * <p>Compatible View implementations should also call
18167     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18168     * consuming a component of the scroll event themselves.</p>
18169     *
18170     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18171     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18172     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18173     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18174     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18175     *                       in local view coordinates of this view from before this operation
18176     *                       to after it completes. View implementations may use this to adjust
18177     *                       expected input coordinate tracking.
18178     * @return true if the event was dispatched, false if it could not be dispatched.
18179     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18180     */
18181    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18182            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18183        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18184            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18185                int startX = 0;
18186                int startY = 0;
18187                if (offsetInWindow != null) {
18188                    getLocationInWindow(offsetInWindow);
18189                    startX = offsetInWindow[0];
18190                    startY = offsetInWindow[1];
18191                }
18192
18193                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18194                        dxUnconsumed, dyUnconsumed);
18195
18196                if (offsetInWindow != null) {
18197                    getLocationInWindow(offsetInWindow);
18198                    offsetInWindow[0] -= startX;
18199                    offsetInWindow[1] -= startY;
18200                }
18201                return true;
18202            } else if (offsetInWindow != null) {
18203                // No motion, no dispatch. Keep offsetInWindow up to date.
18204                offsetInWindow[0] = 0;
18205                offsetInWindow[1] = 0;
18206            }
18207        }
18208        return false;
18209    }
18210
18211    /**
18212     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18213     *
18214     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18215     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18216     * scrolling operation to consume some or all of the scroll operation before the child view
18217     * consumes it.</p>
18218     *
18219     * @param dx Horizontal scroll distance in pixels
18220     * @param dy Vertical scroll distance in pixels
18221     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18222     *                 and consumed[1] the consumed dy.
18223     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18224     *                       in local view coordinates of this view from before this operation
18225     *                       to after it completes. View implementations may use this to adjust
18226     *                       expected input coordinate tracking.
18227     * @return true if the parent consumed some or all of the scroll delta
18228     * @see #dispatchNestedScroll(int, int, int, int, int[])
18229     */
18230    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18231        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18232            if (dx != 0 || dy != 0) {
18233                int startX = 0;
18234                int startY = 0;
18235                if (offsetInWindow != null) {
18236                    getLocationInWindow(offsetInWindow);
18237                    startX = offsetInWindow[0];
18238                    startY = offsetInWindow[1];
18239                }
18240
18241                if (consumed == null) {
18242                    if (mTempNestedScrollConsumed == null) {
18243                        mTempNestedScrollConsumed = new int[2];
18244                    }
18245                    consumed = mTempNestedScrollConsumed;
18246                }
18247                consumed[0] = 0;
18248                consumed[1] = 0;
18249                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18250
18251                if (offsetInWindow != null) {
18252                    getLocationInWindow(offsetInWindow);
18253                    offsetInWindow[0] -= startX;
18254                    offsetInWindow[1] -= startY;
18255                }
18256                return consumed[0] != 0 || consumed[1] != 0;
18257            } else if (offsetInWindow != null) {
18258                offsetInWindow[0] = 0;
18259                offsetInWindow[1] = 0;
18260            }
18261        }
18262        return false;
18263    }
18264
18265    /**
18266     * Dispatch a fling to a nested scrolling parent.
18267     *
18268     * <p>This method should be used to indicate that a nested scrolling child has detected
18269     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18270     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18271     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18272     * along a scrollable axis.</p>
18273     *
18274     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18275     * its own content, it can use this method to delegate the fling to its nested scrolling
18276     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18277     *
18278     * @param velocityX Horizontal fling velocity in pixels per second
18279     * @param velocityY Vertical fling velocity in pixels per second
18280     * @param consumed true if the child consumed the fling, false otherwise
18281     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18282     */
18283    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18284        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18285            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18286        }
18287        return false;
18288    }
18289
18290    /**
18291     * Gets a scale factor that determines the distance the view should scroll
18292     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18293     * @return The vertical scroll scale factor.
18294     * @hide
18295     */
18296    protected float getVerticalScrollFactor() {
18297        if (mVerticalScrollFactor == 0) {
18298            TypedValue outValue = new TypedValue();
18299            if (!mContext.getTheme().resolveAttribute(
18300                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18301                throw new IllegalStateException(
18302                        "Expected theme to define listPreferredItemHeight.");
18303            }
18304            mVerticalScrollFactor = outValue.getDimension(
18305                    mContext.getResources().getDisplayMetrics());
18306        }
18307        return mVerticalScrollFactor;
18308    }
18309
18310    /**
18311     * Gets a scale factor that determines the distance the view should scroll
18312     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18313     * @return The horizontal scroll scale factor.
18314     * @hide
18315     */
18316    protected float getHorizontalScrollFactor() {
18317        // TODO: Should use something else.
18318        return getVerticalScrollFactor();
18319    }
18320
18321    /**
18322     * Return the value specifying the text direction or policy that was set with
18323     * {@link #setTextDirection(int)}.
18324     *
18325     * @return the defined text direction. It can be one of:
18326     *
18327     * {@link #TEXT_DIRECTION_INHERIT},
18328     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18329     * {@link #TEXT_DIRECTION_ANY_RTL},
18330     * {@link #TEXT_DIRECTION_LTR},
18331     * {@link #TEXT_DIRECTION_RTL},
18332     * {@link #TEXT_DIRECTION_LOCALE}
18333     *
18334     * @attr ref android.R.styleable#View_textDirection
18335     *
18336     * @hide
18337     */
18338    @ViewDebug.ExportedProperty(category = "text", mapping = {
18339            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18340            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18341            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18342            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18343            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18344            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18345    })
18346    public int getRawTextDirection() {
18347        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18348    }
18349
18350    /**
18351     * Set the text direction.
18352     *
18353     * @param textDirection the direction to set. Should be one of:
18354     *
18355     * {@link #TEXT_DIRECTION_INHERIT},
18356     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18357     * {@link #TEXT_DIRECTION_ANY_RTL},
18358     * {@link #TEXT_DIRECTION_LTR},
18359     * {@link #TEXT_DIRECTION_RTL},
18360     * {@link #TEXT_DIRECTION_LOCALE}
18361     *
18362     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18363     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18364     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18365     *
18366     * @attr ref android.R.styleable#View_textDirection
18367     */
18368    public void setTextDirection(int textDirection) {
18369        if (getRawTextDirection() != textDirection) {
18370            // Reset the current text direction and the resolved one
18371            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18372            resetResolvedTextDirection();
18373            // Set the new text direction
18374            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18375            // Do resolution
18376            resolveTextDirection();
18377            // Notify change
18378            onRtlPropertiesChanged(getLayoutDirection());
18379            // Refresh
18380            requestLayout();
18381            invalidate(true);
18382        }
18383    }
18384
18385    /**
18386     * Return the resolved text direction.
18387     *
18388     * @return the resolved text direction. Returns one of:
18389     *
18390     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18391     * {@link #TEXT_DIRECTION_ANY_RTL},
18392     * {@link #TEXT_DIRECTION_LTR},
18393     * {@link #TEXT_DIRECTION_RTL},
18394     * {@link #TEXT_DIRECTION_LOCALE}
18395     *
18396     * @attr ref android.R.styleable#View_textDirection
18397     */
18398    @ViewDebug.ExportedProperty(category = "text", mapping = {
18399            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18400            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18401            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18402            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18403            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18404            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18405    })
18406    public int getTextDirection() {
18407        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18408    }
18409
18410    /**
18411     * Resolve the text direction.
18412     *
18413     * @return true if resolution has been done, false otherwise.
18414     *
18415     * @hide
18416     */
18417    public boolean resolveTextDirection() {
18418        // Reset any previous text direction resolution
18419        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18420
18421        if (hasRtlSupport()) {
18422            // Set resolved text direction flag depending on text direction flag
18423            final int textDirection = getRawTextDirection();
18424            switch(textDirection) {
18425                case TEXT_DIRECTION_INHERIT:
18426                    if (!canResolveTextDirection()) {
18427                        // We cannot do the resolution if there is no parent, so use the default one
18428                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18429                        // Resolution will need to happen again later
18430                        return false;
18431                    }
18432
18433                    // Parent has not yet resolved, so we still return the default
18434                    try {
18435                        if (!mParent.isTextDirectionResolved()) {
18436                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18437                            // Resolution will need to happen again later
18438                            return false;
18439                        }
18440                    } catch (AbstractMethodError e) {
18441                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18442                                " does not fully implement ViewParent", e);
18443                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18444                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18445                        return true;
18446                    }
18447
18448                    // Set current resolved direction to the same value as the parent's one
18449                    int parentResolvedDirection;
18450                    try {
18451                        parentResolvedDirection = mParent.getTextDirection();
18452                    } catch (AbstractMethodError e) {
18453                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18454                                " does not fully implement ViewParent", e);
18455                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18456                    }
18457                    switch (parentResolvedDirection) {
18458                        case TEXT_DIRECTION_FIRST_STRONG:
18459                        case TEXT_DIRECTION_ANY_RTL:
18460                        case TEXT_DIRECTION_LTR:
18461                        case TEXT_DIRECTION_RTL:
18462                        case TEXT_DIRECTION_LOCALE:
18463                            mPrivateFlags2 |=
18464                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18465                            break;
18466                        default:
18467                            // Default resolved direction is "first strong" heuristic
18468                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18469                    }
18470                    break;
18471                case TEXT_DIRECTION_FIRST_STRONG:
18472                case TEXT_DIRECTION_ANY_RTL:
18473                case TEXT_DIRECTION_LTR:
18474                case TEXT_DIRECTION_RTL:
18475                case TEXT_DIRECTION_LOCALE:
18476                    // Resolved direction is the same as text direction
18477                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18478                    break;
18479                default:
18480                    // Default resolved direction is "first strong" heuristic
18481                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18482            }
18483        } else {
18484            // Default resolved direction is "first strong" heuristic
18485            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18486        }
18487
18488        // Set to resolved
18489        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18490        return true;
18491    }
18492
18493    /**
18494     * Check if text direction resolution can be done.
18495     *
18496     * @return true if text direction resolution can be done otherwise return false.
18497     */
18498    public boolean canResolveTextDirection() {
18499        switch (getRawTextDirection()) {
18500            case TEXT_DIRECTION_INHERIT:
18501                if (mParent != null) {
18502                    try {
18503                        return mParent.canResolveTextDirection();
18504                    } catch (AbstractMethodError e) {
18505                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18506                                " does not fully implement ViewParent", e);
18507                    }
18508                }
18509                return false;
18510
18511            default:
18512                return true;
18513        }
18514    }
18515
18516    /**
18517     * Reset resolved text direction. Text direction will be resolved during a call to
18518     * {@link #onMeasure(int, int)}.
18519     *
18520     * @hide
18521     */
18522    public void resetResolvedTextDirection() {
18523        // Reset any previous text direction resolution
18524        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18525        // Set to default value
18526        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18527    }
18528
18529    /**
18530     * @return true if text direction is inherited.
18531     *
18532     * @hide
18533     */
18534    public boolean isTextDirectionInherited() {
18535        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18536    }
18537
18538    /**
18539     * @return true if text direction is resolved.
18540     */
18541    public boolean isTextDirectionResolved() {
18542        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18543    }
18544
18545    /**
18546     * Return the value specifying the text alignment or policy that was set with
18547     * {@link #setTextAlignment(int)}.
18548     *
18549     * @return the defined text alignment. It can be one of:
18550     *
18551     * {@link #TEXT_ALIGNMENT_INHERIT},
18552     * {@link #TEXT_ALIGNMENT_GRAVITY},
18553     * {@link #TEXT_ALIGNMENT_CENTER},
18554     * {@link #TEXT_ALIGNMENT_TEXT_START},
18555     * {@link #TEXT_ALIGNMENT_TEXT_END},
18556     * {@link #TEXT_ALIGNMENT_VIEW_START},
18557     * {@link #TEXT_ALIGNMENT_VIEW_END}
18558     *
18559     * @attr ref android.R.styleable#View_textAlignment
18560     *
18561     * @hide
18562     */
18563    @ViewDebug.ExportedProperty(category = "text", mapping = {
18564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18566            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18568            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18569            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18570            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18571    })
18572    @TextAlignment
18573    public int getRawTextAlignment() {
18574        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18575    }
18576
18577    /**
18578     * Set the text alignment.
18579     *
18580     * @param textAlignment The text alignment to set. Should be one of
18581     *
18582     * {@link #TEXT_ALIGNMENT_INHERIT},
18583     * {@link #TEXT_ALIGNMENT_GRAVITY},
18584     * {@link #TEXT_ALIGNMENT_CENTER},
18585     * {@link #TEXT_ALIGNMENT_TEXT_START},
18586     * {@link #TEXT_ALIGNMENT_TEXT_END},
18587     * {@link #TEXT_ALIGNMENT_VIEW_START},
18588     * {@link #TEXT_ALIGNMENT_VIEW_END}
18589     *
18590     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18591     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18592     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18593     *
18594     * @attr ref android.R.styleable#View_textAlignment
18595     */
18596    public void setTextAlignment(@TextAlignment int textAlignment) {
18597        if (textAlignment != getRawTextAlignment()) {
18598            // Reset the current and resolved text alignment
18599            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18600            resetResolvedTextAlignment();
18601            // Set the new text alignment
18602            mPrivateFlags2 |=
18603                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18604            // Do resolution
18605            resolveTextAlignment();
18606            // Notify change
18607            onRtlPropertiesChanged(getLayoutDirection());
18608            // Refresh
18609            requestLayout();
18610            invalidate(true);
18611        }
18612    }
18613
18614    /**
18615     * Return the resolved text alignment.
18616     *
18617     * @return the resolved text alignment. Returns one of:
18618     *
18619     * {@link #TEXT_ALIGNMENT_GRAVITY},
18620     * {@link #TEXT_ALIGNMENT_CENTER},
18621     * {@link #TEXT_ALIGNMENT_TEXT_START},
18622     * {@link #TEXT_ALIGNMENT_TEXT_END},
18623     * {@link #TEXT_ALIGNMENT_VIEW_START},
18624     * {@link #TEXT_ALIGNMENT_VIEW_END}
18625     *
18626     * @attr ref android.R.styleable#View_textAlignment
18627     */
18628    @ViewDebug.ExportedProperty(category = "text", mapping = {
18629            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18630            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18631            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18632            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18633            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18634            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18635            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18636    })
18637    @TextAlignment
18638    public int getTextAlignment() {
18639        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18640                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18641    }
18642
18643    /**
18644     * Resolve the text alignment.
18645     *
18646     * @return true if resolution has been done, false otherwise.
18647     *
18648     * @hide
18649     */
18650    public boolean resolveTextAlignment() {
18651        // Reset any previous text alignment resolution
18652        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18653
18654        if (hasRtlSupport()) {
18655            // Set resolved text alignment flag depending on text alignment flag
18656            final int textAlignment = getRawTextAlignment();
18657            switch (textAlignment) {
18658                case TEXT_ALIGNMENT_INHERIT:
18659                    // Check if we can resolve the text alignment
18660                    if (!canResolveTextAlignment()) {
18661                        // We cannot do the resolution if there is no parent so use the default
18662                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18663                        // Resolution will need to happen again later
18664                        return false;
18665                    }
18666
18667                    // Parent has not yet resolved, so we still return the default
18668                    try {
18669                        if (!mParent.isTextAlignmentResolved()) {
18670                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18671                            // Resolution will need to happen again later
18672                            return false;
18673                        }
18674                    } catch (AbstractMethodError e) {
18675                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18676                                " does not fully implement ViewParent", e);
18677                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18678                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18679                        return true;
18680                    }
18681
18682                    int parentResolvedTextAlignment;
18683                    try {
18684                        parentResolvedTextAlignment = mParent.getTextAlignment();
18685                    } catch (AbstractMethodError e) {
18686                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18687                                " does not fully implement ViewParent", e);
18688                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18689                    }
18690                    switch (parentResolvedTextAlignment) {
18691                        case TEXT_ALIGNMENT_GRAVITY:
18692                        case TEXT_ALIGNMENT_TEXT_START:
18693                        case TEXT_ALIGNMENT_TEXT_END:
18694                        case TEXT_ALIGNMENT_CENTER:
18695                        case TEXT_ALIGNMENT_VIEW_START:
18696                        case TEXT_ALIGNMENT_VIEW_END:
18697                            // Resolved text alignment is the same as the parent resolved
18698                            // text alignment
18699                            mPrivateFlags2 |=
18700                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18701                            break;
18702                        default:
18703                            // Use default resolved text alignment
18704                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18705                    }
18706                    break;
18707                case TEXT_ALIGNMENT_GRAVITY:
18708                case TEXT_ALIGNMENT_TEXT_START:
18709                case TEXT_ALIGNMENT_TEXT_END:
18710                case TEXT_ALIGNMENT_CENTER:
18711                case TEXT_ALIGNMENT_VIEW_START:
18712                case TEXT_ALIGNMENT_VIEW_END:
18713                    // Resolved text alignment is the same as text alignment
18714                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18715                    break;
18716                default:
18717                    // Use default resolved text alignment
18718                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18719            }
18720        } else {
18721            // Use default resolved text alignment
18722            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18723        }
18724
18725        // Set the resolved
18726        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18727        return true;
18728    }
18729
18730    /**
18731     * Check if text alignment resolution can be done.
18732     *
18733     * @return true if text alignment resolution can be done otherwise return false.
18734     */
18735    public boolean canResolveTextAlignment() {
18736        switch (getRawTextAlignment()) {
18737            case TEXT_DIRECTION_INHERIT:
18738                if (mParent != null) {
18739                    try {
18740                        return mParent.canResolveTextAlignment();
18741                    } catch (AbstractMethodError e) {
18742                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18743                                " does not fully implement ViewParent", e);
18744                    }
18745                }
18746                return false;
18747
18748            default:
18749                return true;
18750        }
18751    }
18752
18753    /**
18754     * Reset resolved text alignment. Text alignment will be resolved during a call to
18755     * {@link #onMeasure(int, int)}.
18756     *
18757     * @hide
18758     */
18759    public void resetResolvedTextAlignment() {
18760        // Reset any previous text alignment resolution
18761        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18762        // Set to default
18763        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18764    }
18765
18766    /**
18767     * @return true if text alignment is inherited.
18768     *
18769     * @hide
18770     */
18771    public boolean isTextAlignmentInherited() {
18772        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18773    }
18774
18775    /**
18776     * @return true if text alignment is resolved.
18777     */
18778    public boolean isTextAlignmentResolved() {
18779        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18780    }
18781
18782    /**
18783     * Generate a value suitable for use in {@link #setId(int)}.
18784     * This value will not collide with ID values generated at build time by aapt for R.id.
18785     *
18786     * @return a generated ID value
18787     */
18788    public static int generateViewId() {
18789        for (;;) {
18790            final int result = sNextGeneratedId.get();
18791            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18792            int newValue = result + 1;
18793            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18794            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18795                return result;
18796            }
18797        }
18798    }
18799
18800    /**
18801     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18802     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18803     *                           a normal View or a ViewGroup with
18804     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18805     * @hide
18806     */
18807    public void captureTransitioningViews(List<View> transitioningViews) {
18808        if (getVisibility() == View.VISIBLE) {
18809            transitioningViews.add(this);
18810        }
18811    }
18812
18813    /**
18814     * Adds all Views that have {@link #getViewName()} non-null to namedElements.
18815     * @param namedElements Will contain all Views in the hierarchy having a view name.
18816     * @hide
18817     */
18818    public void findNamedViews(Map<String, View> namedElements) {
18819        if (getVisibility() == VISIBLE) {
18820            String viewName = getViewName();
18821            if (viewName != null) {
18822                namedElements.put(viewName, this);
18823            }
18824        }
18825    }
18826
18827    //
18828    // Properties
18829    //
18830    /**
18831     * A Property wrapper around the <code>alpha</code> functionality handled by the
18832     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18833     */
18834    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18835        @Override
18836        public void setValue(View object, float value) {
18837            object.setAlpha(value);
18838        }
18839
18840        @Override
18841        public Float get(View object) {
18842            return object.getAlpha();
18843        }
18844    };
18845
18846    /**
18847     * A Property wrapper around the <code>translationX</code> functionality handled by the
18848     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18849     */
18850    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18851        @Override
18852        public void setValue(View object, float value) {
18853            object.setTranslationX(value);
18854        }
18855
18856                @Override
18857        public Float get(View object) {
18858            return object.getTranslationX();
18859        }
18860    };
18861
18862    /**
18863     * A Property wrapper around the <code>translationY</code> functionality handled by the
18864     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18865     */
18866    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18867        @Override
18868        public void setValue(View object, float value) {
18869            object.setTranslationY(value);
18870        }
18871
18872        @Override
18873        public Float get(View object) {
18874            return object.getTranslationY();
18875        }
18876    };
18877
18878    /**
18879     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18880     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18881     */
18882    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18883        @Override
18884        public void setValue(View object, float value) {
18885            object.setTranslationZ(value);
18886        }
18887
18888        @Override
18889        public Float get(View object) {
18890            return object.getTranslationZ();
18891        }
18892    };
18893
18894    /**
18895     * A Property wrapper around the <code>x</code> functionality handled by the
18896     * {@link View#setX(float)} and {@link View#getX()} methods.
18897     */
18898    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18899        @Override
18900        public void setValue(View object, float value) {
18901            object.setX(value);
18902        }
18903
18904        @Override
18905        public Float get(View object) {
18906            return object.getX();
18907        }
18908    };
18909
18910    /**
18911     * A Property wrapper around the <code>y</code> functionality handled by the
18912     * {@link View#setY(float)} and {@link View#getY()} methods.
18913     */
18914    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18915        @Override
18916        public void setValue(View object, float value) {
18917            object.setY(value);
18918        }
18919
18920        @Override
18921        public Float get(View object) {
18922            return object.getY();
18923        }
18924    };
18925
18926    /**
18927     * A Property wrapper around the <code>z</code> functionality handled by the
18928     * {@link View#setZ(float)} and {@link View#getZ()} methods.
18929     */
18930    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
18931        @Override
18932        public void setValue(View object, float value) {
18933            object.setZ(value);
18934        }
18935
18936        @Override
18937        public Float get(View object) {
18938            return object.getZ();
18939        }
18940    };
18941
18942    /**
18943     * A Property wrapper around the <code>rotation</code> functionality handled by the
18944     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18945     */
18946    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18947        @Override
18948        public void setValue(View object, float value) {
18949            object.setRotation(value);
18950        }
18951
18952        @Override
18953        public Float get(View object) {
18954            return object.getRotation();
18955        }
18956    };
18957
18958    /**
18959     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18960     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18961     */
18962    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18963        @Override
18964        public void setValue(View object, float value) {
18965            object.setRotationX(value);
18966        }
18967
18968        @Override
18969        public Float get(View object) {
18970            return object.getRotationX();
18971        }
18972    };
18973
18974    /**
18975     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18976     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18977     */
18978    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18979        @Override
18980        public void setValue(View object, float value) {
18981            object.setRotationY(value);
18982        }
18983
18984        @Override
18985        public Float get(View object) {
18986            return object.getRotationY();
18987        }
18988    };
18989
18990    /**
18991     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18992     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18993     */
18994    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18995        @Override
18996        public void setValue(View object, float value) {
18997            object.setScaleX(value);
18998        }
18999
19000        @Override
19001        public Float get(View object) {
19002            return object.getScaleX();
19003        }
19004    };
19005
19006    /**
19007     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19008     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19009     */
19010    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19011        @Override
19012        public void setValue(View object, float value) {
19013            object.setScaleY(value);
19014        }
19015
19016        @Override
19017        public Float get(View object) {
19018            return object.getScaleY();
19019        }
19020    };
19021
19022    /**
19023     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19024     * Each MeasureSpec represents a requirement for either the width or the height.
19025     * A MeasureSpec is comprised of a size and a mode. There are three possible
19026     * modes:
19027     * <dl>
19028     * <dt>UNSPECIFIED</dt>
19029     * <dd>
19030     * The parent has not imposed any constraint on the child. It can be whatever size
19031     * it wants.
19032     * </dd>
19033     *
19034     * <dt>EXACTLY</dt>
19035     * <dd>
19036     * The parent has determined an exact size for the child. The child is going to be
19037     * given those bounds regardless of how big it wants to be.
19038     * </dd>
19039     *
19040     * <dt>AT_MOST</dt>
19041     * <dd>
19042     * The child can be as large as it wants up to the specified size.
19043     * </dd>
19044     * </dl>
19045     *
19046     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19047     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19048     */
19049    public static class MeasureSpec {
19050        private static final int MODE_SHIFT = 30;
19051        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19052
19053        /**
19054         * Measure specification mode: The parent has not imposed any constraint
19055         * on the child. It can be whatever size it wants.
19056         */
19057        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19058
19059        /**
19060         * Measure specification mode: The parent has determined an exact size
19061         * for the child. The child is going to be given those bounds regardless
19062         * of how big it wants to be.
19063         */
19064        public static final int EXACTLY     = 1 << MODE_SHIFT;
19065
19066        /**
19067         * Measure specification mode: The child can be as large as it wants up
19068         * to the specified size.
19069         */
19070        public static final int AT_MOST     = 2 << MODE_SHIFT;
19071
19072        /**
19073         * Creates a measure specification based on the supplied size and mode.
19074         *
19075         * The mode must always be one of the following:
19076         * <ul>
19077         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19078         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19079         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19080         * </ul>
19081         *
19082         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19083         * implementation was such that the order of arguments did not matter
19084         * and overflow in either value could impact the resulting MeasureSpec.
19085         * {@link android.widget.RelativeLayout} was affected by this bug.
19086         * Apps targeting API levels greater than 17 will get the fixed, more strict
19087         * behavior.</p>
19088         *
19089         * @param size the size of the measure specification
19090         * @param mode the mode of the measure specification
19091         * @return the measure specification based on size and mode
19092         */
19093        public static int makeMeasureSpec(int size, int mode) {
19094            if (sUseBrokenMakeMeasureSpec) {
19095                return size + mode;
19096            } else {
19097                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19098            }
19099        }
19100
19101        /**
19102         * Extracts the mode from the supplied measure specification.
19103         *
19104         * @param measureSpec the measure specification to extract the mode from
19105         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19106         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19107         *         {@link android.view.View.MeasureSpec#EXACTLY}
19108         */
19109        public static int getMode(int measureSpec) {
19110            return (measureSpec & MODE_MASK);
19111        }
19112
19113        /**
19114         * Extracts the size from the supplied measure specification.
19115         *
19116         * @param measureSpec the measure specification to extract the size from
19117         * @return the size in pixels defined in the supplied measure specification
19118         */
19119        public static int getSize(int measureSpec) {
19120            return (measureSpec & ~MODE_MASK);
19121        }
19122
19123        static int adjust(int measureSpec, int delta) {
19124            final int mode = getMode(measureSpec);
19125            if (mode == UNSPECIFIED) {
19126                // No need to adjust size for UNSPECIFIED mode.
19127                return makeMeasureSpec(0, UNSPECIFIED);
19128            }
19129            int size = getSize(measureSpec) + delta;
19130            if (size < 0) {
19131                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19132                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19133                size = 0;
19134            }
19135            return makeMeasureSpec(size, mode);
19136        }
19137
19138        /**
19139         * Returns a String representation of the specified measure
19140         * specification.
19141         *
19142         * @param measureSpec the measure specification to convert to a String
19143         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19144         */
19145        public static String toString(int measureSpec) {
19146            int mode = getMode(measureSpec);
19147            int size = getSize(measureSpec);
19148
19149            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19150
19151            if (mode == UNSPECIFIED)
19152                sb.append("UNSPECIFIED ");
19153            else if (mode == EXACTLY)
19154                sb.append("EXACTLY ");
19155            else if (mode == AT_MOST)
19156                sb.append("AT_MOST ");
19157            else
19158                sb.append(mode).append(" ");
19159
19160            sb.append(size);
19161            return sb.toString();
19162        }
19163    }
19164
19165    private final class CheckForLongPress implements Runnable {
19166        private int mOriginalWindowAttachCount;
19167
19168        @Override
19169        public void run() {
19170            if (isPressed() && (mParent != null)
19171                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19172                if (performLongClick()) {
19173                    mHasPerformedLongPress = true;
19174                }
19175            }
19176        }
19177
19178        public void rememberWindowAttachCount() {
19179            mOriginalWindowAttachCount = mWindowAttachCount;
19180        }
19181    }
19182
19183    private final class CheckForTap implements Runnable {
19184        public float x;
19185        public float y;
19186
19187        @Override
19188        public void run() {
19189            mPrivateFlags &= ~PFLAG_PREPRESSED;
19190            setPressed(true, x, y);
19191            checkForLongClick(ViewConfiguration.getTapTimeout());
19192        }
19193    }
19194
19195    private final class PerformClick implements Runnable {
19196        @Override
19197        public void run() {
19198            performClick();
19199        }
19200    }
19201
19202    /** @hide */
19203    public void hackTurnOffWindowResizeAnim(boolean off) {
19204        mAttachInfo.mTurnOffWindowResizeAnim = off;
19205    }
19206
19207    /**
19208     * This method returns a ViewPropertyAnimator object, which can be used to animate
19209     * specific properties on this View.
19210     *
19211     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19212     */
19213    public ViewPropertyAnimator animate() {
19214        if (mAnimator == null) {
19215            mAnimator = new ViewPropertyAnimator(this);
19216        }
19217        return mAnimator;
19218    }
19219
19220    /**
19221     * Sets the name of the View to be used to identify Views in Transitions.
19222     * Names should be unique in the View hierarchy.
19223     *
19224     * @param viewName The name of the View to uniquely identify it for Transitions.
19225     */
19226    public final void setViewName(String viewName) {
19227        mViewName = viewName;
19228    }
19229
19230    /**
19231     * Returns the name of the View to be used to identify Views in Transitions.
19232     * Names should be unique in the View hierarchy.
19233     *
19234     * <p>This returns null if the View has not been given a name.</p>
19235     *
19236     * @return The name used of the View to be used to identify Views in Transitions or null
19237     * if no name has been given.
19238     */
19239    public String getViewName() {
19240        return mViewName;
19241    }
19242
19243    /**
19244     * Interface definition for a callback to be invoked when a hardware key event is
19245     * dispatched to this view. The callback will be invoked before the key event is
19246     * given to the view. This is only useful for hardware keyboards; a software input
19247     * method has no obligation to trigger this listener.
19248     */
19249    public interface OnKeyListener {
19250        /**
19251         * Called when a hardware key is dispatched to a view. This allows listeners to
19252         * get a chance to respond before the target view.
19253         * <p>Key presses in software keyboards will generally NOT trigger this method,
19254         * although some may elect to do so in some situations. Do not assume a
19255         * software input method has to be key-based; even if it is, it may use key presses
19256         * in a different way than you expect, so there is no way to reliably catch soft
19257         * input key presses.
19258         *
19259         * @param v The view the key has been dispatched to.
19260         * @param keyCode The code for the physical key that was pressed
19261         * @param event The KeyEvent object containing full information about
19262         *        the event.
19263         * @return True if the listener has consumed the event, false otherwise.
19264         */
19265        boolean onKey(View v, int keyCode, KeyEvent event);
19266    }
19267
19268    /**
19269     * Interface definition for a callback to be invoked when a touch event is
19270     * dispatched to this view. The callback will be invoked before the touch
19271     * event is given to the view.
19272     */
19273    public interface OnTouchListener {
19274        /**
19275         * Called when a touch event is dispatched to a view. This allows listeners to
19276         * get a chance to respond before the target view.
19277         *
19278         * @param v The view the touch event has been dispatched to.
19279         * @param event The MotionEvent object containing full information about
19280         *        the event.
19281         * @return True if the listener has consumed the event, false otherwise.
19282         */
19283        boolean onTouch(View v, MotionEvent event);
19284    }
19285
19286    /**
19287     * Interface definition for a callback to be invoked when a hover event is
19288     * dispatched to this view. The callback will be invoked before the hover
19289     * event is given to the view.
19290     */
19291    public interface OnHoverListener {
19292        /**
19293         * Called when a hover event is dispatched to a view. This allows listeners to
19294         * get a chance to respond before the target view.
19295         *
19296         * @param v The view the hover event has been dispatched to.
19297         * @param event The MotionEvent object containing full information about
19298         *        the event.
19299         * @return True if the listener has consumed the event, false otherwise.
19300         */
19301        boolean onHover(View v, MotionEvent event);
19302    }
19303
19304    /**
19305     * Interface definition for a callback to be invoked when a generic motion event is
19306     * dispatched to this view. The callback will be invoked before the generic motion
19307     * event is given to the view.
19308     */
19309    public interface OnGenericMotionListener {
19310        /**
19311         * Called when a generic motion event is dispatched to a view. This allows listeners to
19312         * get a chance to respond before the target view.
19313         *
19314         * @param v The view the generic motion event has been dispatched to.
19315         * @param event The MotionEvent object containing full information about
19316         *        the event.
19317         * @return True if the listener has consumed the event, false otherwise.
19318         */
19319        boolean onGenericMotion(View v, MotionEvent event);
19320    }
19321
19322    /**
19323     * Interface definition for a callback to be invoked when a view has been clicked and held.
19324     */
19325    public interface OnLongClickListener {
19326        /**
19327         * Called when a view has been clicked and held.
19328         *
19329         * @param v The view that was clicked and held.
19330         *
19331         * @return true if the callback consumed the long click, false otherwise.
19332         */
19333        boolean onLongClick(View v);
19334    }
19335
19336    /**
19337     * Interface definition for a callback to be invoked when a drag is being dispatched
19338     * to this view.  The callback will be invoked before the hosting view's own
19339     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19340     * onDrag(event) behavior, it should return 'false' from this callback.
19341     *
19342     * <div class="special reference">
19343     * <h3>Developer Guides</h3>
19344     * <p>For a guide to implementing drag and drop features, read the
19345     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19346     * </div>
19347     */
19348    public interface OnDragListener {
19349        /**
19350         * Called when a drag event is dispatched to a view. This allows listeners
19351         * to get a chance to override base View behavior.
19352         *
19353         * @param v The View that received the drag event.
19354         * @param event The {@link android.view.DragEvent} object for the drag event.
19355         * @return {@code true} if the drag event was handled successfully, or {@code false}
19356         * if the drag event was not handled. Note that {@code false} will trigger the View
19357         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19358         */
19359        boolean onDrag(View v, DragEvent event);
19360    }
19361
19362    /**
19363     * Interface definition for a callback to be invoked when the focus state of
19364     * a view changed.
19365     */
19366    public interface OnFocusChangeListener {
19367        /**
19368         * Called when the focus state of a view has changed.
19369         *
19370         * @param v The view whose state has changed.
19371         * @param hasFocus The new focus state of v.
19372         */
19373        void onFocusChange(View v, boolean hasFocus);
19374    }
19375
19376    /**
19377     * Interface definition for a callback to be invoked when a view is clicked.
19378     */
19379    public interface OnClickListener {
19380        /**
19381         * Called when a view has been clicked.
19382         *
19383         * @param v The view that was clicked.
19384         */
19385        void onClick(View v);
19386    }
19387
19388    /**
19389     * Interface definition for a callback to be invoked when the context menu
19390     * for this view is being built.
19391     */
19392    public interface OnCreateContextMenuListener {
19393        /**
19394         * Called when the context menu for this view is being built. It is not
19395         * safe to hold onto the menu after this method returns.
19396         *
19397         * @param menu The context menu that is being built
19398         * @param v The view for which the context menu is being built
19399         * @param menuInfo Extra information about the item for which the
19400         *            context menu should be shown. This information will vary
19401         *            depending on the class of v.
19402         */
19403        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19404    }
19405
19406    /**
19407     * Interface definition for a callback to be invoked when the status bar changes
19408     * visibility.  This reports <strong>global</strong> changes to the system UI
19409     * state, not what the application is requesting.
19410     *
19411     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19412     */
19413    public interface OnSystemUiVisibilityChangeListener {
19414        /**
19415         * Called when the status bar changes visibility because of a call to
19416         * {@link View#setSystemUiVisibility(int)}.
19417         *
19418         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19419         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19420         * This tells you the <strong>global</strong> state of these UI visibility
19421         * flags, not what your app is currently applying.
19422         */
19423        public void onSystemUiVisibilityChange(int visibility);
19424    }
19425
19426    /**
19427     * Interface definition for a callback to be invoked when this view is attached
19428     * or detached from its window.
19429     */
19430    public interface OnAttachStateChangeListener {
19431        /**
19432         * Called when the view is attached to a window.
19433         * @param v The view that was attached
19434         */
19435        public void onViewAttachedToWindow(View v);
19436        /**
19437         * Called when the view is detached from a window.
19438         * @param v The view that was detached
19439         */
19440        public void onViewDetachedFromWindow(View v);
19441    }
19442
19443    /**
19444     * Listener for applying window insets on a view in a custom way.
19445     *
19446     * <p>Apps may choose to implement this interface if they want to apply custom policy
19447     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19448     * is set, its
19449     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19450     * method will be called instead of the View's own
19451     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19452     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19453     * the View's normal behavior as part of its own.</p>
19454     */
19455    public interface OnApplyWindowInsetsListener {
19456        /**
19457         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19458         * on a View, this listener method will be called instead of the view's own
19459         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19460         *
19461         * @param v The view applying window insets
19462         * @param insets The insets to apply
19463         * @return The insets supplied, minus any insets that were consumed
19464         */
19465        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19466    }
19467
19468    private final class UnsetPressedState implements Runnable {
19469        @Override
19470        public void run() {
19471            setPressed(false);
19472        }
19473    }
19474
19475    /**
19476     * Base class for derived classes that want to save and restore their own
19477     * state in {@link android.view.View#onSaveInstanceState()}.
19478     */
19479    public static class BaseSavedState extends AbsSavedState {
19480        /**
19481         * Constructor used when reading from a parcel. Reads the state of the superclass.
19482         *
19483         * @param source
19484         */
19485        public BaseSavedState(Parcel source) {
19486            super(source);
19487        }
19488
19489        /**
19490         * Constructor called by derived classes when creating their SavedState objects
19491         *
19492         * @param superState The state of the superclass of this view
19493         */
19494        public BaseSavedState(Parcelable superState) {
19495            super(superState);
19496        }
19497
19498        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19499                new Parcelable.Creator<BaseSavedState>() {
19500            public BaseSavedState createFromParcel(Parcel in) {
19501                return new BaseSavedState(in);
19502            }
19503
19504            public BaseSavedState[] newArray(int size) {
19505                return new BaseSavedState[size];
19506            }
19507        };
19508    }
19509
19510    /**
19511     * A set of information given to a view when it is attached to its parent
19512     * window.
19513     */
19514    final static class AttachInfo {
19515        interface Callbacks {
19516            void playSoundEffect(int effectId);
19517            boolean performHapticFeedback(int effectId, boolean always);
19518        }
19519
19520        /**
19521         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19522         * to a Handler. This class contains the target (View) to invalidate and
19523         * the coordinates of the dirty rectangle.
19524         *
19525         * For performance purposes, this class also implements a pool of up to
19526         * POOL_LIMIT objects that get reused. This reduces memory allocations
19527         * whenever possible.
19528         */
19529        static class InvalidateInfo {
19530            private static final int POOL_LIMIT = 10;
19531
19532            private static final SynchronizedPool<InvalidateInfo> sPool =
19533                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19534
19535            View target;
19536
19537            int left;
19538            int top;
19539            int right;
19540            int bottom;
19541
19542            public static InvalidateInfo obtain() {
19543                InvalidateInfo instance = sPool.acquire();
19544                return (instance != null) ? instance : new InvalidateInfo();
19545            }
19546
19547            public void recycle() {
19548                target = null;
19549                sPool.release(this);
19550            }
19551        }
19552
19553        final IWindowSession mSession;
19554
19555        final IWindow mWindow;
19556
19557        final IBinder mWindowToken;
19558
19559        final Display mDisplay;
19560
19561        final Callbacks mRootCallbacks;
19562
19563        IWindowId mIWindowId;
19564        WindowId mWindowId;
19565
19566        /**
19567         * The top view of the hierarchy.
19568         */
19569        View mRootView;
19570
19571        IBinder mPanelParentWindowToken;
19572
19573        boolean mHardwareAccelerated;
19574        boolean mHardwareAccelerationRequested;
19575        HardwareRenderer mHardwareRenderer;
19576
19577        /**
19578         * The state of the display to which the window is attached, as reported
19579         * by {@link Display#getState()}.  Note that the display state constants
19580         * declared by {@link Display} do not exactly line up with the screen state
19581         * constants declared by {@link View} (there are more display states than
19582         * screen states).
19583         */
19584        int mDisplayState = Display.STATE_UNKNOWN;
19585
19586        /**
19587         * Scale factor used by the compatibility mode
19588         */
19589        float mApplicationScale;
19590
19591        /**
19592         * Indicates whether the application is in compatibility mode
19593         */
19594        boolean mScalingRequired;
19595
19596        /**
19597         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19598         */
19599        boolean mTurnOffWindowResizeAnim;
19600
19601        /**
19602         * Left position of this view's window
19603         */
19604        int mWindowLeft;
19605
19606        /**
19607         * Top position of this view's window
19608         */
19609        int mWindowTop;
19610
19611        /**
19612         * Indicates whether views need to use 32-bit drawing caches
19613         */
19614        boolean mUse32BitDrawingCache;
19615
19616        /**
19617         * For windows that are full-screen but using insets to layout inside
19618         * of the screen areas, these are the current insets to appear inside
19619         * the overscan area of the display.
19620         */
19621        final Rect mOverscanInsets = new Rect();
19622
19623        /**
19624         * For windows that are full-screen but using insets to layout inside
19625         * of the screen decorations, these are the current insets for the
19626         * content of the window.
19627         */
19628        final Rect mContentInsets = new Rect();
19629
19630        /**
19631         * For windows that are full-screen but using insets to layout inside
19632         * of the screen decorations, these are the current insets for the
19633         * actual visible parts of the window.
19634         */
19635        final Rect mVisibleInsets = new Rect();
19636
19637        /**
19638         * The internal insets given by this window.  This value is
19639         * supplied by the client (through
19640         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19641         * be given to the window manager when changed to be used in laying
19642         * out windows behind it.
19643         */
19644        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19645                = new ViewTreeObserver.InternalInsetsInfo();
19646
19647        /**
19648         * Set to true when mGivenInternalInsets is non-empty.
19649         */
19650        boolean mHasNonEmptyGivenInternalInsets;
19651
19652        /**
19653         * All views in the window's hierarchy that serve as scroll containers,
19654         * used to determine if the window can be resized or must be panned
19655         * to adjust for a soft input area.
19656         */
19657        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19658
19659        final KeyEvent.DispatcherState mKeyDispatchState
19660                = new KeyEvent.DispatcherState();
19661
19662        /**
19663         * Indicates whether the view's window currently has the focus.
19664         */
19665        boolean mHasWindowFocus;
19666
19667        /**
19668         * The current visibility of the window.
19669         */
19670        int mWindowVisibility;
19671
19672        /**
19673         * Indicates the time at which drawing started to occur.
19674         */
19675        long mDrawingTime;
19676
19677        /**
19678         * Indicates whether or not ignoring the DIRTY_MASK flags.
19679         */
19680        boolean mIgnoreDirtyState;
19681
19682        /**
19683         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19684         * to avoid clearing that flag prematurely.
19685         */
19686        boolean mSetIgnoreDirtyState = false;
19687
19688        /**
19689         * Indicates whether the view's window is currently in touch mode.
19690         */
19691        boolean mInTouchMode;
19692
19693        /**
19694         * Indicates whether the view has requested unbuffered input dispatching for the current
19695         * event stream.
19696         */
19697        boolean mUnbufferedDispatchRequested;
19698
19699        /**
19700         * Indicates that ViewAncestor should trigger a global layout change
19701         * the next time it performs a traversal
19702         */
19703        boolean mRecomputeGlobalAttributes;
19704
19705        /**
19706         * Always report new attributes at next traversal.
19707         */
19708        boolean mForceReportNewAttributes;
19709
19710        /**
19711         * Set during a traveral if any views want to keep the screen on.
19712         */
19713        boolean mKeepScreenOn;
19714
19715        /**
19716         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19717         */
19718        int mSystemUiVisibility;
19719
19720        /**
19721         * Hack to force certain system UI visibility flags to be cleared.
19722         */
19723        int mDisabledSystemUiVisibility;
19724
19725        /**
19726         * Last global system UI visibility reported by the window manager.
19727         */
19728        int mGlobalSystemUiVisibility;
19729
19730        /**
19731         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19732         * attached.
19733         */
19734        boolean mHasSystemUiListeners;
19735
19736        /**
19737         * Set if the window has requested to extend into the overscan region
19738         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19739         */
19740        boolean mOverscanRequested;
19741
19742        /**
19743         * Set if the visibility of any views has changed.
19744         */
19745        boolean mViewVisibilityChanged;
19746
19747        /**
19748         * Set to true if a view has been scrolled.
19749         */
19750        boolean mViewScrollChanged;
19751
19752        /**
19753         * Global to the view hierarchy used as a temporary for dealing with
19754         * x/y points in the transparent region computations.
19755         */
19756        final int[] mTransparentLocation = new int[2];
19757
19758        /**
19759         * Global to the view hierarchy used as a temporary for dealing with
19760         * x/y points in the ViewGroup.invalidateChild implementation.
19761         */
19762        final int[] mInvalidateChildLocation = new int[2];
19763
19764
19765        /**
19766         * Global to the view hierarchy used as a temporary for dealing with
19767         * x/y location when view is transformed.
19768         */
19769        final float[] mTmpTransformLocation = new float[2];
19770
19771        /**
19772         * The view tree observer used to dispatch global events like
19773         * layout, pre-draw, touch mode change, etc.
19774         */
19775        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19776
19777        /**
19778         * A Canvas used by the view hierarchy to perform bitmap caching.
19779         */
19780        Canvas mCanvas;
19781
19782        /**
19783         * The view root impl.
19784         */
19785        final ViewRootImpl mViewRootImpl;
19786
19787        /**
19788         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19789         * handler can be used to pump events in the UI events queue.
19790         */
19791        final Handler mHandler;
19792
19793        /**
19794         * Temporary for use in computing invalidate rectangles while
19795         * calling up the hierarchy.
19796         */
19797        final Rect mTmpInvalRect = new Rect();
19798
19799        /**
19800         * Temporary for use in computing hit areas with transformed views
19801         */
19802        final RectF mTmpTransformRect = new RectF();
19803
19804        /**
19805         * Temporary for use in transforming invalidation rect
19806         */
19807        final Matrix mTmpMatrix = new Matrix();
19808
19809        /**
19810         * Temporary for use in transforming invalidation rect
19811         */
19812        final Transformation mTmpTransformation = new Transformation();
19813
19814        /**
19815         * Temporary list for use in collecting focusable descendents of a view.
19816         */
19817        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19818
19819        /**
19820         * The id of the window for accessibility purposes.
19821         */
19822        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19823
19824        /**
19825         * Flags related to accessibility processing.
19826         *
19827         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19828         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19829         */
19830        int mAccessibilityFetchFlags;
19831
19832        /**
19833         * The drawable for highlighting accessibility focus.
19834         */
19835        Drawable mAccessibilityFocusDrawable;
19836
19837        /**
19838         * Show where the margins, bounds and layout bounds are for each view.
19839         */
19840        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19841
19842        /**
19843         * Point used to compute visible regions.
19844         */
19845        final Point mPoint = new Point();
19846
19847        /**
19848         * Used to track which View originated a requestLayout() call, used when
19849         * requestLayout() is called during layout.
19850         */
19851        View mViewRequestingLayout;
19852
19853        /**
19854         * Creates a new set of attachment information with the specified
19855         * events handler and thread.
19856         *
19857         * @param handler the events handler the view must use
19858         */
19859        AttachInfo(IWindowSession session, IWindow window, Display display,
19860                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19861            mSession = session;
19862            mWindow = window;
19863            mWindowToken = window.asBinder();
19864            mDisplay = display;
19865            mViewRootImpl = viewRootImpl;
19866            mHandler = handler;
19867            mRootCallbacks = effectPlayer;
19868        }
19869    }
19870
19871    /**
19872     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19873     * is supported. This avoids keeping too many unused fields in most
19874     * instances of View.</p>
19875     */
19876    private static class ScrollabilityCache implements Runnable {
19877
19878        /**
19879         * Scrollbars are not visible
19880         */
19881        public static final int OFF = 0;
19882
19883        /**
19884         * Scrollbars are visible
19885         */
19886        public static final int ON = 1;
19887
19888        /**
19889         * Scrollbars are fading away
19890         */
19891        public static final int FADING = 2;
19892
19893        public boolean fadeScrollBars;
19894
19895        public int fadingEdgeLength;
19896        public int scrollBarDefaultDelayBeforeFade;
19897        public int scrollBarFadeDuration;
19898
19899        public int scrollBarSize;
19900        public ScrollBarDrawable scrollBar;
19901        public float[] interpolatorValues;
19902        public View host;
19903
19904        public final Paint paint;
19905        public final Matrix matrix;
19906        public Shader shader;
19907
19908        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19909
19910        private static final float[] OPAQUE = { 255 };
19911        private static final float[] TRANSPARENT = { 0.0f };
19912
19913        /**
19914         * When fading should start. This time moves into the future every time
19915         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19916         */
19917        public long fadeStartTime;
19918
19919
19920        /**
19921         * The current state of the scrollbars: ON, OFF, or FADING
19922         */
19923        public int state = OFF;
19924
19925        private int mLastColor;
19926
19927        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19928            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19929            scrollBarSize = configuration.getScaledScrollBarSize();
19930            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19931            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19932
19933            paint = new Paint();
19934            matrix = new Matrix();
19935            // use use a height of 1, and then wack the matrix each time we
19936            // actually use it.
19937            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19938            paint.setShader(shader);
19939            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19940
19941            this.host = host;
19942        }
19943
19944        public void setFadeColor(int color) {
19945            if (color != mLastColor) {
19946                mLastColor = color;
19947
19948                if (color != 0) {
19949                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19950                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19951                    paint.setShader(shader);
19952                    // Restore the default transfer mode (src_over)
19953                    paint.setXfermode(null);
19954                } else {
19955                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19956                    paint.setShader(shader);
19957                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19958                }
19959            }
19960        }
19961
19962        public void run() {
19963            long now = AnimationUtils.currentAnimationTimeMillis();
19964            if (now >= fadeStartTime) {
19965
19966                // the animation fades the scrollbars out by changing
19967                // the opacity (alpha) from fully opaque to fully
19968                // transparent
19969                int nextFrame = (int) now;
19970                int framesCount = 0;
19971
19972                Interpolator interpolator = scrollBarInterpolator;
19973
19974                // Start opaque
19975                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19976
19977                // End transparent
19978                nextFrame += scrollBarFadeDuration;
19979                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19980
19981                state = FADING;
19982
19983                // Kick off the fade animation
19984                host.invalidate(true);
19985            }
19986        }
19987    }
19988
19989    /**
19990     * Resuable callback for sending
19991     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19992     */
19993    private class SendViewScrolledAccessibilityEvent implements Runnable {
19994        public volatile boolean mIsPending;
19995
19996        public void run() {
19997            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19998            mIsPending = false;
19999        }
20000    }
20001
20002    /**
20003     * <p>
20004     * This class represents a delegate that can be registered in a {@link View}
20005     * to enhance accessibility support via composition rather via inheritance.
20006     * It is specifically targeted to widget developers that extend basic View
20007     * classes i.e. classes in package android.view, that would like their
20008     * applications to be backwards compatible.
20009     * </p>
20010     * <div class="special reference">
20011     * <h3>Developer Guides</h3>
20012     * <p>For more information about making applications accessible, read the
20013     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20014     * developer guide.</p>
20015     * </div>
20016     * <p>
20017     * A scenario in which a developer would like to use an accessibility delegate
20018     * is overriding a method introduced in a later API version then the minimal API
20019     * version supported by the application. For example, the method
20020     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20021     * in API version 4 when the accessibility APIs were first introduced. If a
20022     * developer would like his application to run on API version 4 devices (assuming
20023     * all other APIs used by the application are version 4 or lower) and take advantage
20024     * of this method, instead of overriding the method which would break the application's
20025     * backwards compatibility, he can override the corresponding method in this
20026     * delegate and register the delegate in the target View if the API version of
20027     * the system is high enough i.e. the API version is same or higher to the API
20028     * version that introduced
20029     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20030     * </p>
20031     * <p>
20032     * Here is an example implementation:
20033     * </p>
20034     * <code><pre><p>
20035     * if (Build.VERSION.SDK_INT >= 14) {
20036     *     // If the API version is equal of higher than the version in
20037     *     // which onInitializeAccessibilityNodeInfo was introduced we
20038     *     // register a delegate with a customized implementation.
20039     *     View view = findViewById(R.id.view_id);
20040     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20041     *         public void onInitializeAccessibilityNodeInfo(View host,
20042     *                 AccessibilityNodeInfo info) {
20043     *             // Let the default implementation populate the info.
20044     *             super.onInitializeAccessibilityNodeInfo(host, info);
20045     *             // Set some other information.
20046     *             info.setEnabled(host.isEnabled());
20047     *         }
20048     *     });
20049     * }
20050     * </code></pre></p>
20051     * <p>
20052     * This delegate contains methods that correspond to the accessibility methods
20053     * in View. If a delegate has been specified the implementation in View hands
20054     * off handling to the corresponding method in this delegate. The default
20055     * implementation the delegate methods behaves exactly as the corresponding
20056     * method in View for the case of no accessibility delegate been set. Hence,
20057     * to customize the behavior of a View method, clients can override only the
20058     * corresponding delegate method without altering the behavior of the rest
20059     * accessibility related methods of the host view.
20060     * </p>
20061     */
20062    public static class AccessibilityDelegate {
20063
20064        /**
20065         * Sends an accessibility event of the given type. If accessibility is not
20066         * enabled this method has no effect.
20067         * <p>
20068         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20069         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20070         * been set.
20071         * </p>
20072         *
20073         * @param host The View hosting the delegate.
20074         * @param eventType The type of the event to send.
20075         *
20076         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20077         */
20078        public void sendAccessibilityEvent(View host, int eventType) {
20079            host.sendAccessibilityEventInternal(eventType);
20080        }
20081
20082        /**
20083         * Performs the specified accessibility action on the view. For
20084         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20085         * <p>
20086         * The default implementation behaves as
20087         * {@link View#performAccessibilityAction(int, Bundle)
20088         *  View#performAccessibilityAction(int, Bundle)} for the case of
20089         *  no accessibility delegate been set.
20090         * </p>
20091         *
20092         * @param action The action to perform.
20093         * @return Whether the action was performed.
20094         *
20095         * @see View#performAccessibilityAction(int, Bundle)
20096         *      View#performAccessibilityAction(int, Bundle)
20097         */
20098        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20099            return host.performAccessibilityActionInternal(action, args);
20100        }
20101
20102        /**
20103         * Sends an accessibility event. This method behaves exactly as
20104         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20105         * empty {@link AccessibilityEvent} and does not perform a check whether
20106         * accessibility is enabled.
20107         * <p>
20108         * The default implementation behaves as
20109         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20110         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20111         * the case of no accessibility delegate been set.
20112         * </p>
20113         *
20114         * @param host The View hosting the delegate.
20115         * @param event The event to send.
20116         *
20117         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20118         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20119         */
20120        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20121            host.sendAccessibilityEventUncheckedInternal(event);
20122        }
20123
20124        /**
20125         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20126         * to its children for adding their text content to the event.
20127         * <p>
20128         * The default implementation behaves as
20129         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20130         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20131         * the case of no accessibility delegate been set.
20132         * </p>
20133         *
20134         * @param host The View hosting the delegate.
20135         * @param event The event.
20136         * @return True if the event population was completed.
20137         *
20138         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20139         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20140         */
20141        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20142            return host.dispatchPopulateAccessibilityEventInternal(event);
20143        }
20144
20145        /**
20146         * Gives a chance to the host View to populate the accessibility event with its
20147         * text content.
20148         * <p>
20149         * The default implementation behaves as
20150         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20151         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20152         * the case of no accessibility delegate been set.
20153         * </p>
20154         *
20155         * @param host The View hosting the delegate.
20156         * @param event The accessibility event which to populate.
20157         *
20158         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20159         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20160         */
20161        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20162            host.onPopulateAccessibilityEventInternal(event);
20163        }
20164
20165        /**
20166         * Initializes an {@link AccessibilityEvent} with information about the
20167         * the host View which is the event source.
20168         * <p>
20169         * The default implementation behaves as
20170         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20171         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20172         * the case of no accessibility delegate been set.
20173         * </p>
20174         *
20175         * @param host The View hosting the delegate.
20176         * @param event The event to initialize.
20177         *
20178         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20179         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20180         */
20181        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20182            host.onInitializeAccessibilityEventInternal(event);
20183        }
20184
20185        /**
20186         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20187         * <p>
20188         * The default implementation behaves as
20189         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20190         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20191         * the case of no accessibility delegate been set.
20192         * </p>
20193         *
20194         * @param host The View hosting the delegate.
20195         * @param info The instance to initialize.
20196         *
20197         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20198         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20199         */
20200        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20201            host.onInitializeAccessibilityNodeInfoInternal(info);
20202        }
20203
20204        /**
20205         * Called when a child of the host View has requested sending an
20206         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20207         * to augment the event.
20208         * <p>
20209         * The default implementation behaves as
20210         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20211         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20212         * the case of no accessibility delegate been set.
20213         * </p>
20214         *
20215         * @param host The View hosting the delegate.
20216         * @param child The child which requests sending the event.
20217         * @param event The event to be sent.
20218         * @return True if the event should be sent
20219         *
20220         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20221         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20222         */
20223        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20224                AccessibilityEvent event) {
20225            return host.onRequestSendAccessibilityEventInternal(child, event);
20226        }
20227
20228        /**
20229         * Gets the provider for managing a virtual view hierarchy rooted at this View
20230         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20231         * that explore the window content.
20232         * <p>
20233         * The default implementation behaves as
20234         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20235         * the case of no accessibility delegate been set.
20236         * </p>
20237         *
20238         * @return The provider.
20239         *
20240         * @see AccessibilityNodeProvider
20241         */
20242        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20243            return null;
20244        }
20245
20246        /**
20247         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20248         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20249         * This method is responsible for obtaining an accessibility node info from a
20250         * pool of reusable instances and calling
20251         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20252         * view to initialize the former.
20253         * <p>
20254         * <strong>Note:</strong> The client is responsible for recycling the obtained
20255         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20256         * creation.
20257         * </p>
20258         * <p>
20259         * The default implementation behaves as
20260         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20261         * the case of no accessibility delegate been set.
20262         * </p>
20263         * @return A populated {@link AccessibilityNodeInfo}.
20264         *
20265         * @see AccessibilityNodeInfo
20266         *
20267         * @hide
20268         */
20269        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20270            return host.createAccessibilityNodeInfoInternal();
20271        }
20272    }
20273
20274    private class MatchIdPredicate implements Predicate<View> {
20275        public int mId;
20276
20277        @Override
20278        public boolean apply(View view) {
20279            return (view.mID == mId);
20280        }
20281    }
20282
20283    private class MatchLabelForPredicate implements Predicate<View> {
20284        private int mLabeledId;
20285
20286        @Override
20287        public boolean apply(View view) {
20288            return (view.mLabelForId == mLabeledId);
20289        }
20290    }
20291
20292    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20293        private int mChangeTypes = 0;
20294        private boolean mPosted;
20295        private boolean mPostedWithDelay;
20296        private long mLastEventTimeMillis;
20297
20298        @Override
20299        public void run() {
20300            mPosted = false;
20301            mPostedWithDelay = false;
20302            mLastEventTimeMillis = SystemClock.uptimeMillis();
20303            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20304                final AccessibilityEvent event = AccessibilityEvent.obtain();
20305                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20306                event.setContentChangeTypes(mChangeTypes);
20307                sendAccessibilityEventUnchecked(event);
20308            }
20309            mChangeTypes = 0;
20310        }
20311
20312        public void runOrPost(int changeType) {
20313            mChangeTypes |= changeType;
20314
20315            // If this is a live region or the child of a live region, collect
20316            // all events from this frame and send them on the next frame.
20317            if (inLiveRegion()) {
20318                // If we're already posted with a delay, remove that.
20319                if (mPostedWithDelay) {
20320                    removeCallbacks(this);
20321                    mPostedWithDelay = false;
20322                }
20323                // Only post if we're not already posted.
20324                if (!mPosted) {
20325                    post(this);
20326                    mPosted = true;
20327                }
20328                return;
20329            }
20330
20331            if (mPosted) {
20332                return;
20333            }
20334            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20335            final long minEventIntevalMillis =
20336                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20337            if (timeSinceLastMillis >= minEventIntevalMillis) {
20338                removeCallbacks(this);
20339                run();
20340            } else {
20341                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20342                mPosted = true;
20343                mPostedWithDelay = true;
20344            }
20345        }
20346    }
20347
20348    private boolean inLiveRegion() {
20349        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20350            return true;
20351        }
20352
20353        ViewParent parent = getParent();
20354        while (parent instanceof View) {
20355            if (((View) parent).getAccessibilityLiveRegion()
20356                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20357                return true;
20358            }
20359            parent = parent.getParent();
20360        }
20361
20362        return false;
20363    }
20364
20365    /**
20366     * Dump all private flags in readable format, useful for documentation and
20367     * sanity checking.
20368     */
20369    private static void dumpFlags() {
20370        final HashMap<String, String> found = Maps.newHashMap();
20371        try {
20372            for (Field field : View.class.getDeclaredFields()) {
20373                final int modifiers = field.getModifiers();
20374                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20375                    if (field.getType().equals(int.class)) {
20376                        final int value = field.getInt(null);
20377                        dumpFlag(found, field.getName(), value);
20378                    } else if (field.getType().equals(int[].class)) {
20379                        final int[] values = (int[]) field.get(null);
20380                        for (int i = 0; i < values.length; i++) {
20381                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20382                        }
20383                    }
20384                }
20385            }
20386        } catch (IllegalAccessException e) {
20387            throw new RuntimeException(e);
20388        }
20389
20390        final ArrayList<String> keys = Lists.newArrayList();
20391        keys.addAll(found.keySet());
20392        Collections.sort(keys);
20393        for (String key : keys) {
20394            Log.d(VIEW_LOG_TAG, found.get(key));
20395        }
20396    }
20397
20398    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20399        // Sort flags by prefix, then by bits, always keeping unique keys
20400        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20401        final int prefix = name.indexOf('_');
20402        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20403        final String output = bits + " " + name;
20404        found.put(key, output);
20405    }
20406}
20407