View.java revision e7fad2fa90c1e5935a33ceff6980cc04a42323e2
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.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.Path;
39import android.graphics.PathMeasure;
40import android.graphics.PixelFormat;
41import android.graphics.Point;
42import android.graphics.PorterDuff;
43import android.graphics.PorterDuffXfermode;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.ColorDrawable;
49import android.graphics.drawable.Drawable;
50import android.hardware.display.DisplayManagerGlobal;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.RemoteException;
57import android.os.SystemClock;
58import android.os.SystemProperties;
59import android.os.Trace;
60import android.text.TextUtils;
61import android.util.AttributeSet;
62import android.util.FloatProperty;
63import android.util.LayoutDirection;
64import android.util.Log;
65import android.util.LongSparseLongArray;
66import android.util.Pools.SynchronizedPool;
67import android.util.Property;
68import android.util.SparseArray;
69import android.util.StateSet;
70import android.util.SuperNotCalledException;
71import android.util.TypedValue;
72import android.view.ContextMenu.ContextMenuInfo;
73import android.view.AccessibilityIterators.TextSegmentIterator;
74import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
75import android.view.AccessibilityIterators.WordTextSegmentIterator;
76import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
77import android.view.accessibility.AccessibilityEvent;
78import android.view.accessibility.AccessibilityEventSource;
79import android.view.accessibility.AccessibilityManager;
80import android.view.accessibility.AccessibilityNodeInfo;
81import android.view.accessibility.AccessibilityNodeProvider;
82import android.view.animation.Animation;
83import android.view.animation.AnimationUtils;
84import android.view.animation.Transformation;
85import android.view.inputmethod.EditorInfo;
86import android.view.inputmethod.InputConnection;
87import android.view.inputmethod.InputMethodManager;
88import android.widget.ScrollBarDrawable;
89
90import static android.os.Build.VERSION_CODES.*;
91import static java.lang.Math.max;
92
93import com.android.internal.R;
94import com.android.internal.util.Predicate;
95import com.android.internal.view.menu.MenuBuilder;
96import com.google.android.collect.Lists;
97import com.google.android.collect.Maps;
98
99import java.lang.annotation.Retention;
100import java.lang.annotation.RetentionPolicy;
101import java.lang.ref.WeakReference;
102import java.lang.reflect.Field;
103import java.lang.reflect.InvocationTargetException;
104import java.lang.reflect.Method;
105import java.lang.reflect.Modifier;
106import java.util.ArrayList;
107import java.util.Arrays;
108import java.util.Collections;
109import java.util.HashMap;
110import java.util.List;
111import java.util.Locale;
112import java.util.Map;
113import java.util.concurrent.CopyOnWriteArrayList;
114import java.util.concurrent.atomic.AtomicInteger;
115
116/**
117 * <p>
118 * This class represents the basic building block for user interface components. A View
119 * occupies a rectangular area on the screen and is responsible for drawing and
120 * event handling. View is the base class for <em>widgets</em>, which are
121 * used to create interactive UI components (buttons, text fields, etc.). The
122 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
123 * are invisible containers that hold other Views (or other ViewGroups) and define
124 * their layout properties.
125 * </p>
126 *
127 * <div class="special reference">
128 * <h3>Developer Guides</h3>
129 * <p>For information about using this class to develop your application's user interface,
130 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
131 * </div>
132 *
133 * <a name="Using"></a>
134 * <h3>Using Views</h3>
135 * <p>
136 * All of the views in a window are arranged in a single tree. You can add views
137 * either from code or by specifying a tree of views in one or more XML layout
138 * files. There are many specialized subclasses of views that act as controls or
139 * are capable of displaying text, images, or other content.
140 * </p>
141 * <p>
142 * Once you have created a tree of views, there are typically a few types of
143 * common operations you may wish to perform:
144 * <ul>
145 * <li><strong>Set properties:</strong> for example setting the text of a
146 * {@link android.widget.TextView}. The available properties and the methods
147 * that set them will vary among the different subclasses of views. Note that
148 * properties that are known at build time can be set in the XML layout
149 * files.</li>
150 * <li><strong>Set focus:</strong> The framework will handled moving focus in
151 * response to user input. To force focus to a specific view, call
152 * {@link #requestFocus}.</li>
153 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
154 * that will be notified when something interesting happens to the view. For
155 * example, all views will let you set a listener to be notified when the view
156 * gains or loses focus. You can register such a listener using
157 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
158 * Other view subclasses offer more specialized listeners. For example, a Button
159 * exposes a listener to notify clients when the button is clicked.</li>
160 * <li><strong>Set visibility:</strong> You can hide or show views using
161 * {@link #setVisibility(int)}.</li>
162 * </ul>
163 * </p>
164 * <p><em>
165 * Note: The Android framework is responsible for measuring, laying out and
166 * drawing views. You should not call methods that perform these actions on
167 * views yourself unless you are actually implementing a
168 * {@link android.view.ViewGroup}.
169 * </em></p>
170 *
171 * <a name="Lifecycle"></a>
172 * <h3>Implementing a Custom View</h3>
173 *
174 * <p>
175 * To implement a custom view, you will usually begin by providing overrides for
176 * some of the standard methods that the framework calls on all views. You do
177 * not need to override all of these methods. In fact, you can start by just
178 * overriding {@link #onDraw(android.graphics.Canvas)}.
179 * <table border="2" width="85%" align="center" cellpadding="5">
180 *     <thead>
181 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
182 *     </thead>
183 *
184 *     <tbody>
185 *     <tr>
186 *         <td rowspan="2">Creation</td>
187 *         <td>Constructors</td>
188 *         <td>There is a form of the constructor that are called when the view
189 *         is created from code and a form that is called when the view is
190 *         inflated from a layout file. The second form should parse and apply
191 *         any attributes defined in the layout file.
192 *         </td>
193 *     </tr>
194 *     <tr>
195 *         <td><code>{@link #onFinishInflate()}</code></td>
196 *         <td>Called after a view and all of its children has been inflated
197 *         from XML.</td>
198 *     </tr>
199 *
200 *     <tr>
201 *         <td rowspan="3">Layout</td>
202 *         <td><code>{@link #onMeasure(int, int)}</code></td>
203 *         <td>Called to determine the size requirements for this view and all
204 *         of its children.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
209 *         <td>Called when this view should assign a size and position to all
210 *         of its children.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
215 *         <td>Called when the size of this view has changed.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td>Drawing</td>
221 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
222 *         <td>Called when the view should render its content.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="4">Event processing</td>
228 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
229 *         <td>Called when a new hardware key event occurs.
230 *         </td>
231 *     </tr>
232 *     <tr>
233 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
234 *         <td>Called when a hardware key up event occurs.
235 *         </td>
236 *     </tr>
237 *     <tr>
238 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
239 *         <td>Called when a trackball motion event occurs.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
244 *         <td>Called when a touch screen motion event occurs.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td rowspan="2">Focus</td>
250 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
251 *         <td>Called when the view gains or loses focus.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
257 *         <td>Called when the window containing the view gains or loses focus.
258 *         </td>
259 *     </tr>
260 *
261 *     <tr>
262 *         <td rowspan="3">Attaching</td>
263 *         <td><code>{@link #onAttachedToWindow()}</code></td>
264 *         <td>Called when the view is attached to a window.
265 *         </td>
266 *     </tr>
267 *
268 *     <tr>
269 *         <td><code>{@link #onDetachedFromWindow}</code></td>
270 *         <td>Called when the view is detached from its window.
271 *         </td>
272 *     </tr>
273 *
274 *     <tr>
275 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
276 *         <td>Called when the visibility of the window containing the view
277 *         has changed.
278 *         </td>
279 *     </tr>
280 *     </tbody>
281 *
282 * </table>
283 * </p>
284 *
285 * <a name="IDs"></a>
286 * <h3>IDs</h3>
287 * Views may have an integer id associated with them. These ids are typically
288 * assigned in the layout XML files, and are used to find specific views within
289 * the view tree. A common pattern is to:
290 * <ul>
291 * <li>Define a Button in the layout file and assign it a unique ID.
292 * <pre>
293 * &lt;Button
294 *     android:id="@+id/my_button"
295 *     android:layout_width="wrap_content"
296 *     android:layout_height="wrap_content"
297 *     android:text="@string/my_button_text"/&gt;
298 * </pre></li>
299 * <li>From the onCreate method of an Activity, find the Button
300 * <pre class="prettyprint">
301 *      Button myButton = (Button) findViewById(R.id.my_button);
302 * </pre></li>
303 * </ul>
304 * <p>
305 * View IDs need not be unique throughout the tree, but it is good practice to
306 * ensure that they are at least unique within the part of the tree you are
307 * searching.
308 * </p>
309 *
310 * <a name="Position"></a>
311 * <h3>Position</h3>
312 * <p>
313 * The geometry of a view is that of a rectangle. A view has a location,
314 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
315 * two dimensions, expressed as a width and a height. The unit for location
316 * and dimensions is the pixel.
317 * </p>
318 *
319 * <p>
320 * It is possible to retrieve the location of a view by invoking the methods
321 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
322 * coordinate of the rectangle representing the view. The latter returns the
323 * top, or Y, coordinate of the rectangle representing the view. These methods
324 * both return the location of the view relative to its parent. For instance,
325 * when getLeft() returns 20, that means the view is located 20 pixels to the
326 * right of the left edge of its direct parent.
327 * </p>
328 *
329 * <p>
330 * In addition, several convenience methods are offered to avoid unnecessary
331 * computations, namely {@link #getRight()} and {@link #getBottom()}.
332 * These methods return the coordinates of the right and bottom edges of the
333 * rectangle representing the view. For instance, calling {@link #getRight()}
334 * is similar to the following computation: <code>getLeft() + getWidth()</code>
335 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
336 * </p>
337 *
338 * <a name="SizePaddingMargins"></a>
339 * <h3>Size, padding and margins</h3>
340 * <p>
341 * The size of a view is expressed with a width and a height. A view actually
342 * possess two pairs of width and height values.
343 * </p>
344 *
345 * <p>
346 * The first pair is known as <em>measured width</em> and
347 * <em>measured height</em>. These dimensions define how big a view wants to be
348 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
349 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
350 * and {@link #getMeasuredHeight()}.
351 * </p>
352 *
353 * <p>
354 * The second pair is simply known as <em>width</em> and <em>height</em>, or
355 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
356 * dimensions define the actual size of the view on screen, at drawing time and
357 * after layout. These values may, but do not have to, be different from the
358 * measured width and height. The width and height can be obtained by calling
359 * {@link #getWidth()} and {@link #getHeight()}.
360 * </p>
361 *
362 * <p>
363 * To measure its dimensions, a view takes into account its padding. The padding
364 * is expressed in pixels for the left, top, right and bottom parts of the view.
365 * Padding can be used to offset the content of the view by a specific amount of
366 * pixels. For instance, a left padding of 2 will push the view's content by
367 * 2 pixels to the right of the left edge. Padding can be set using the
368 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
369 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
370 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
371 * {@link #getPaddingEnd()}.
372 * </p>
373 *
374 * <p>
375 * Even though a view can define a padding, it does not provide any support for
376 * margins. However, view groups provide such a support. Refer to
377 * {@link android.view.ViewGroup} and
378 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
379 * </p>
380 *
381 * <a name="Layout"></a>
382 * <h3>Layout</h3>
383 * <p>
384 * Layout is a two pass process: a measure pass and a layout pass. The measuring
385 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
386 * of the view tree. Each view pushes dimension specifications down the tree
387 * during the recursion. At the end of the measure pass, every view has stored
388 * its measurements. The second pass happens in
389 * {@link #layout(int,int,int,int)} and is also top-down. During
390 * this pass each parent is responsible for positioning all of its children
391 * using the sizes computed in the measure pass.
392 * </p>
393 *
394 * <p>
395 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
396 * {@link #getMeasuredHeight()} values must be set, along with those for all of
397 * that view's descendants. A view's measured width and measured height values
398 * must respect the constraints imposed by the view's parents. This guarantees
399 * that at the end of the measure pass, all parents accept all of their
400 * children's measurements. A parent view may call measure() more than once on
401 * its children. For example, the parent may measure each child once with
402 * unspecified dimensions to find out how big they want to be, then call
403 * measure() on them again with actual numbers if the sum of all the children's
404 * unconstrained sizes is too big or too small.
405 * </p>
406 *
407 * <p>
408 * The measure pass uses two classes to communicate dimensions. The
409 * {@link MeasureSpec} class is used by views to tell their parents how they
410 * want to be measured and positioned. The base LayoutParams class just
411 * describes how big the view wants to be for both width and height. For each
412 * dimension, it can specify one of:
413 * <ul>
414 * <li> an exact number
415 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
416 * (minus padding)
417 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
418 * enclose its content (plus padding).
419 * </ul>
420 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
421 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
422 * an X and Y value.
423 * </p>
424 *
425 * <p>
426 * MeasureSpecs are used to push requirements down the tree from parent to
427 * child. A MeasureSpec can be in one of three modes:
428 * <ul>
429 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
430 * of a child view. For example, a LinearLayout may call measure() on its child
431 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
432 * tall the child view wants to be given a width of 240 pixels.
433 * <li>EXACTLY: This is used by the parent to impose an exact size on the
434 * child. The child must use this size, and guarantee that all of its
435 * descendants will fit within this size.
436 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
437 * child. The child must guarantee that it and all of its descendants will fit
438 * within this size.
439 * </ul>
440 * </p>
441 *
442 * <p>
443 * To initiate a layout, call {@link #requestLayout}. This method is typically
444 * called by a view on itself when it believes that is can no longer fit within
445 * its current bounds.
446 * </p>
447 *
448 * <a name="Drawing"></a>
449 * <h3>Drawing</h3>
450 * <p>
451 * Drawing is handled by walking the tree and recording the drawing commands of
452 * any View that needs to update. After this, the drawing commands of the
453 * entire tree are issued to screen, clipped to the newly damaged area.
454 * </p>
455 *
456 * <p>
457 * The tree is largely recorded and drawn in order, with parents drawn before
458 * (i.e., behind) their children, with siblings drawn in the order they appear
459 * in the tree. If you set a background drawable for a View, then the View will
460 * draw it before calling back to its <code>onDraw()</code> method. The child
461 * drawing order can be overridden with
462 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
463 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
464 * </p>
465 *
466 * <p>
467 * To force a view to draw, call {@link #invalidate()}.
468 * </p>
469 *
470 * <a name="EventHandlingThreading"></a>
471 * <h3>Event Handling and Threading</h3>
472 * <p>
473 * The basic cycle of a view is as follows:
474 * <ol>
475 * <li>An event comes in and is dispatched to the appropriate view. The view
476 * handles the event and notifies any listeners.</li>
477 * <li>If in the course of processing the event, the view's bounds may need
478 * to be changed, the view will call {@link #requestLayout()}.</li>
479 * <li>Similarly, if in the course of processing the event the view's appearance
480 * may need to be changed, the view will call {@link #invalidate()}.</li>
481 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
482 * the framework will take care of measuring, laying out, and drawing the tree
483 * as appropriate.</li>
484 * </ol>
485 * </p>
486 *
487 * <p><em>Note: The entire view tree is single threaded. You must always be on
488 * the UI thread when calling any method on any view.</em>
489 * If you are doing work on other threads and want to update the state of a view
490 * from that thread, you should use a {@link Handler}.
491 * </p>
492 *
493 * <a name="FocusHandling"></a>
494 * <h3>Focus Handling</h3>
495 * <p>
496 * The framework will handle routine focus movement in response to user input.
497 * This includes changing the focus as views are removed or hidden, or as new
498 * views become available. Views indicate their willingness to take focus
499 * through the {@link #isFocusable} method. To change whether a view can take
500 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
501 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
502 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
503 * </p>
504 * <p>
505 * Focus movement is based on an algorithm which finds the nearest neighbor in a
506 * given direction. In rare cases, the default algorithm may not match the
507 * intended behavior of the developer. In these situations, you can provide
508 * explicit overrides by using these XML attributes in the layout file:
509 * <pre>
510 * nextFocusDown
511 * nextFocusLeft
512 * nextFocusRight
513 * nextFocusUp
514 * </pre>
515 * </p>
516 *
517 *
518 * <p>
519 * To get a particular view to take focus, call {@link #requestFocus()}.
520 * </p>
521 *
522 * <a name="TouchMode"></a>
523 * <h3>Touch Mode</h3>
524 * <p>
525 * When a user is navigating a user interface via directional keys such as a D-pad, it is
526 * necessary to give focus to actionable items such as buttons so the user can see
527 * what will take input.  If the device has touch capabilities, however, and the user
528 * begins interacting with the interface by touching it, it is no longer necessary to
529 * always highlight, or give focus to, a particular view.  This motivates a mode
530 * for interaction named 'touch mode'.
531 * </p>
532 * <p>
533 * For a touch capable device, once the user touches the screen, the device
534 * will enter touch mode.  From this point onward, only views for which
535 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
536 * Other views that are touchable, like buttons, will not take focus when touched; they will
537 * only fire the on click listeners.
538 * </p>
539 * <p>
540 * Any time a user hits a directional key, such as a D-pad direction, the view device will
541 * exit touch mode, and find a view to take focus, so that the user may resume interacting
542 * with the user interface without touching the screen again.
543 * </p>
544 * <p>
545 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
546 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
547 * </p>
548 *
549 * <a name="Scrolling"></a>
550 * <h3>Scrolling</h3>
551 * <p>
552 * The framework provides basic support for views that wish to internally
553 * scroll their content. This includes keeping track of the X and Y scroll
554 * offset as well as mechanisms for drawing scrollbars. See
555 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
556 * {@link #awakenScrollBars()} for more details.
557 * </p>
558 *
559 * <a name="Tags"></a>
560 * <h3>Tags</h3>
561 * <p>
562 * Unlike IDs, tags are not used to identify views. Tags are essentially an
563 * extra piece of information that can be associated with a view. They are most
564 * often used as a convenience to store data related to views in the views
565 * themselves rather than by putting them in a separate structure.
566 * </p>
567 *
568 * <a name="Properties"></a>
569 * <h3>Properties</h3>
570 * <p>
571 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
572 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
573 * available both in the {@link Property} form as well as in similarly-named setter/getter
574 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
575 * be used to set persistent state associated with these rendering-related properties on the view.
576 * The properties and methods can also be used in conjunction with
577 * {@link android.animation.Animator Animator}-based animations, described more in the
578 * <a href="#Animation">Animation</a> section.
579 * </p>
580 *
581 * <a name="Animation"></a>
582 * <h3>Animation</h3>
583 * <p>
584 * Starting with Android 3.0, the preferred way of animating views is to use the
585 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
586 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
587 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
588 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
589 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
590 * makes animating these View properties particularly easy and efficient.
591 * </p>
592 * <p>
593 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
594 * You can attach an {@link Animation} object to a view using
595 * {@link #setAnimation(Animation)} or
596 * {@link #startAnimation(Animation)}. The animation can alter the scale,
597 * rotation, translation and alpha of a view over time. If the animation is
598 * attached to a view that has children, the animation will affect the entire
599 * subtree rooted by that node. When an animation is started, the framework will
600 * take care of redrawing the appropriate views until the animation completes.
601 * </p>
602 *
603 * <a name="Security"></a>
604 * <h3>Security</h3>
605 * <p>
606 * Sometimes it is essential that an application be able to verify that an action
607 * is being performed with the full knowledge and consent of the user, such as
608 * granting a permission request, making a purchase or clicking on an advertisement.
609 * Unfortunately, a malicious application could try to spoof the user into
610 * performing these actions, unaware, by concealing the intended purpose of the view.
611 * As a remedy, the framework offers a touch filtering mechanism that can be used to
612 * improve the security of views that provide access to sensitive functionality.
613 * </p><p>
614 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
615 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
616 * will discard touches that are received whenever the view's window is obscured by
617 * another visible window.  As a result, the view will not receive touches whenever a
618 * toast, dialog or other window appears above the view's window.
619 * </p><p>
620 * For more fine-grained control over security, consider overriding the
621 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
622 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
623 * </p>
624 *
625 * @attr ref android.R.styleable#View_alpha
626 * @attr ref android.R.styleable#View_background
627 * @attr ref android.R.styleable#View_clickable
628 * @attr ref android.R.styleable#View_contentDescription
629 * @attr ref android.R.styleable#View_drawingCacheQuality
630 * @attr ref android.R.styleable#View_duplicateParentState
631 * @attr ref android.R.styleable#View_id
632 * @attr ref android.R.styleable#View_requiresFadingEdge
633 * @attr ref android.R.styleable#View_fadeScrollbars
634 * @attr ref android.R.styleable#View_fadingEdgeLength
635 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
636 * @attr ref android.R.styleable#View_fitsSystemWindows
637 * @attr ref android.R.styleable#View_isScrollContainer
638 * @attr ref android.R.styleable#View_focusable
639 * @attr ref android.R.styleable#View_focusableInTouchMode
640 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
641 * @attr ref android.R.styleable#View_keepScreenOn
642 * @attr ref android.R.styleable#View_layerType
643 * @attr ref android.R.styleable#View_layoutDirection
644 * @attr ref android.R.styleable#View_longClickable
645 * @attr ref android.R.styleable#View_minHeight
646 * @attr ref android.R.styleable#View_minWidth
647 * @attr ref android.R.styleable#View_nextFocusDown
648 * @attr ref android.R.styleable#View_nextFocusLeft
649 * @attr ref android.R.styleable#View_nextFocusRight
650 * @attr ref android.R.styleable#View_nextFocusUp
651 * @attr ref android.R.styleable#View_onClick
652 * @attr ref android.R.styleable#View_padding
653 * @attr ref android.R.styleable#View_paddingBottom
654 * @attr ref android.R.styleable#View_paddingLeft
655 * @attr ref android.R.styleable#View_paddingRight
656 * @attr ref android.R.styleable#View_paddingTop
657 * @attr ref android.R.styleable#View_paddingStart
658 * @attr ref android.R.styleable#View_paddingEnd
659 * @attr ref android.R.styleable#View_saveEnabled
660 * @attr ref android.R.styleable#View_rotation
661 * @attr ref android.R.styleable#View_rotationX
662 * @attr ref android.R.styleable#View_rotationY
663 * @attr ref android.R.styleable#View_scaleX
664 * @attr ref android.R.styleable#View_scaleY
665 * @attr ref android.R.styleable#View_scrollX
666 * @attr ref android.R.styleable#View_scrollY
667 * @attr ref android.R.styleable#View_scrollbarSize
668 * @attr ref android.R.styleable#View_scrollbarStyle
669 * @attr ref android.R.styleable#View_scrollbars
670 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
671 * @attr ref android.R.styleable#View_scrollbarFadeDuration
672 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
673 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
674 * @attr ref android.R.styleable#View_scrollbarThumbVertical
675 * @attr ref android.R.styleable#View_scrollbarTrackVertical
676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
677 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
678 * @attr ref android.R.styleable#View_stateListAnimator
679 * @attr ref android.R.styleable#View_transitionName
680 * @attr ref android.R.styleable#View_soundEffectsEnabled
681 * @attr ref android.R.styleable#View_tag
682 * @attr ref android.R.styleable#View_textAlignment
683 * @attr ref android.R.styleable#View_textDirection
684 * @attr ref android.R.styleable#View_transformPivotX
685 * @attr ref android.R.styleable#View_transformPivotY
686 * @attr ref android.R.styleable#View_translationX
687 * @attr ref android.R.styleable#View_translationY
688 * @attr ref android.R.styleable#View_translationZ
689 * @attr ref android.R.styleable#View_visibility
690 *
691 * @see android.view.ViewGroup
692 */
693public class View implements Drawable.Callback, KeyEvent.Callback,
694        AccessibilityEventSource {
695    private static final boolean DBG = false;
696
697    /**
698     * The logging tag used by this class with android.util.Log.
699     */
700    protected static final String VIEW_LOG_TAG = "View";
701
702    /**
703     * When set to true, apps will draw debugging information about their layouts.
704     *
705     * @hide
706     */
707    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
708
709    /**
710     * When set to true, this view will save its attribute data.
711     *
712     * @hide
713     */
714    public static boolean mDebugViewAttributes = false;
715
716    /**
717     * Used to mark a View that has no ID.
718     */
719    public static final int NO_ID = -1;
720
721    /**
722     * Signals that compatibility booleans have been initialized according to
723     * target SDK versions.
724     */
725    private static boolean sCompatibilityDone = false;
726
727    /**
728     * Use the old (broken) way of building MeasureSpecs.
729     */
730    private static boolean sUseBrokenMakeMeasureSpec = false;
731
732    /**
733     * Ignore any optimizations using the measure cache.
734     */
735    private static boolean sIgnoreMeasureCache = false;
736
737    /**
738     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
739     * calling setFlags.
740     */
741    private static final int NOT_FOCUSABLE = 0x00000000;
742
743    /**
744     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
745     * setFlags.
746     */
747    private static final int FOCUSABLE = 0x00000001;
748
749    /**
750     * Mask for use with setFlags indicating bits used for focus.
751     */
752    private static final int FOCUSABLE_MASK = 0x00000001;
753
754    /**
755     * This view will adjust its padding to fit sytem windows (e.g. status bar)
756     */
757    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
758
759    /** @hide */
760    @IntDef({VISIBLE, INVISIBLE, GONE})
761    @Retention(RetentionPolicy.SOURCE)
762    public @interface Visibility {}
763
764    /**
765     * This view is visible.
766     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
767     * android:visibility}.
768     */
769    public static final int VISIBLE = 0x00000000;
770
771    /**
772     * This view is invisible, but it still takes up space for layout purposes.
773     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
774     * android:visibility}.
775     */
776    public static final int INVISIBLE = 0x00000004;
777
778    /**
779     * This view is invisible, and it doesn't take any space for layout
780     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
781     * android:visibility}.
782     */
783    public static final int GONE = 0x00000008;
784
785    /**
786     * Mask for use with setFlags indicating bits used for visibility.
787     * {@hide}
788     */
789    static final int VISIBILITY_MASK = 0x0000000C;
790
791    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
792
793    /**
794     * This view is enabled. Interpretation varies by subclass.
795     * Use with ENABLED_MASK when calling setFlags.
796     * {@hide}
797     */
798    static final int ENABLED = 0x00000000;
799
800    /**
801     * This view is disabled. Interpretation varies by subclass.
802     * Use with ENABLED_MASK when calling setFlags.
803     * {@hide}
804     */
805    static final int DISABLED = 0x00000020;
806
807   /**
808    * Mask for use with setFlags indicating bits used for indicating whether
809    * this view is enabled
810    * {@hide}
811    */
812    static final int ENABLED_MASK = 0x00000020;
813
814    /**
815     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
816     * called and further optimizations will be performed. It is okay to have
817     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
818     * {@hide}
819     */
820    static final int WILL_NOT_DRAW = 0x00000080;
821
822    /**
823     * Mask for use with setFlags indicating bits used for indicating whether
824     * this view is will draw
825     * {@hide}
826     */
827    static final int DRAW_MASK = 0x00000080;
828
829    /**
830     * <p>This view doesn't show scrollbars.</p>
831     * {@hide}
832     */
833    static final int SCROLLBARS_NONE = 0x00000000;
834
835    /**
836     * <p>This view shows horizontal scrollbars.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
840
841    /**
842     * <p>This view shows vertical scrollbars.</p>
843     * {@hide}
844     */
845    static final int SCROLLBARS_VERTICAL = 0x00000200;
846
847    /**
848     * <p>Mask for use with setFlags indicating bits used for indicating which
849     * scrollbars are enabled.</p>
850     * {@hide}
851     */
852    static final int SCROLLBARS_MASK = 0x00000300;
853
854    /**
855     * Indicates that the view should filter touches when its window is obscured.
856     * Refer to the class comments for more information about this security feature.
857     * {@hide}
858     */
859    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
860
861    /**
862     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
863     * that they are optional and should be skipped if the window has
864     * requested system UI flags that ignore those insets for layout.
865     */
866    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
867
868    /**
869     * <p>This view doesn't show fading edges.</p>
870     * {@hide}
871     */
872    static final int FADING_EDGE_NONE = 0x00000000;
873
874    /**
875     * <p>This view shows horizontal fading edges.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
879
880    /**
881     * <p>This view shows vertical fading edges.</p>
882     * {@hide}
883     */
884    static final int FADING_EDGE_VERTICAL = 0x00002000;
885
886    /**
887     * <p>Mask for use with setFlags indicating bits used for indicating which
888     * fading edges are enabled.</p>
889     * {@hide}
890     */
891    static final int FADING_EDGE_MASK = 0x00003000;
892
893    /**
894     * <p>Indicates this view can be clicked. When clickable, a View reacts
895     * to clicks by notifying the OnClickListener.<p>
896     * {@hide}
897     */
898    static final int CLICKABLE = 0x00004000;
899
900    /**
901     * <p>Indicates this view is caching its drawing into a bitmap.</p>
902     * {@hide}
903     */
904    static final int DRAWING_CACHE_ENABLED = 0x00008000;
905
906    /**
907     * <p>Indicates that no icicle should be saved for this view.<p>
908     * {@hide}
909     */
910    static final int SAVE_DISABLED = 0x000010000;
911
912    /**
913     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
914     * property.</p>
915     * {@hide}
916     */
917    static final int SAVE_DISABLED_MASK = 0x000010000;
918
919    /**
920     * <p>Indicates that no drawing cache should ever be created for this view.<p>
921     * {@hide}
922     */
923    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
924
925    /**
926     * <p>Indicates this view can take / keep focus when int touch mode.</p>
927     * {@hide}
928     */
929    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
930
931    /** @hide */
932    @Retention(RetentionPolicy.SOURCE)
933    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
934    public @interface DrawingCacheQuality {}
935
936    /**
937     * <p>Enables low quality mode for the drawing cache.</p>
938     */
939    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
940
941    /**
942     * <p>Enables high quality mode for the drawing cache.</p>
943     */
944    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
945
946    /**
947     * <p>Enables automatic quality mode for the drawing cache.</p>
948     */
949    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
950
951    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
952            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
953    };
954
955    /**
956     * <p>Mask for use with setFlags indicating bits used for the cache
957     * quality property.</p>
958     * {@hide}
959     */
960    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
961
962    /**
963     * <p>
964     * Indicates this view can be long clicked. When long clickable, a View
965     * reacts to long clicks by notifying the OnLongClickListener or showing a
966     * context menu.
967     * </p>
968     * {@hide}
969     */
970    static final int LONG_CLICKABLE = 0x00200000;
971
972    /**
973     * <p>Indicates that this view gets its drawable states from its direct parent
974     * and ignores its original internal states.</p>
975     *
976     * @hide
977     */
978    static final int DUPLICATE_PARENT_STATE = 0x00400000;
979
980    /** @hide */
981    @IntDef({
982        SCROLLBARS_INSIDE_OVERLAY,
983        SCROLLBARS_INSIDE_INSET,
984        SCROLLBARS_OUTSIDE_OVERLAY,
985        SCROLLBARS_OUTSIDE_INSET
986    })
987    @Retention(RetentionPolicy.SOURCE)
988    public @interface ScrollBarStyle {}
989
990    /**
991     * The scrollbar style to display the scrollbars inside the content area,
992     * without increasing the padding. The scrollbars will be overlaid with
993     * translucency on the view's content.
994     */
995    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
996
997    /**
998     * The scrollbar style to display the scrollbars inside the padded area,
999     * increasing the padding of the view. The scrollbars will not overlap the
1000     * content area of the view.
1001     */
1002    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1003
1004    /**
1005     * The scrollbar style to display the scrollbars at the edge of the view,
1006     * without increasing the padding. The scrollbars will be overlaid with
1007     * translucency.
1008     */
1009    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1010
1011    /**
1012     * The scrollbar style to display the scrollbars at the edge of the view,
1013     * increasing the padding of the view. The scrollbars will only overlap the
1014     * background, if any.
1015     */
1016    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1017
1018    /**
1019     * Mask to check if the scrollbar style is overlay or inset.
1020     * {@hide}
1021     */
1022    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1023
1024    /**
1025     * Mask to check if the scrollbar style is inside or outside.
1026     * {@hide}
1027     */
1028    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1029
1030    /**
1031     * Mask for scrollbar style.
1032     * {@hide}
1033     */
1034    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1035
1036    /**
1037     * View flag indicating that the screen should remain on while the
1038     * window containing this view is visible to the user.  This effectively
1039     * takes care of automatically setting the WindowManager's
1040     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1041     */
1042    public static final int KEEP_SCREEN_ON = 0x04000000;
1043
1044    /**
1045     * View flag indicating whether this view should have sound effects enabled
1046     * for events such as clicking and touching.
1047     */
1048    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1049
1050    /**
1051     * View flag indicating whether this view should have haptic feedback
1052     * enabled for events such as long presses.
1053     */
1054    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1055
1056    /**
1057     * <p>Indicates that the view hierarchy should stop saving state when
1058     * it reaches this view.  If state saving is initiated immediately at
1059     * the view, it will be allowed.
1060     * {@hide}
1061     */
1062    static final int PARENT_SAVE_DISABLED = 0x20000000;
1063
1064    /**
1065     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1066     * {@hide}
1067     */
1068    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1069
1070    /** @hide */
1071    @IntDef(flag = true,
1072            value = {
1073                FOCUSABLES_ALL,
1074                FOCUSABLES_TOUCH_MODE
1075            })
1076    @Retention(RetentionPolicy.SOURCE)
1077    public @interface FocusableMode {}
1078
1079    /**
1080     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1081     * should add all focusable Views regardless if they are focusable in touch mode.
1082     */
1083    public static final int FOCUSABLES_ALL = 0x00000000;
1084
1085    /**
1086     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1087     * should add only Views focusable in touch mode.
1088     */
1089    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1090
1091    /** @hide */
1092    @IntDef({
1093            FOCUS_BACKWARD,
1094            FOCUS_FORWARD,
1095            FOCUS_LEFT,
1096            FOCUS_UP,
1097            FOCUS_RIGHT,
1098            FOCUS_DOWN
1099    })
1100    @Retention(RetentionPolicy.SOURCE)
1101    public @interface FocusDirection {}
1102
1103    /** @hide */
1104    @IntDef({
1105            FOCUS_LEFT,
1106            FOCUS_UP,
1107            FOCUS_RIGHT,
1108            FOCUS_DOWN
1109    })
1110    @Retention(RetentionPolicy.SOURCE)
1111    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1115     * item.
1116     */
1117    public static final int FOCUS_BACKWARD = 0x00000001;
1118
1119    /**
1120     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1121     * item.
1122     */
1123    public static final int FOCUS_FORWARD = 0x00000002;
1124
1125    /**
1126     * Use with {@link #focusSearch(int)}. Move focus to the left.
1127     */
1128    public static final int FOCUS_LEFT = 0x00000011;
1129
1130    /**
1131     * Use with {@link #focusSearch(int)}. Move focus up.
1132     */
1133    public static final int FOCUS_UP = 0x00000021;
1134
1135    /**
1136     * Use with {@link #focusSearch(int)}. Move focus to the right.
1137     */
1138    public static final int FOCUS_RIGHT = 0x00000042;
1139
1140    /**
1141     * Use with {@link #focusSearch(int)}. Move focus down.
1142     */
1143    public static final int FOCUS_DOWN = 0x00000082;
1144
1145    /**
1146     * Bits of {@link #getMeasuredWidthAndState()} and
1147     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1148     */
1149    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1150
1151    /**
1152     * Bits of {@link #getMeasuredWidthAndState()} and
1153     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1154     */
1155    public static final int MEASURED_STATE_MASK = 0xff000000;
1156
1157    /**
1158     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1159     * for functions that combine both width and height into a single int,
1160     * such as {@link #getMeasuredState()} and the childState argument of
1161     * {@link #resolveSizeAndState(int, int, int)}.
1162     */
1163    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1164
1165    /**
1166     * Bit of {@link #getMeasuredWidthAndState()} and
1167     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1168     * is smaller that the space the view would like to have.
1169     */
1170    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1171
1172    /**
1173     * Base View state sets
1174     */
1175    // Singles
1176    /**
1177     * Indicates the view has no states set. States are used with
1178     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1179     * view depending on its state.
1180     *
1181     * @see android.graphics.drawable.Drawable
1182     * @see #getDrawableState()
1183     */
1184    protected static final int[] EMPTY_STATE_SET;
1185    /**
1186     * Indicates the view is enabled. States are used with
1187     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1188     * view depending on its state.
1189     *
1190     * @see android.graphics.drawable.Drawable
1191     * @see #getDrawableState()
1192     */
1193    protected static final int[] ENABLED_STATE_SET;
1194    /**
1195     * Indicates the view is focused. States are used with
1196     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1197     * view depending on its state.
1198     *
1199     * @see android.graphics.drawable.Drawable
1200     * @see #getDrawableState()
1201     */
1202    protected static final int[] FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is selected. States are used with
1205     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1206     * view depending on its state.
1207     *
1208     * @see android.graphics.drawable.Drawable
1209     * @see #getDrawableState()
1210     */
1211    protected static final int[] SELECTED_STATE_SET;
1212    /**
1213     * Indicates the view is pressed. States are used with
1214     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1215     * view depending on its state.
1216     *
1217     * @see android.graphics.drawable.Drawable
1218     * @see #getDrawableState()
1219     */
1220    protected static final int[] PRESSED_STATE_SET;
1221    /**
1222     * Indicates the view's window has focus. States are used with
1223     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1224     * view depending on its state.
1225     *
1226     * @see android.graphics.drawable.Drawable
1227     * @see #getDrawableState()
1228     */
1229    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1230    // Doubles
1231    /**
1232     * Indicates the view is enabled and has the focus.
1233     *
1234     * @see #ENABLED_STATE_SET
1235     * @see #FOCUSED_STATE_SET
1236     */
1237    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is enabled and selected.
1240     *
1241     * @see #ENABLED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     */
1244    protected static final int[] ENABLED_SELECTED_STATE_SET;
1245    /**
1246     * Indicates the view is enabled and that its window has focus.
1247     *
1248     * @see #ENABLED_STATE_SET
1249     * @see #WINDOW_FOCUSED_STATE_SET
1250     */
1251    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is focused and selected.
1254     *
1255     * @see #FOCUSED_STATE_SET
1256     * @see #SELECTED_STATE_SET
1257     */
1258    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1259    /**
1260     * Indicates the view has the focus and that its window has the focus.
1261     *
1262     * @see #FOCUSED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is selected and that its window has the focus.
1268     *
1269     * @see #SELECTED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1273    // Triples
1274    /**
1275     * Indicates the view is enabled, focused and selected.
1276     *
1277     * @see #ENABLED_STATE_SET
1278     * @see #FOCUSED_STATE_SET
1279     * @see #SELECTED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1282    /**
1283     * Indicates the view is enabled, focused and its window has the focus.
1284     *
1285     * @see #ENABLED_STATE_SET
1286     * @see #FOCUSED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is enabled, selected and its window has the focus.
1292     *
1293     * @see #ENABLED_STATE_SET
1294     * @see #SELECTED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is focused, selected and its window has the focus.
1300     *
1301     * @see #FOCUSED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is enabled, focused, selected and its window
1308     * has the focus.
1309     *
1310     * @see #ENABLED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     * @see #SELECTED_STATE_SET
1313     * @see #WINDOW_FOCUSED_STATE_SET
1314     */
1315    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed and its window has the focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #WINDOW_FOCUSED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed and selected.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #SELECTED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_SELECTED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, selected and its window has the focus.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #WINDOW_FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed and focused.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, focused and its window has the focus.
1347     *
1348     * @see #PRESSED_STATE_SET
1349     * @see #FOCUSED_STATE_SET
1350     * @see #WINDOW_FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, focused and selected.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #SELECTED_STATE_SET
1358     * @see #FOCUSED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed, focused, selected and its window has the focus.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #FOCUSED_STATE_SET
1366     * @see #SELECTED_STATE_SET
1367     * @see #WINDOW_FOCUSED_STATE_SET
1368     */
1369    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1370    /**
1371     * Indicates the view is pressed and enabled.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_STATE_SET;
1377    /**
1378     * Indicates the view is pressed, enabled and its window has the focus.
1379     *
1380     * @see #PRESSED_STATE_SET
1381     * @see #ENABLED_STATE_SET
1382     * @see #WINDOW_FOCUSED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled and selected.
1387     *
1388     * @see #PRESSED_STATE_SET
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     */
1392    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1393    /**
1394     * Indicates the view is pressed, enabled, selected and its window has the
1395     * focus.
1396     *
1397     * @see #PRESSED_STATE_SET
1398     * @see #ENABLED_STATE_SET
1399     * @see #SELECTED_STATE_SET
1400     * @see #WINDOW_FOCUSED_STATE_SET
1401     */
1402    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is pressed, enabled and focused.
1405     *
1406     * @see #PRESSED_STATE_SET
1407     * @see #ENABLED_STATE_SET
1408     * @see #FOCUSED_STATE_SET
1409     */
1410    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1411    /**
1412     * Indicates the view is pressed, enabled, focused and its window has the
1413     * focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #ENABLED_STATE_SET
1417     * @see #FOCUSED_STATE_SET
1418     * @see #WINDOW_FOCUSED_STATE_SET
1419     */
1420    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1421    /**
1422     * Indicates the view is pressed, enabled, focused and selected.
1423     *
1424     * @see #PRESSED_STATE_SET
1425     * @see #ENABLED_STATE_SET
1426     * @see #SELECTED_STATE_SET
1427     * @see #FOCUSED_STATE_SET
1428     */
1429    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1430    /**
1431     * Indicates the view is pressed, enabled, focused, selected and its window
1432     * has the focus.
1433     *
1434     * @see #PRESSED_STATE_SET
1435     * @see #ENABLED_STATE_SET
1436     * @see #SELECTED_STATE_SET
1437     * @see #FOCUSED_STATE_SET
1438     * @see #WINDOW_FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1441
1442    static {
1443        EMPTY_STATE_SET = StateSet.get(0);
1444
1445        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1446
1447        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1448        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1449                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1450
1451        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1452        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1453                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1454        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1455                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1456        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1457                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1458                        | StateSet.VIEW_STATE_FOCUSED);
1459
1460        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1461        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1462                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1463        ENABLED_SELECTED_STATE_SET = StateSet.get(
1464                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1465        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1466                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1467                        | StateSet.VIEW_STATE_ENABLED);
1468        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1469                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1470        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1471                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1472                        | StateSet.VIEW_STATE_ENABLED);
1473        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1474                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1475                        | StateSet.VIEW_STATE_ENABLED);
1476        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1477                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1478                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1479
1480        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1481        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1482                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1483        PRESSED_SELECTED_STATE_SET = StateSet.get(
1484                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1485        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1486                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1487                        | StateSet.VIEW_STATE_PRESSED);
1488        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1489                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1490        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1491                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1492                        | StateSet.VIEW_STATE_PRESSED);
1493        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1495                        | StateSet.VIEW_STATE_PRESSED);
1496        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1497                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1498                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1499        PRESSED_ENABLED_STATE_SET = StateSet.get(
1500                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1501        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1502                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1503                        | StateSet.VIEW_STATE_PRESSED);
1504        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1505                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1506                        | StateSet.VIEW_STATE_PRESSED);
1507        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1508                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1509                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1510        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1511                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1512                        | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1515                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1516        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1517                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1518                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1519        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1520                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1521                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1522                        | StateSet.VIEW_STATE_PRESSED);
1523    }
1524
1525    /**
1526     * Accessibility event types that are dispatched for text population.
1527     */
1528    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1529            AccessibilityEvent.TYPE_VIEW_CLICKED
1530            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1531            | AccessibilityEvent.TYPE_VIEW_SELECTED
1532            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1533            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1534            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1535            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1536            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1537            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1538            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1539            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1540
1541    /**
1542     * Temporary Rect currently for use in setBackground().  This will probably
1543     * be extended in the future to hold our own class with more than just
1544     * a Rect. :)
1545     */
1546    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1547
1548    /**
1549     * Map used to store views' tags.
1550     */
1551    private SparseArray<Object> mKeyedTags;
1552
1553    /**
1554     * The next available accessibility id.
1555     */
1556    private static int sNextAccessibilityViewId;
1557
1558    /**
1559     * The animation currently associated with this view.
1560     * @hide
1561     */
1562    protected Animation mCurrentAnimation = null;
1563
1564    /**
1565     * Width as measured during measure pass.
1566     * {@hide}
1567     */
1568    @ViewDebug.ExportedProperty(category = "measurement")
1569    int mMeasuredWidth;
1570
1571    /**
1572     * Height as measured during measure pass.
1573     * {@hide}
1574     */
1575    @ViewDebug.ExportedProperty(category = "measurement")
1576    int mMeasuredHeight;
1577
1578    /**
1579     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1580     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1581     * its display list. This flag, used only when hw accelerated, allows us to clear the
1582     * flag while retaining this information until it's needed (at getDisplayList() time and
1583     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1584     *
1585     * {@hide}
1586     */
1587    boolean mRecreateDisplayList = false;
1588
1589    /**
1590     * The view's identifier.
1591     * {@hide}
1592     *
1593     * @see #setId(int)
1594     * @see #getId()
1595     */
1596    @ViewDebug.ExportedProperty(resolveId = true)
1597    int mID = NO_ID;
1598
1599    /**
1600     * The stable ID of this view for accessibility purposes.
1601     */
1602    int mAccessibilityViewId = NO_ID;
1603
1604    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1605
1606    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1607
1608    /**
1609     * The view's tag.
1610     * {@hide}
1611     *
1612     * @see #setTag(Object)
1613     * @see #getTag()
1614     */
1615    protected Object mTag = null;
1616
1617    // for mPrivateFlags:
1618    /** {@hide} */
1619    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1620    /** {@hide} */
1621    static final int PFLAG_FOCUSED                     = 0x00000002;
1622    /** {@hide} */
1623    static final int PFLAG_SELECTED                    = 0x00000004;
1624    /** {@hide} */
1625    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1626    /** {@hide} */
1627    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1628    /** {@hide} */
1629    static final int PFLAG_DRAWN                       = 0x00000020;
1630    /**
1631     * When this flag is set, this view is running an animation on behalf of its
1632     * children and should therefore not cancel invalidate requests, even if they
1633     * lie outside of this view's bounds.
1634     *
1635     * {@hide}
1636     */
1637    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1638    /** {@hide} */
1639    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1640    /** {@hide} */
1641    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1642    /** {@hide} */
1643    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1644    /** {@hide} */
1645    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1646    /** {@hide} */
1647    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1648    /** {@hide} */
1649    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1650    /** {@hide} */
1651    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1652
1653    private static final int PFLAG_PRESSED             = 0x00004000;
1654
1655    /** {@hide} */
1656    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1657    /**
1658     * Flag used to indicate that this view should be drawn once more (and only once
1659     * more) after its animation has completed.
1660     * {@hide}
1661     */
1662    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1663
1664    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1665
1666    /**
1667     * Indicates that the View returned true when onSetAlpha() was called and that
1668     * the alpha must be restored.
1669     * {@hide}
1670     */
1671    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1672
1673    /**
1674     * Set by {@link #setScrollContainer(boolean)}.
1675     */
1676    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1677
1678    /**
1679     * Set by {@link #setScrollContainer(boolean)}.
1680     */
1681    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1682
1683    /**
1684     * View flag indicating whether this view was invalidated (fully or partially.)
1685     *
1686     * @hide
1687     */
1688    static final int PFLAG_DIRTY                       = 0x00200000;
1689
1690    /**
1691     * View flag indicating whether this view was invalidated by an opaque
1692     * invalidate request.
1693     *
1694     * @hide
1695     */
1696    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1697
1698    /**
1699     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1700     *
1701     * @hide
1702     */
1703    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1704
1705    /**
1706     * Indicates whether the background is opaque.
1707     *
1708     * @hide
1709     */
1710    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1711
1712    /**
1713     * Indicates whether the scrollbars are opaque.
1714     *
1715     * @hide
1716     */
1717    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1718
1719    /**
1720     * Indicates whether the view is opaque.
1721     *
1722     * @hide
1723     */
1724    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1725
1726    /**
1727     * Indicates a prepressed state;
1728     * the short time between ACTION_DOWN and recognizing
1729     * a 'real' press. Prepressed is used to recognize quick taps
1730     * even when they are shorter than ViewConfiguration.getTapTimeout().
1731     *
1732     * @hide
1733     */
1734    private static final int PFLAG_PREPRESSED          = 0x02000000;
1735
1736    /**
1737     * Indicates whether the view is temporarily detached.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1742
1743    /**
1744     * Indicates that we should awaken scroll bars once attached
1745     *
1746     * @hide
1747     */
1748    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1749
1750    /**
1751     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1752     * @hide
1753     */
1754    private static final int PFLAG_HOVERED             = 0x10000000;
1755
1756    /**
1757     * no longer needed, should be reused
1758     */
1759    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1760
1761    /** {@hide} */
1762    static final int PFLAG_ACTIVATED                   = 0x40000000;
1763
1764    /**
1765     * Indicates that this view was specifically invalidated, not just dirtied because some
1766     * child view was invalidated. The flag is used to determine when we need to recreate
1767     * a view's display list (as opposed to just returning a reference to its existing
1768     * display list).
1769     *
1770     * @hide
1771     */
1772    static final int PFLAG_INVALIDATED                 = 0x80000000;
1773
1774    /**
1775     * Masks for mPrivateFlags2, as generated by dumpFlags():
1776     *
1777     * |-------|-------|-------|-------|
1778     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1779     *                                1  PFLAG2_DRAG_HOVERED
1780     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1781     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1782     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1783     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1784     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1785     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1786     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1787     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1788     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1789     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1790     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1791     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1792     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1793     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1794     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1795     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1796     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1797     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1798     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1799     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1800     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1801     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1802     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1803     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1804     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1805     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1806     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1807     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1808     *    1                              PFLAG2_PADDING_RESOLVED
1809     *   1                               PFLAG2_DRAWABLE_RESOLVED
1810     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1811     * |-------|-------|-------|-------|
1812     */
1813
1814    /**
1815     * Indicates that this view has reported that it can accept the current drag's content.
1816     * Cleared when the drag operation concludes.
1817     * @hide
1818     */
1819    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1820
1821    /**
1822     * Indicates that this view is currently directly under the drag location in a
1823     * drag-and-drop operation involving content that it can accept.  Cleared when
1824     * the drag exits the view, or when the drag operation concludes.
1825     * @hide
1826     */
1827    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1828
1829    /** @hide */
1830    @IntDef({
1831        LAYOUT_DIRECTION_LTR,
1832        LAYOUT_DIRECTION_RTL,
1833        LAYOUT_DIRECTION_INHERIT,
1834        LAYOUT_DIRECTION_LOCALE
1835    })
1836    @Retention(RetentionPolicy.SOURCE)
1837    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1838    public @interface LayoutDir {}
1839
1840    /** @hide */
1841    @IntDef({
1842        LAYOUT_DIRECTION_LTR,
1843        LAYOUT_DIRECTION_RTL
1844    })
1845    @Retention(RetentionPolicy.SOURCE)
1846    public @interface ResolvedLayoutDir {}
1847
1848    /**
1849     * Horizontal layout direction of this view is from Left to Right.
1850     * Use with {@link #setLayoutDirection}.
1851     */
1852    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1853
1854    /**
1855     * Horizontal layout direction of this view is from Right to Left.
1856     * Use with {@link #setLayoutDirection}.
1857     */
1858    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1859
1860    /**
1861     * Horizontal layout direction of this view is inherited from its parent.
1862     * Use with {@link #setLayoutDirection}.
1863     */
1864    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1865
1866    /**
1867     * Horizontal layout direction of this view is from deduced from the default language
1868     * script for the locale. Use with {@link #setLayoutDirection}.
1869     */
1870    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1871
1872    /**
1873     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1874     * @hide
1875     */
1876    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1877
1878    /**
1879     * Mask for use with private flags indicating bits used for horizontal layout direction.
1880     * @hide
1881     */
1882    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1883
1884    /**
1885     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1886     * right-to-left direction.
1887     * @hide
1888     */
1889    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1890
1891    /**
1892     * Indicates whether the view horizontal layout direction has been resolved.
1893     * @hide
1894     */
1895    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1896
1897    /**
1898     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1899     * @hide
1900     */
1901    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1902            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1903
1904    /*
1905     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1906     * flag value.
1907     * @hide
1908     */
1909    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1910            LAYOUT_DIRECTION_LTR,
1911            LAYOUT_DIRECTION_RTL,
1912            LAYOUT_DIRECTION_INHERIT,
1913            LAYOUT_DIRECTION_LOCALE
1914    };
1915
1916    /**
1917     * Default horizontal layout direction.
1918     */
1919    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1920
1921    /**
1922     * Default horizontal layout direction.
1923     * @hide
1924     */
1925    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1926
1927    /**
1928     * Text direction is inherited through {@link ViewGroup}
1929     */
1930    public static final int TEXT_DIRECTION_INHERIT = 0;
1931
1932    /**
1933     * Text direction is using "first strong algorithm". The first strong directional character
1934     * determines the paragraph direction. If there is no strong directional character, the
1935     * paragraph direction is the view's resolved layout direction.
1936     */
1937    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1938
1939    /**
1940     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1941     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1942     * If there are neither, the paragraph direction is the view's resolved layout direction.
1943     */
1944    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1945
1946    /**
1947     * Text direction is forced to LTR.
1948     */
1949    public static final int TEXT_DIRECTION_LTR = 3;
1950
1951    /**
1952     * Text direction is forced to RTL.
1953     */
1954    public static final int TEXT_DIRECTION_RTL = 4;
1955
1956    /**
1957     * Text direction is coming from the system Locale.
1958     */
1959    public static final int TEXT_DIRECTION_LOCALE = 5;
1960
1961    /**
1962     * Default text direction is inherited
1963     */
1964    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1965
1966    /**
1967     * Default resolved text direction
1968     * @hide
1969     */
1970    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1971
1972    /**
1973     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1974     * @hide
1975     */
1976    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1977
1978    /**
1979     * Mask for use with private flags indicating bits used for text direction.
1980     * @hide
1981     */
1982    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1983            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1984
1985    /**
1986     * Array of text direction flags for mapping attribute "textDirection" to correct
1987     * flag value.
1988     * @hide
1989     */
1990    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1991            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1992            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1993            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1994            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1995            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1996            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1997    };
1998
1999    /**
2000     * Indicates whether the view text direction has been resolved.
2001     * @hide
2002     */
2003    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2004            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2005
2006    /**
2007     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2008     * @hide
2009     */
2010    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2011
2012    /**
2013     * Mask for use with private flags indicating bits used for resolved text direction.
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2017            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2018
2019    /**
2020     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2021     * @hide
2022     */
2023    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2024            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2025
2026    /** @hide */
2027    @IntDef({
2028        TEXT_ALIGNMENT_INHERIT,
2029        TEXT_ALIGNMENT_GRAVITY,
2030        TEXT_ALIGNMENT_CENTER,
2031        TEXT_ALIGNMENT_TEXT_START,
2032        TEXT_ALIGNMENT_TEXT_END,
2033        TEXT_ALIGNMENT_VIEW_START,
2034        TEXT_ALIGNMENT_VIEW_END
2035    })
2036    @Retention(RetentionPolicy.SOURCE)
2037    public @interface TextAlignment {}
2038
2039    /**
2040     * Default text alignment. The text alignment of this View is inherited from its parent.
2041     * Use with {@link #setTextAlignment(int)}
2042     */
2043    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2044
2045    /**
2046     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2047     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2048     *
2049     * Use with {@link #setTextAlignment(int)}
2050     */
2051    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2052
2053    /**
2054     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2055     *
2056     * Use with {@link #setTextAlignment(int)}
2057     */
2058    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2059
2060    /**
2061     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2062     *
2063     * Use with {@link #setTextAlignment(int)}
2064     */
2065    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2066
2067    /**
2068     * Center the paragraph, e.g. ALIGN_CENTER.
2069     *
2070     * Use with {@link #setTextAlignment(int)}
2071     */
2072    public static final int TEXT_ALIGNMENT_CENTER = 4;
2073
2074    /**
2075     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2076     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2077     *
2078     * Use with {@link #setTextAlignment(int)}
2079     */
2080    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2081
2082    /**
2083     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2084     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2085     *
2086     * Use with {@link #setTextAlignment(int)}
2087     */
2088    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2089
2090    /**
2091     * Default text alignment is inherited
2092     */
2093    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2094
2095    /**
2096     * Default resolved text alignment
2097     * @hide
2098     */
2099    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2100
2101    /**
2102      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2103      * @hide
2104      */
2105    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2106
2107    /**
2108      * Mask for use with private flags indicating bits used for text alignment.
2109      * @hide
2110      */
2111    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2112
2113    /**
2114     * Array of text direction flags for mapping attribute "textAlignment" to correct
2115     * flag value.
2116     * @hide
2117     */
2118    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2119            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2120            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2121            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2122            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2123            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2124            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2125            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2126    };
2127
2128    /**
2129     * Indicates whether the view text alignment has been resolved.
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2133
2134    /**
2135     * Bit shift to get the resolved text alignment.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2139
2140    /**
2141     * Mask for use with private flags indicating bits used for text alignment.
2142     * @hide
2143     */
2144    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2145            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2146
2147    /**
2148     * Indicates whether if the view text alignment has been resolved to gravity
2149     */
2150    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2151            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2152
2153    // Accessiblity constants for mPrivateFlags2
2154
2155    /**
2156     * Shift for the bits in {@link #mPrivateFlags2} related to the
2157     * "importantForAccessibility" attribute.
2158     */
2159    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2160
2161    /**
2162     * Automatically determine whether a view is important for accessibility.
2163     */
2164    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2165
2166    /**
2167     * The view is important for accessibility.
2168     */
2169    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2170
2171    /**
2172     * The view is not important for accessibility.
2173     */
2174    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2175
2176    /**
2177     * The view is not important for accessibility, nor are any of its
2178     * descendant views.
2179     */
2180    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2181
2182    /**
2183     * The default whether the view is important for accessibility.
2184     */
2185    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2186
2187    /**
2188     * Mask for obtainig the bits which specify how to determine
2189     * whether a view is important for accessibility.
2190     */
2191    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2192        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2193        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2194        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2195
2196    /**
2197     * Shift for the bits in {@link #mPrivateFlags2} related to the
2198     * "accessibilityLiveRegion" attribute.
2199     */
2200    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2201
2202    /**
2203     * Live region mode specifying that accessibility services should not
2204     * automatically announce changes to this view. This is the default live
2205     * region mode for most views.
2206     * <p>
2207     * Use with {@link #setAccessibilityLiveRegion(int)}.
2208     */
2209    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2210
2211    /**
2212     * Live region mode specifying that accessibility services should announce
2213     * changes to this view.
2214     * <p>
2215     * Use with {@link #setAccessibilityLiveRegion(int)}.
2216     */
2217    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2218
2219    /**
2220     * Live region mode specifying that accessibility services should interrupt
2221     * ongoing speech to immediately announce changes to this view.
2222     * <p>
2223     * Use with {@link #setAccessibilityLiveRegion(int)}.
2224     */
2225    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2226
2227    /**
2228     * The default whether the view is important for accessibility.
2229     */
2230    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2231
2232    /**
2233     * Mask for obtaining the bits which specify a view's accessibility live
2234     * region mode.
2235     */
2236    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2237            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2238            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2239
2240    /**
2241     * Flag indicating whether a view has accessibility focus.
2242     */
2243    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2244
2245    /**
2246     * Flag whether the accessibility state of the subtree rooted at this view changed.
2247     */
2248    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2249
2250    /**
2251     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2252     * is used to check whether later changes to the view's transform should invalidate the
2253     * view to force the quickReject test to run again.
2254     */
2255    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2256
2257    /**
2258     * Flag indicating that start/end padding has been resolved into left/right padding
2259     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2260     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2261     * during measurement. In some special cases this is required such as when an adapter-based
2262     * view measures prospective children without attaching them to a window.
2263     */
2264    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2265
2266    /**
2267     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2268     */
2269    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2270
2271    /**
2272     * Indicates that the view is tracking some sort of transient state
2273     * that the app should not need to be aware of, but that the framework
2274     * should take special care to preserve.
2275     */
2276    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2277
2278    /**
2279     * Group of bits indicating that RTL properties resolution is done.
2280     */
2281    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2282            PFLAG2_TEXT_DIRECTION_RESOLVED |
2283            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2284            PFLAG2_PADDING_RESOLVED |
2285            PFLAG2_DRAWABLE_RESOLVED;
2286
2287    // There are a couple of flags left in mPrivateFlags2
2288
2289    /* End of masks for mPrivateFlags2 */
2290
2291    /**
2292     * Masks for mPrivateFlags3, as generated by dumpFlags():
2293     *
2294     * |-------|-------|-------|-------|
2295     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2296     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2297     *                               1   PFLAG3_IS_LAID_OUT
2298     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2299     *                             1     PFLAG3_CALLED_SUPER
2300     * |-------|-------|-------|-------|
2301     */
2302
2303    /**
2304     * Flag indicating that view has a transform animation set on it. This is used to track whether
2305     * an animation is cleared between successive frames, in order to tell the associated
2306     * DisplayList to clear its animation matrix.
2307     */
2308    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2309
2310    /**
2311     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2312     * animation is cleared between successive frames, in order to tell the associated
2313     * DisplayList to restore its alpha value.
2314     */
2315    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2316
2317    /**
2318     * Flag indicating that the view has been through at least one layout since it
2319     * was last attached to a window.
2320     */
2321    static final int PFLAG3_IS_LAID_OUT = 0x4;
2322
2323    /**
2324     * Flag indicating that a call to measure() was skipped and should be done
2325     * instead when layout() is invoked.
2326     */
2327    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2328
2329    /**
2330     * Flag indicating that an overridden method correctly called down to
2331     * the superclass implementation as required by the API spec.
2332     */
2333    static final int PFLAG3_CALLED_SUPER = 0x10;
2334
2335    /**
2336     * Flag indicating that we're in the process of applying window insets.
2337     */
2338    static final int PFLAG3_APPLYING_INSETS = 0x20;
2339
2340    /**
2341     * Flag indicating that we're in the process of fitting system windows using the old method.
2342     */
2343    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2344
2345    /**
2346     * Flag indicating that nested scrolling is enabled for this view.
2347     * The view will optionally cooperate with views up its parent chain to allow for
2348     * integrated nested scrolling along the same axis.
2349     */
2350    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2351
2352    /* End of masks for mPrivateFlags3 */
2353
2354    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2355
2356    /**
2357     * Always allow a user to over-scroll this view, provided it is a
2358     * view that can scroll.
2359     *
2360     * @see #getOverScrollMode()
2361     * @see #setOverScrollMode(int)
2362     */
2363    public static final int OVER_SCROLL_ALWAYS = 0;
2364
2365    /**
2366     * Allow a user to over-scroll this view only if the content is large
2367     * enough to meaningfully scroll, provided it is a view that can scroll.
2368     *
2369     * @see #getOverScrollMode()
2370     * @see #setOverScrollMode(int)
2371     */
2372    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2373
2374    /**
2375     * Never allow a user to over-scroll this view.
2376     *
2377     * @see #getOverScrollMode()
2378     * @see #setOverScrollMode(int)
2379     */
2380    public static final int OVER_SCROLL_NEVER = 2;
2381
2382    /**
2383     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2384     * requested the system UI (status bar) to be visible (the default).
2385     *
2386     * @see #setSystemUiVisibility(int)
2387     */
2388    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2389
2390    /**
2391     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2392     * system UI to enter an unobtrusive "low profile" mode.
2393     *
2394     * <p>This is for use in games, book readers, video players, or any other
2395     * "immersive" application where the usual system chrome is deemed too distracting.
2396     *
2397     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2398     *
2399     * @see #setSystemUiVisibility(int)
2400     */
2401    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2402
2403    /**
2404     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2405     * system navigation be temporarily hidden.
2406     *
2407     * <p>This is an even less obtrusive state than that called for by
2408     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2409     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2410     * those to disappear. This is useful (in conjunction with the
2411     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2412     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2413     * window flags) for displaying content using every last pixel on the display.
2414     *
2415     * <p>There is a limitation: because navigation controls are so important, the least user
2416     * interaction will cause them to reappear immediately.  When this happens, both
2417     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2418     * so that both elements reappear at the same time.
2419     *
2420     * @see #setSystemUiVisibility(int)
2421     */
2422    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2423
2424    /**
2425     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2426     * into the normal fullscreen mode so that its content can take over the screen
2427     * while still allowing the user to interact with the application.
2428     *
2429     * <p>This has the same visual effect as
2430     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2431     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2432     * meaning that non-critical screen decorations (such as the status bar) will be
2433     * hidden while the user is in the View's window, focusing the experience on
2434     * that content.  Unlike the window flag, if you are using ActionBar in
2435     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2436     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2437     * hide the action bar.
2438     *
2439     * <p>This approach to going fullscreen is best used over the window flag when
2440     * it is a transient state -- that is, the application does this at certain
2441     * points in its user interaction where it wants to allow the user to focus
2442     * on content, but not as a continuous state.  For situations where the application
2443     * would like to simply stay full screen the entire time (such as a game that
2444     * wants to take over the screen), the
2445     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2446     * is usually a better approach.  The state set here will be removed by the system
2447     * in various situations (such as the user moving to another application) like
2448     * the other system UI states.
2449     *
2450     * <p>When using this flag, the application should provide some easy facility
2451     * for the user to go out of it.  A common example would be in an e-book
2452     * reader, where tapping on the screen brings back whatever screen and UI
2453     * decorations that had been hidden while the user was immersed in reading
2454     * the book.
2455     *
2456     * @see #setSystemUiVisibility(int)
2457     */
2458    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2459
2460    /**
2461     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2462     * flags, we would like a stable view of the content insets given to
2463     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2464     * will always represent the worst case that the application can expect
2465     * as a continuous state.  In the stock Android UI this is the space for
2466     * the system bar, nav bar, and status bar, but not more transient elements
2467     * such as an input method.
2468     *
2469     * The stable layout your UI sees is based on the system UI modes you can
2470     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2471     * then you will get a stable layout for changes of the
2472     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2473     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2474     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2475     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2476     * with a stable layout.  (Note that you should avoid using
2477     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2478     *
2479     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2480     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2481     * then a hidden status bar will be considered a "stable" state for purposes
2482     * here.  This allows your UI to continually hide the status bar, while still
2483     * using the system UI flags to hide the action bar while still retaining
2484     * a stable layout.  Note that changing the window fullscreen flag will never
2485     * provide a stable layout for a clean transition.
2486     *
2487     * <p>If you are using ActionBar in
2488     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2489     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2490     * insets it adds to those given to the application.
2491     */
2492    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2493
2494    /**
2495     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2496     * to be laid out as if it has requested
2497     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2498     * allows it to avoid artifacts when switching in and out of that mode, at
2499     * the expense that some of its user interface may be covered by screen
2500     * decorations when they are shown.  You can perform layout of your inner
2501     * UI elements to account for the navigation system UI through the
2502     * {@link #fitSystemWindows(Rect)} method.
2503     */
2504    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2505
2506    /**
2507     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2508     * to be laid out as if it has requested
2509     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2510     * allows it to avoid artifacts when switching in and out of that mode, at
2511     * the expense that some of its user interface may be covered by screen
2512     * decorations when they are shown.  You can perform layout of your inner
2513     * UI elements to account for non-fullscreen system UI through the
2514     * {@link #fitSystemWindows(Rect)} method.
2515     */
2516    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2517
2518    /**
2519     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2520     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2521     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2522     * user interaction.
2523     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2524     * has an effect when used in combination with that flag.</p>
2525     */
2526    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2527
2528    /**
2529     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2530     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2531     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2532     * experience while also hiding the system bars.  If this flag is not set,
2533     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2534     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2535     * if the user swipes from the top of the screen.
2536     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2537     * system gestures, such as swiping from the top of the screen.  These transient system bars
2538     * will overlay app’s content, may have some degree of transparency, and will automatically
2539     * hide after a short timeout.
2540     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2541     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2542     * with one or both of those flags.</p>
2543     */
2544    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2545
2546    /**
2547     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2548     * is compatible with light status bar backgrounds.
2549     *
2550     * <p>For this to take effect, the window must request
2551     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2552     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2553     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2554     *         FLAG_TRANSLUCENT_STATUS}.
2555     *
2556     * @see android.R.attr#windowHasLightStatusBar
2557     */
2558    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2559
2560    /**
2561     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2562     */
2563    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2564
2565    /**
2566     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2567     */
2568    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2569
2570    /**
2571     * @hide
2572     *
2573     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2574     * out of the public fields to keep the undefined bits out of the developer's way.
2575     *
2576     * Flag to make the status bar not expandable.  Unless you also
2577     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2578     */
2579    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2580
2581    /**
2582     * @hide
2583     *
2584     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2585     * out of the public fields to keep the undefined bits out of the developer's way.
2586     *
2587     * Flag to hide notification icons and scrolling ticker text.
2588     */
2589    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2590
2591    /**
2592     * @hide
2593     *
2594     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2595     * out of the public fields to keep the undefined bits out of the developer's way.
2596     *
2597     * Flag to disable incoming notification alerts.  This will not block
2598     * icons, but it will block sound, vibrating and other visual or aural notifications.
2599     */
2600    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2601
2602    /**
2603     * @hide
2604     *
2605     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2606     * out of the public fields to keep the undefined bits out of the developer's way.
2607     *
2608     * Flag to hide only the scrolling ticker.  Note that
2609     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2610     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2611     */
2612    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2613
2614    /**
2615     * @hide
2616     *
2617     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2618     * out of the public fields to keep the undefined bits out of the developer's way.
2619     *
2620     * Flag to hide the center system info area.
2621     */
2622    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2623
2624    /**
2625     * @hide
2626     *
2627     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2628     * out of the public fields to keep the undefined bits out of the developer's way.
2629     *
2630     * Flag to hide only the home button.  Don't use this
2631     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2632     */
2633    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2634
2635    /**
2636     * @hide
2637     *
2638     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2639     * out of the public fields to keep the undefined bits out of the developer's way.
2640     *
2641     * Flag to hide only the back button. Don't use this
2642     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2643     */
2644    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2645
2646    /**
2647     * @hide
2648     *
2649     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2650     * out of the public fields to keep the undefined bits out of the developer's way.
2651     *
2652     * Flag to hide only the clock.  You might use this if your activity has
2653     * its own clock making the status bar's clock redundant.
2654     */
2655    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2656
2657    /**
2658     * @hide
2659     *
2660     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2661     * out of the public fields to keep the undefined bits out of the developer's way.
2662     *
2663     * Flag to hide only the recent apps button. Don't use this
2664     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2665     */
2666    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2667
2668    /**
2669     * @hide
2670     *
2671     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2672     * out of the public fields to keep the undefined bits out of the developer's way.
2673     *
2674     * Flag to disable the global search gesture. Don't use this
2675     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2676     */
2677    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2678
2679    /**
2680     * @hide
2681     *
2682     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2683     * out of the public fields to keep the undefined bits out of the developer's way.
2684     *
2685     * Flag to specify that the status bar is displayed in transient mode.
2686     */
2687    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2688
2689    /**
2690     * @hide
2691     *
2692     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2693     * out of the public fields to keep the undefined bits out of the developer's way.
2694     *
2695     * Flag to specify that the navigation bar is displayed in transient mode.
2696     */
2697    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2698
2699    /**
2700     * @hide
2701     *
2702     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2703     * out of the public fields to keep the undefined bits out of the developer's way.
2704     *
2705     * Flag to specify that the hidden status bar would like to be shown.
2706     */
2707    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2708
2709    /**
2710     * @hide
2711     *
2712     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2713     * out of the public fields to keep the undefined bits out of the developer's way.
2714     *
2715     * Flag to specify that the hidden navigation bar would like to be shown.
2716     */
2717    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2718
2719    /**
2720     * @hide
2721     *
2722     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2723     * out of the public fields to keep the undefined bits out of the developer's way.
2724     *
2725     * Flag to specify that the status bar is displayed in translucent mode.
2726     */
2727    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2728
2729    /**
2730     * @hide
2731     *
2732     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2733     * out of the public fields to keep the undefined bits out of the developer's way.
2734     *
2735     * Flag to specify that the navigation bar is displayed in translucent mode.
2736     */
2737    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2738
2739    /**
2740     * @hide
2741     *
2742     * Whether Recents is visible or not.
2743     */
2744    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2745
2746    /**
2747     * @hide
2748     *
2749     * Makes system ui transparent.
2750     */
2751    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2752
2753    /**
2754     * @hide
2755     */
2756    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2757
2758    /**
2759     * These are the system UI flags that can be cleared by events outside
2760     * of an application.  Currently this is just the ability to tap on the
2761     * screen while hiding the navigation bar to have it return.
2762     * @hide
2763     */
2764    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2765            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2766            | SYSTEM_UI_FLAG_FULLSCREEN;
2767
2768    /**
2769     * Flags that can impact the layout in relation to system UI.
2770     */
2771    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2772            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2773            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2774
2775    /** @hide */
2776    @IntDef(flag = true,
2777            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2778    @Retention(RetentionPolicy.SOURCE)
2779    public @interface FindViewFlags {}
2780
2781    /**
2782     * Find views that render the specified text.
2783     *
2784     * @see #findViewsWithText(ArrayList, CharSequence, int)
2785     */
2786    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2787
2788    /**
2789     * Find find views that contain the specified content description.
2790     *
2791     * @see #findViewsWithText(ArrayList, CharSequence, int)
2792     */
2793    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2794
2795    /**
2796     * Find views that contain {@link AccessibilityNodeProvider}. Such
2797     * a View is a root of virtual view hierarchy and may contain the searched
2798     * text. If this flag is set Views with providers are automatically
2799     * added and it is a responsibility of the client to call the APIs of
2800     * the provider to determine whether the virtual tree rooted at this View
2801     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2802     * representing the virtual views with this text.
2803     *
2804     * @see #findViewsWithText(ArrayList, CharSequence, int)
2805     *
2806     * @hide
2807     */
2808    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2809
2810    /**
2811     * The undefined cursor position.
2812     *
2813     * @hide
2814     */
2815    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2816
2817    /**
2818     * Indicates that the screen has changed state and is now off.
2819     *
2820     * @see #onScreenStateChanged(int)
2821     */
2822    public static final int SCREEN_STATE_OFF = 0x0;
2823
2824    /**
2825     * Indicates that the screen has changed state and is now on.
2826     *
2827     * @see #onScreenStateChanged(int)
2828     */
2829    public static final int SCREEN_STATE_ON = 0x1;
2830
2831    /**
2832     * Indicates no axis of view scrolling.
2833     */
2834    public static final int SCROLL_AXIS_NONE = 0;
2835
2836    /**
2837     * Indicates scrolling along the horizontal axis.
2838     */
2839    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2840
2841    /**
2842     * Indicates scrolling along the vertical axis.
2843     */
2844    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2845
2846    /**
2847     * Controls the over-scroll mode for this view.
2848     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2849     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2850     * and {@link #OVER_SCROLL_NEVER}.
2851     */
2852    private int mOverScrollMode;
2853
2854    /**
2855     * The parent this view is attached to.
2856     * {@hide}
2857     *
2858     * @see #getParent()
2859     */
2860    protected ViewParent mParent;
2861
2862    /**
2863     * {@hide}
2864     */
2865    AttachInfo mAttachInfo;
2866
2867    /**
2868     * {@hide}
2869     */
2870    @ViewDebug.ExportedProperty(flagMapping = {
2871        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2872                name = "FORCE_LAYOUT"),
2873        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2874                name = "LAYOUT_REQUIRED"),
2875        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2876            name = "DRAWING_CACHE_INVALID", outputIf = false),
2877        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2878        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2879        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2880        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2881    }, formatToHexString = true)
2882    int mPrivateFlags;
2883    int mPrivateFlags2;
2884    int mPrivateFlags3;
2885
2886    /**
2887     * This view's request for the visibility of the status bar.
2888     * @hide
2889     */
2890    @ViewDebug.ExportedProperty(flagMapping = {
2891        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2892                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2893                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2894        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2895                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2896                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2897        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2898                                equals = SYSTEM_UI_FLAG_VISIBLE,
2899                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2900    }, formatToHexString = true)
2901    int mSystemUiVisibility;
2902
2903    /**
2904     * Reference count for transient state.
2905     * @see #setHasTransientState(boolean)
2906     */
2907    int mTransientStateCount = 0;
2908
2909    /**
2910     * Count of how many windows this view has been attached to.
2911     */
2912    int mWindowAttachCount;
2913
2914    /**
2915     * The layout parameters associated with this view and used by the parent
2916     * {@link android.view.ViewGroup} to determine how this view should be
2917     * laid out.
2918     * {@hide}
2919     */
2920    protected ViewGroup.LayoutParams mLayoutParams;
2921
2922    /**
2923     * The view flags hold various views states.
2924     * {@hide}
2925     */
2926    @ViewDebug.ExportedProperty(formatToHexString = true)
2927    int mViewFlags;
2928
2929    static class TransformationInfo {
2930        /**
2931         * The transform matrix for the View. This transform is calculated internally
2932         * based on the translation, rotation, and scale properties.
2933         *
2934         * Do *not* use this variable directly; instead call getMatrix(), which will
2935         * load the value from the View's RenderNode.
2936         */
2937        private final Matrix mMatrix = new Matrix();
2938
2939        /**
2940         * The inverse transform matrix for the View. This transform is calculated
2941         * internally based on the translation, rotation, and scale properties.
2942         *
2943         * Do *not* use this variable directly; instead call getInverseMatrix(),
2944         * which will load the value from the View's RenderNode.
2945         */
2946        private Matrix mInverseMatrix;
2947
2948        /**
2949         * The opacity of the View. This is a value from 0 to 1, where 0 means
2950         * completely transparent and 1 means completely opaque.
2951         */
2952        @ViewDebug.ExportedProperty
2953        float mAlpha = 1f;
2954
2955        /**
2956         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2957         * property only used by transitions, which is composited with the other alpha
2958         * values to calculate the final visual alpha value.
2959         */
2960        float mTransitionAlpha = 1f;
2961    }
2962
2963    TransformationInfo mTransformationInfo;
2964
2965    /**
2966     * Current clip bounds. to which all drawing of this view are constrained.
2967     */
2968    Rect mClipBounds = null;
2969
2970    private boolean mLastIsOpaque;
2971
2972    /**
2973     * The distance in pixels from the left edge of this view's parent
2974     * to the left edge of this view.
2975     * {@hide}
2976     */
2977    @ViewDebug.ExportedProperty(category = "layout")
2978    protected int mLeft;
2979    /**
2980     * The distance in pixels from the left edge of this view's parent
2981     * to the right edge of this view.
2982     * {@hide}
2983     */
2984    @ViewDebug.ExportedProperty(category = "layout")
2985    protected int mRight;
2986    /**
2987     * The distance in pixels from the top edge of this view's parent
2988     * to the top edge of this view.
2989     * {@hide}
2990     */
2991    @ViewDebug.ExportedProperty(category = "layout")
2992    protected int mTop;
2993    /**
2994     * The distance in pixels from the top edge of this view's parent
2995     * to the bottom edge of this view.
2996     * {@hide}
2997     */
2998    @ViewDebug.ExportedProperty(category = "layout")
2999    protected int mBottom;
3000
3001    /**
3002     * The offset, in pixels, by which the content of this view is scrolled
3003     * horizontally.
3004     * {@hide}
3005     */
3006    @ViewDebug.ExportedProperty(category = "scrolling")
3007    protected int mScrollX;
3008    /**
3009     * The offset, in pixels, by which the content of this view is scrolled
3010     * vertically.
3011     * {@hide}
3012     */
3013    @ViewDebug.ExportedProperty(category = "scrolling")
3014    protected int mScrollY;
3015
3016    /**
3017     * The left padding in pixels, that is the distance in pixels between the
3018     * left edge of this view and the left edge of its content.
3019     * {@hide}
3020     */
3021    @ViewDebug.ExportedProperty(category = "padding")
3022    protected int mPaddingLeft = 0;
3023    /**
3024     * The right padding in pixels, that is the distance in pixels between the
3025     * right edge of this view and the right edge of its content.
3026     * {@hide}
3027     */
3028    @ViewDebug.ExportedProperty(category = "padding")
3029    protected int mPaddingRight = 0;
3030    /**
3031     * The top padding in pixels, that is the distance in pixels between the
3032     * top edge of this view and the top edge of its content.
3033     * {@hide}
3034     */
3035    @ViewDebug.ExportedProperty(category = "padding")
3036    protected int mPaddingTop;
3037    /**
3038     * The bottom padding in pixels, that is the distance in pixels between the
3039     * bottom edge of this view and the bottom edge of its content.
3040     * {@hide}
3041     */
3042    @ViewDebug.ExportedProperty(category = "padding")
3043    protected int mPaddingBottom;
3044
3045    /**
3046     * The layout insets in pixels, that is the distance in pixels between the
3047     * visible edges of this view its bounds.
3048     */
3049    private Insets mLayoutInsets;
3050
3051    /**
3052     * Briefly describes the view and is primarily used for accessibility support.
3053     */
3054    private CharSequence mContentDescription;
3055
3056    /**
3057     * Specifies the id of a view for which this view serves as a label for
3058     * accessibility purposes.
3059     */
3060    private int mLabelForId = View.NO_ID;
3061
3062    /**
3063     * Predicate for matching labeled view id with its label for
3064     * accessibility purposes.
3065     */
3066    private MatchLabelForPredicate mMatchLabelForPredicate;
3067
3068    /**
3069     * Specifies a view before which this one is visited in accessibility traversal.
3070     */
3071    private int mAccessibilityTraversalBeforeId = NO_ID;
3072
3073    /**
3074     * Specifies a view after which this one is visited in accessibility traversal.
3075     */
3076    private int mAccessibilityTraversalAfterId = NO_ID;
3077
3078    /**
3079     * Predicate for matching a view by its id.
3080     */
3081    private MatchIdPredicate mMatchIdPredicate;
3082
3083    /**
3084     * Cache the paddingRight set by the user to append to the scrollbar's size.
3085     *
3086     * @hide
3087     */
3088    @ViewDebug.ExportedProperty(category = "padding")
3089    protected int mUserPaddingRight;
3090
3091    /**
3092     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3093     *
3094     * @hide
3095     */
3096    @ViewDebug.ExportedProperty(category = "padding")
3097    protected int mUserPaddingBottom;
3098
3099    /**
3100     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3101     *
3102     * @hide
3103     */
3104    @ViewDebug.ExportedProperty(category = "padding")
3105    protected int mUserPaddingLeft;
3106
3107    /**
3108     * Cache the paddingStart set by the user to append to the scrollbar's size.
3109     *
3110     */
3111    @ViewDebug.ExportedProperty(category = "padding")
3112    int mUserPaddingStart;
3113
3114    /**
3115     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3116     *
3117     */
3118    @ViewDebug.ExportedProperty(category = "padding")
3119    int mUserPaddingEnd;
3120
3121    /**
3122     * Cache initial left padding.
3123     *
3124     * @hide
3125     */
3126    int mUserPaddingLeftInitial;
3127
3128    /**
3129     * Cache initial right padding.
3130     *
3131     * @hide
3132     */
3133    int mUserPaddingRightInitial;
3134
3135    /**
3136     * Default undefined padding
3137     */
3138    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3139
3140    /**
3141     * Cache if a left padding has been defined
3142     */
3143    private boolean mLeftPaddingDefined = false;
3144
3145    /**
3146     * Cache if a right padding has been defined
3147     */
3148    private boolean mRightPaddingDefined = false;
3149
3150    /**
3151     * @hide
3152     */
3153    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3154    /**
3155     * @hide
3156     */
3157    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3158
3159    private LongSparseLongArray mMeasureCache;
3160
3161    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3162    private Drawable mBackground;
3163    private TintInfo mBackgroundTint;
3164
3165    /**
3166     * RenderNode used for backgrounds.
3167     * <p>
3168     * When non-null and valid, this is expected to contain an up-to-date copy
3169     * of the background drawable. It is cleared on temporary detach, and reset
3170     * on cleanup.
3171     */
3172    private RenderNode mBackgroundRenderNode;
3173
3174    private int mBackgroundResource;
3175    private boolean mBackgroundSizeChanged;
3176
3177    private String mTransitionName;
3178
3179    private static class TintInfo {
3180        ColorStateList mTintList;
3181        PorterDuff.Mode mTintMode;
3182        boolean mHasTintMode;
3183        boolean mHasTintList;
3184    }
3185
3186    static class ListenerInfo {
3187        /**
3188         * Listener used to dispatch focus change events.
3189         * This field should be made private, so it is hidden from the SDK.
3190         * {@hide}
3191         */
3192        protected OnFocusChangeListener mOnFocusChangeListener;
3193
3194        /**
3195         * Listeners for layout change events.
3196         */
3197        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3198
3199        protected OnScrollChangeListener mOnScrollChangeListener;
3200
3201        /**
3202         * Listeners for attach events.
3203         */
3204        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3205
3206        /**
3207         * Listener used to dispatch click events.
3208         * This field should be made private, so it is hidden from the SDK.
3209         * {@hide}
3210         */
3211        public OnClickListener mOnClickListener;
3212
3213        /**
3214         * Listener used to dispatch long click events.
3215         * This field should be made private, so it is hidden from the SDK.
3216         * {@hide}
3217         */
3218        protected OnLongClickListener mOnLongClickListener;
3219
3220        /**
3221         * Listener used to build the context menu.
3222         * This field should be made private, so it is hidden from the SDK.
3223         * {@hide}
3224         */
3225        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3226
3227        private OnKeyListener mOnKeyListener;
3228
3229        private OnTouchListener mOnTouchListener;
3230
3231        private OnHoverListener mOnHoverListener;
3232
3233        private OnGenericMotionListener mOnGenericMotionListener;
3234
3235        private OnDragListener mOnDragListener;
3236
3237        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3238
3239        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3240    }
3241
3242    ListenerInfo mListenerInfo;
3243
3244    /**
3245     * The application environment this view lives in.
3246     * This field should be made private, so it is hidden from the SDK.
3247     * {@hide}
3248     */
3249    @ViewDebug.ExportedProperty(deepExport = true)
3250    protected Context mContext;
3251
3252    private final Resources mResources;
3253
3254    private ScrollabilityCache mScrollCache;
3255
3256    private int[] mDrawableState = null;
3257
3258    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3259
3260    /**
3261     * Animator that automatically runs based on state changes.
3262     */
3263    private StateListAnimator mStateListAnimator;
3264
3265    /**
3266     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3267     * the user may specify which view to go to next.
3268     */
3269    private int mNextFocusLeftId = View.NO_ID;
3270
3271    /**
3272     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3273     * the user may specify which view to go to next.
3274     */
3275    private int mNextFocusRightId = View.NO_ID;
3276
3277    /**
3278     * When this view has focus and the next focus is {@link #FOCUS_UP},
3279     * the user may specify which view to go to next.
3280     */
3281    private int mNextFocusUpId = View.NO_ID;
3282
3283    /**
3284     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3285     * the user may specify which view to go to next.
3286     */
3287    private int mNextFocusDownId = View.NO_ID;
3288
3289    /**
3290     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3291     * the user may specify which view to go to next.
3292     */
3293    int mNextFocusForwardId = View.NO_ID;
3294
3295    private CheckForLongPress mPendingCheckForLongPress;
3296    private CheckForTap mPendingCheckForTap = null;
3297    private PerformClick mPerformClick;
3298    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3299
3300    private UnsetPressedState mUnsetPressedState;
3301
3302    /**
3303     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3304     * up event while a long press is invoked as soon as the long press duration is reached, so
3305     * a long press could be performed before the tap is checked, in which case the tap's action
3306     * should not be invoked.
3307     */
3308    private boolean mHasPerformedLongPress;
3309
3310    /**
3311     * The minimum height of the view. We'll try our best to have the height
3312     * of this view to at least this amount.
3313     */
3314    @ViewDebug.ExportedProperty(category = "measurement")
3315    private int mMinHeight;
3316
3317    /**
3318     * The minimum width of the view. We'll try our best to have the width
3319     * of this view to at least this amount.
3320     */
3321    @ViewDebug.ExportedProperty(category = "measurement")
3322    private int mMinWidth;
3323
3324    /**
3325     * The delegate to handle touch events that are physically in this view
3326     * but should be handled by another view.
3327     */
3328    private TouchDelegate mTouchDelegate = null;
3329
3330    /**
3331     * Solid color to use as a background when creating the drawing cache. Enables
3332     * the cache to use 16 bit bitmaps instead of 32 bit.
3333     */
3334    private int mDrawingCacheBackgroundColor = 0;
3335
3336    /**
3337     * Special tree observer used when mAttachInfo is null.
3338     */
3339    private ViewTreeObserver mFloatingTreeObserver;
3340
3341    /**
3342     * Cache the touch slop from the context that created the view.
3343     */
3344    private int mTouchSlop;
3345
3346    /**
3347     * Object that handles automatic animation of view properties.
3348     */
3349    private ViewPropertyAnimator mAnimator = null;
3350
3351    /**
3352     * Flag indicating that a drag can cross window boundaries.  When
3353     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3354     * with this flag set, all visible applications will be able to participate
3355     * in the drag operation and receive the dragged content.
3356     *
3357     * @hide
3358     */
3359    public static final int DRAG_FLAG_GLOBAL = 1;
3360
3361    /**
3362     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3363     */
3364    private float mVerticalScrollFactor;
3365
3366    /**
3367     * Position of the vertical scroll bar.
3368     */
3369    private int mVerticalScrollbarPosition;
3370
3371    /**
3372     * Position the scroll bar at the default position as determined by the system.
3373     */
3374    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3375
3376    /**
3377     * Position the scroll bar along the left edge.
3378     */
3379    public static final int SCROLLBAR_POSITION_LEFT = 1;
3380
3381    /**
3382     * Position the scroll bar along the right edge.
3383     */
3384    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3385
3386    /**
3387     * Indicates that the view does not have a layer.
3388     *
3389     * @see #getLayerType()
3390     * @see #setLayerType(int, android.graphics.Paint)
3391     * @see #LAYER_TYPE_SOFTWARE
3392     * @see #LAYER_TYPE_HARDWARE
3393     */
3394    public static final int LAYER_TYPE_NONE = 0;
3395
3396    /**
3397     * <p>Indicates that the view has a software layer. A software layer is backed
3398     * by a bitmap and causes the view to be rendered using Android's software
3399     * rendering pipeline, even if hardware acceleration is enabled.</p>
3400     *
3401     * <p>Software layers have various usages:</p>
3402     * <p>When the application is not using hardware acceleration, a software layer
3403     * is useful to apply a specific color filter and/or blending mode and/or
3404     * translucency to a view and all its children.</p>
3405     * <p>When the application is using hardware acceleration, a software layer
3406     * is useful to render drawing primitives not supported by the hardware
3407     * accelerated pipeline. It can also be used to cache a complex view tree
3408     * into a texture and reduce the complexity of drawing operations. For instance,
3409     * when animating a complex view tree with a translation, a software layer can
3410     * be used to render the view tree only once.</p>
3411     * <p>Software layers should be avoided when the affected view tree updates
3412     * often. Every update will require to re-render the software layer, which can
3413     * potentially be slow (particularly when hardware acceleration is turned on
3414     * since the layer will have to be uploaded into a hardware texture after every
3415     * update.)</p>
3416     *
3417     * @see #getLayerType()
3418     * @see #setLayerType(int, android.graphics.Paint)
3419     * @see #LAYER_TYPE_NONE
3420     * @see #LAYER_TYPE_HARDWARE
3421     */
3422    public static final int LAYER_TYPE_SOFTWARE = 1;
3423
3424    /**
3425     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3426     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3427     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3428     * rendering pipeline, but only if hardware acceleration is turned on for the
3429     * view hierarchy. When hardware acceleration is turned off, hardware layers
3430     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3431     *
3432     * <p>A hardware layer is useful to apply a specific color filter and/or
3433     * blending mode and/or translucency to a view and all its children.</p>
3434     * <p>A hardware layer can be used to cache a complex view tree into a
3435     * texture and reduce the complexity of drawing operations. For instance,
3436     * when animating a complex view tree with a translation, a hardware layer can
3437     * be used to render the view tree only once.</p>
3438     * <p>A hardware layer can also be used to increase the rendering quality when
3439     * rotation transformations are applied on a view. It can also be used to
3440     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3441     *
3442     * @see #getLayerType()
3443     * @see #setLayerType(int, android.graphics.Paint)
3444     * @see #LAYER_TYPE_NONE
3445     * @see #LAYER_TYPE_SOFTWARE
3446     */
3447    public static final int LAYER_TYPE_HARDWARE = 2;
3448
3449    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3450            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3451            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3452            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3453    })
3454    int mLayerType = LAYER_TYPE_NONE;
3455    Paint mLayerPaint;
3456
3457    /**
3458     * Set to true when drawing cache is enabled and cannot be created.
3459     *
3460     * @hide
3461     */
3462    public boolean mCachingFailed;
3463    private Bitmap mDrawingCache;
3464    private Bitmap mUnscaledDrawingCache;
3465
3466    /**
3467     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3468     * <p>
3469     * When non-null and valid, this is expected to contain an up-to-date copy
3470     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3471     * cleanup.
3472     */
3473    final RenderNode mRenderNode;
3474
3475    /**
3476     * Set to true when the view is sending hover accessibility events because it
3477     * is the innermost hovered view.
3478     */
3479    private boolean mSendingHoverAccessibilityEvents;
3480
3481    /**
3482     * Delegate for injecting accessibility functionality.
3483     */
3484    AccessibilityDelegate mAccessibilityDelegate;
3485
3486    /**
3487     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3488     * and add/remove objects to/from the overlay directly through the Overlay methods.
3489     */
3490    ViewOverlay mOverlay;
3491
3492    /**
3493     * The currently active parent view for receiving delegated nested scrolling events.
3494     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3495     * by {@link #stopNestedScroll()} at the same point where we clear
3496     * requestDisallowInterceptTouchEvent.
3497     */
3498    private ViewParent mNestedScrollingParent;
3499
3500    /**
3501     * Consistency verifier for debugging purposes.
3502     * @hide
3503     */
3504    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3505            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3506                    new InputEventConsistencyVerifier(this, 0) : null;
3507
3508    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3509
3510    private int[] mTempNestedScrollConsumed;
3511
3512    /**
3513     * An overlay is going to draw this View instead of being drawn as part of this
3514     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3515     * when this view is invalidated.
3516     */
3517    GhostView mGhostView;
3518
3519    /**
3520     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3521     * @hide
3522     */
3523    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3524    public String[] mAttributes;
3525
3526    /**
3527     * Maps a Resource id to its name.
3528     */
3529    private static SparseArray<String> mAttributeMap;
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(), this);
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            sCompatibilityDone = true;
3566        }
3567    }
3568
3569    /**
3570     * Constructor that is called when inflating a view from XML. This is called
3571     * when a view is being constructed from an XML file, supplying attributes
3572     * that were specified in the XML file. This version uses a default style of
3573     * 0, so the only attribute values applied are those in the Context's Theme
3574     * and the given AttributeSet.
3575     *
3576     * <p>
3577     * The method onFinishInflate() will be called after all children have been
3578     * added.
3579     *
3580     * @param context The Context the view is running in, through which it can
3581     *        access the current theme, resources, etc.
3582     * @param attrs The attributes of the XML tag that is inflating the view.
3583     * @see #View(Context, AttributeSet, int)
3584     */
3585    public View(Context context, AttributeSet attrs) {
3586        this(context, attrs, 0);
3587    }
3588
3589    /**
3590     * Perform inflation from XML and apply a class-specific base style from a
3591     * theme attribute. This constructor of View allows subclasses to use their
3592     * own base style when they are inflating. For example, a Button class's
3593     * constructor would call this version of the super class constructor and
3594     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3595     * allows the theme's button style to modify all of the base view attributes
3596     * (in particular its background) as well as the Button class's attributes.
3597     *
3598     * @param context The Context the view is running in, through which it can
3599     *        access the current theme, resources, etc.
3600     * @param attrs The attributes of the XML tag that is inflating the view.
3601     * @param defStyleAttr An attribute in the current theme that contains a
3602     *        reference to a style resource that supplies default values for
3603     *        the view. Can be 0 to not look for defaults.
3604     * @see #View(Context, AttributeSet)
3605     */
3606    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3607        this(context, attrs, defStyleAttr, 0);
3608    }
3609
3610    /**
3611     * Perform inflation from XML and apply a class-specific base style from a
3612     * theme attribute or style resource. This constructor of View allows
3613     * subclasses to use their own base style when they are inflating.
3614     * <p>
3615     * When determining the final value of a particular attribute, there are
3616     * four inputs that come into play:
3617     * <ol>
3618     * <li>Any attribute values in the given AttributeSet.
3619     * <li>The style resource specified in the AttributeSet (named "style").
3620     * <li>The default style specified by <var>defStyleAttr</var>.
3621     * <li>The default style specified by <var>defStyleRes</var>.
3622     * <li>The base values in this theme.
3623     * </ol>
3624     * <p>
3625     * Each of these inputs is considered in-order, with the first listed taking
3626     * precedence over the following ones. In other words, if in the
3627     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3628     * , then the button's text will <em>always</em> be black, regardless of
3629     * what is specified in any of the styles.
3630     *
3631     * @param context The Context the view is running in, through which it can
3632     *        access the current theme, resources, etc.
3633     * @param attrs The attributes of the XML tag that is inflating the view.
3634     * @param defStyleAttr An attribute in the current theme that contains a
3635     *        reference to a style resource that supplies default values for
3636     *        the view. Can be 0 to not look for defaults.
3637     * @param defStyleRes A resource identifier of a style resource that
3638     *        supplies default values for the view, used only if
3639     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3640     *        to not look for defaults.
3641     * @see #View(Context, AttributeSet, int)
3642     */
3643    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3644        this(context);
3645
3646        final TypedArray a = context.obtainStyledAttributes(
3647                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3648
3649        if (mDebugViewAttributes) {
3650            saveAttributeData(attrs, a);
3651        }
3652
3653        Drawable background = null;
3654
3655        int leftPadding = -1;
3656        int topPadding = -1;
3657        int rightPadding = -1;
3658        int bottomPadding = -1;
3659        int startPadding = UNDEFINED_PADDING;
3660        int endPadding = UNDEFINED_PADDING;
3661
3662        int padding = -1;
3663
3664        int viewFlagValues = 0;
3665        int viewFlagMasks = 0;
3666
3667        boolean setScrollContainer = false;
3668
3669        int x = 0;
3670        int y = 0;
3671
3672        float tx = 0;
3673        float ty = 0;
3674        float tz = 0;
3675        float elevation = 0;
3676        float rotation = 0;
3677        float rotationX = 0;
3678        float rotationY = 0;
3679        float sx = 1f;
3680        float sy = 1f;
3681        boolean transformSet = false;
3682
3683        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3684        int overScrollMode = mOverScrollMode;
3685        boolean initializeScrollbars = false;
3686
3687        boolean startPaddingDefined = false;
3688        boolean endPaddingDefined = false;
3689        boolean leftPaddingDefined = false;
3690        boolean rightPaddingDefined = false;
3691
3692        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3693
3694        final int N = a.getIndexCount();
3695        for (int i = 0; i < N; i++) {
3696            int attr = a.getIndex(i);
3697            switch (attr) {
3698                case com.android.internal.R.styleable.View_background:
3699                    background = a.getDrawable(attr);
3700                    break;
3701                case com.android.internal.R.styleable.View_padding:
3702                    padding = a.getDimensionPixelSize(attr, -1);
3703                    mUserPaddingLeftInitial = padding;
3704                    mUserPaddingRightInitial = padding;
3705                    leftPaddingDefined = true;
3706                    rightPaddingDefined = true;
3707                    break;
3708                 case com.android.internal.R.styleable.View_paddingLeft:
3709                    leftPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingLeftInitial = leftPadding;
3711                    leftPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingTop:
3714                    topPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingRight:
3717                    rightPadding = a.getDimensionPixelSize(attr, -1);
3718                    mUserPaddingRightInitial = rightPadding;
3719                    rightPaddingDefined = true;
3720                    break;
3721                case com.android.internal.R.styleable.View_paddingBottom:
3722                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3723                    break;
3724                case com.android.internal.R.styleable.View_paddingStart:
3725                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3726                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3727                    break;
3728                case com.android.internal.R.styleable.View_paddingEnd:
3729                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3730                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3731                    break;
3732                case com.android.internal.R.styleable.View_scrollX:
3733                    x = a.getDimensionPixelOffset(attr, 0);
3734                    break;
3735                case com.android.internal.R.styleable.View_scrollY:
3736                    y = a.getDimensionPixelOffset(attr, 0);
3737                    break;
3738                case com.android.internal.R.styleable.View_alpha:
3739                    setAlpha(a.getFloat(attr, 1f));
3740                    break;
3741                case com.android.internal.R.styleable.View_transformPivotX:
3742                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3743                    break;
3744                case com.android.internal.R.styleable.View_transformPivotY:
3745                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3746                    break;
3747                case com.android.internal.R.styleable.View_translationX:
3748                    tx = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_translationY:
3752                    ty = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_translationZ:
3756                    tz = a.getDimensionPixelOffset(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_elevation:
3760                    elevation = a.getDimensionPixelOffset(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotation:
3764                    rotation = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_rotationX:
3768                    rotationX = a.getFloat(attr, 0);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_rotationY:
3772                    rotationY = a.getFloat(attr, 0);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_scaleX:
3776                    sx = a.getFloat(attr, 1f);
3777                    transformSet = true;
3778                    break;
3779                case com.android.internal.R.styleable.View_scaleY:
3780                    sy = a.getFloat(attr, 1f);
3781                    transformSet = true;
3782                    break;
3783                case com.android.internal.R.styleable.View_id:
3784                    mID = a.getResourceId(attr, NO_ID);
3785                    break;
3786                case com.android.internal.R.styleable.View_tag:
3787                    mTag = a.getText(attr);
3788                    break;
3789                case com.android.internal.R.styleable.View_fitsSystemWindows:
3790                    if (a.getBoolean(attr, false)) {
3791                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3792                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3793                    }
3794                    break;
3795                case com.android.internal.R.styleable.View_focusable:
3796                    if (a.getBoolean(attr, false)) {
3797                        viewFlagValues |= FOCUSABLE;
3798                        viewFlagMasks |= FOCUSABLE_MASK;
3799                    }
3800                    break;
3801                case com.android.internal.R.styleable.View_focusableInTouchMode:
3802                    if (a.getBoolean(attr, false)) {
3803                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3804                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3805                    }
3806                    break;
3807                case com.android.internal.R.styleable.View_clickable:
3808                    if (a.getBoolean(attr, false)) {
3809                        viewFlagValues |= CLICKABLE;
3810                        viewFlagMasks |= CLICKABLE;
3811                    }
3812                    break;
3813                case com.android.internal.R.styleable.View_longClickable:
3814                    if (a.getBoolean(attr, false)) {
3815                        viewFlagValues |= LONG_CLICKABLE;
3816                        viewFlagMasks |= LONG_CLICKABLE;
3817                    }
3818                    break;
3819                case com.android.internal.R.styleable.View_saveEnabled:
3820                    if (!a.getBoolean(attr, true)) {
3821                        viewFlagValues |= SAVE_DISABLED;
3822                        viewFlagMasks |= SAVE_DISABLED_MASK;
3823                    }
3824                    break;
3825                case com.android.internal.R.styleable.View_duplicateParentState:
3826                    if (a.getBoolean(attr, false)) {
3827                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3828                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3829                    }
3830                    break;
3831                case com.android.internal.R.styleable.View_visibility:
3832                    final int visibility = a.getInt(attr, 0);
3833                    if (visibility != 0) {
3834                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3835                        viewFlagMasks |= VISIBILITY_MASK;
3836                    }
3837                    break;
3838                case com.android.internal.R.styleable.View_layoutDirection:
3839                    // Clear any layout direction flags (included resolved bits) already set
3840                    mPrivateFlags2 &=
3841                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3842                    // Set the layout direction flags depending on the value of the attribute
3843                    final int layoutDirection = a.getInt(attr, -1);
3844                    final int value = (layoutDirection != -1) ?
3845                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3846                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3847                    break;
3848                case com.android.internal.R.styleable.View_drawingCacheQuality:
3849                    final int cacheQuality = a.getInt(attr, 0);
3850                    if (cacheQuality != 0) {
3851                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3852                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3853                    }
3854                    break;
3855                case com.android.internal.R.styleable.View_contentDescription:
3856                    setContentDescription(a.getString(attr));
3857                    break;
3858                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3859                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3860                    break;
3861                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3862                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3863                    break;
3864                case com.android.internal.R.styleable.View_labelFor:
3865                    setLabelFor(a.getResourceId(attr, NO_ID));
3866                    break;
3867                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3868                    if (!a.getBoolean(attr, true)) {
3869                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3870                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3871                    }
3872                    break;
3873                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3874                    if (!a.getBoolean(attr, true)) {
3875                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3876                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3877                    }
3878                    break;
3879                case R.styleable.View_scrollbars:
3880                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3881                    if (scrollbars != SCROLLBARS_NONE) {
3882                        viewFlagValues |= scrollbars;
3883                        viewFlagMasks |= SCROLLBARS_MASK;
3884                        initializeScrollbars = true;
3885                    }
3886                    break;
3887                //noinspection deprecation
3888                case R.styleable.View_fadingEdge:
3889                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3890                        // Ignore the attribute starting with ICS
3891                        break;
3892                    }
3893                    // With builds < ICS, fall through and apply fading edges
3894                case R.styleable.View_requiresFadingEdge:
3895                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3896                    if (fadingEdge != FADING_EDGE_NONE) {
3897                        viewFlagValues |= fadingEdge;
3898                        viewFlagMasks |= FADING_EDGE_MASK;
3899                        initializeFadingEdgeInternal(a);
3900                    }
3901                    break;
3902                case R.styleable.View_scrollbarStyle:
3903                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3904                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3905                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3906                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3907                    }
3908                    break;
3909                case R.styleable.View_isScrollContainer:
3910                    setScrollContainer = true;
3911                    if (a.getBoolean(attr, false)) {
3912                        setScrollContainer(true);
3913                    }
3914                    break;
3915                case com.android.internal.R.styleable.View_keepScreenOn:
3916                    if (a.getBoolean(attr, false)) {
3917                        viewFlagValues |= KEEP_SCREEN_ON;
3918                        viewFlagMasks |= KEEP_SCREEN_ON;
3919                    }
3920                    break;
3921                case R.styleable.View_filterTouchesWhenObscured:
3922                    if (a.getBoolean(attr, false)) {
3923                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3924                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3925                    }
3926                    break;
3927                case R.styleable.View_nextFocusLeft:
3928                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3929                    break;
3930                case R.styleable.View_nextFocusRight:
3931                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3932                    break;
3933                case R.styleable.View_nextFocusUp:
3934                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3935                    break;
3936                case R.styleable.View_nextFocusDown:
3937                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3938                    break;
3939                case R.styleable.View_nextFocusForward:
3940                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3941                    break;
3942                case R.styleable.View_minWidth:
3943                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3944                    break;
3945                case R.styleable.View_minHeight:
3946                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3947                    break;
3948                case R.styleable.View_onClick:
3949                    if (context.isRestricted()) {
3950                        throw new IllegalStateException("The android:onClick attribute cannot "
3951                                + "be used within a restricted context");
3952                    }
3953
3954                    final String handlerName = a.getString(attr);
3955                    if (handlerName != null) {
3956                        setOnClickListener(new OnClickListener() {
3957                            private Method mHandler;
3958
3959                            public void onClick(View v) {
3960                                if (mHandler == null) {
3961                                    try {
3962                                        mHandler = getContext().getClass().getMethod(handlerName,
3963                                                View.class);
3964                                    } catch (NoSuchMethodException e) {
3965                                        int id = getId();
3966                                        String idText = id == NO_ID ? "" : " with id '"
3967                                                + getContext().getResources().getResourceEntryName(
3968                                                    id) + "'";
3969                                        throw new IllegalStateException("Could not find a method " +
3970                                                handlerName + "(View) in the activity "
3971                                                + getContext().getClass() + " for onClick handler"
3972                                                + " on view " + View.this.getClass() + idText, e);
3973                                    }
3974                                }
3975
3976                                try {
3977                                    mHandler.invoke(getContext(), View.this);
3978                                } catch (IllegalAccessException e) {
3979                                    throw new IllegalStateException("Could not execute non "
3980                                            + "public method of the activity", e);
3981                                } catch (InvocationTargetException e) {
3982                                    throw new IllegalStateException("Could not execute "
3983                                            + "method of the activity", e);
3984                                }
3985                            }
3986                        });
3987                    }
3988                    break;
3989                case R.styleable.View_overScrollMode:
3990                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3991                    break;
3992                case R.styleable.View_verticalScrollbarPosition:
3993                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3994                    break;
3995                case R.styleable.View_layerType:
3996                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3997                    break;
3998                case R.styleable.View_textDirection:
3999                    // Clear any text direction flag already set
4000                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4001                    // Set the text direction flags depending on the value of the attribute
4002                    final int textDirection = a.getInt(attr, -1);
4003                    if (textDirection != -1) {
4004                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4005                    }
4006                    break;
4007                case R.styleable.View_textAlignment:
4008                    // Clear any text alignment flag already set
4009                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4010                    // Set the text alignment flag depending on the value of the attribute
4011                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4012                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4013                    break;
4014                case R.styleable.View_importantForAccessibility:
4015                    setImportantForAccessibility(a.getInt(attr,
4016                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4017                    break;
4018                case R.styleable.View_accessibilityLiveRegion:
4019                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4020                    break;
4021                case R.styleable.View_transitionName:
4022                    setTransitionName(a.getString(attr));
4023                    break;
4024                case R.styleable.View_nestedScrollingEnabled:
4025                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4026                    break;
4027                case R.styleable.View_stateListAnimator:
4028                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4029                            a.getResourceId(attr, 0)));
4030                    break;
4031                case R.styleable.View_backgroundTint:
4032                    // This will get applied later during setBackground().
4033                    if (mBackgroundTint == null) {
4034                        mBackgroundTint = new TintInfo();
4035                    }
4036                    mBackgroundTint.mTintList = a.getColorStateList(
4037                            R.styleable.View_backgroundTint);
4038                    mBackgroundTint.mHasTintList = true;
4039                    break;
4040                case R.styleable.View_backgroundTintMode:
4041                    // This will get applied later during setBackground().
4042                    if (mBackgroundTint == null) {
4043                        mBackgroundTint = new TintInfo();
4044                    }
4045                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4046                            R.styleable.View_backgroundTintMode, -1), null);
4047                    mBackgroundTint.mHasTintMode = true;
4048                    break;
4049                case R.styleable.View_outlineProvider:
4050                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4051                            PROVIDER_BACKGROUND));
4052                    break;
4053            }
4054        }
4055
4056        setOverScrollMode(overScrollMode);
4057
4058        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4059        // the resolved layout direction). Those cached values will be used later during padding
4060        // resolution.
4061        mUserPaddingStart = startPadding;
4062        mUserPaddingEnd = endPadding;
4063
4064        if (background != null) {
4065            setBackground(background);
4066        }
4067
4068        // setBackground above will record that padding is currently provided by the background.
4069        // If we have padding specified via xml, record that here instead and use it.
4070        mLeftPaddingDefined = leftPaddingDefined;
4071        mRightPaddingDefined = rightPaddingDefined;
4072
4073        if (padding >= 0) {
4074            leftPadding = padding;
4075            topPadding = padding;
4076            rightPadding = padding;
4077            bottomPadding = padding;
4078            mUserPaddingLeftInitial = padding;
4079            mUserPaddingRightInitial = padding;
4080        }
4081
4082        if (isRtlCompatibilityMode()) {
4083            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4084            // left / right padding are used if defined (meaning here nothing to do). If they are not
4085            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4086            // start / end and resolve them as left / right (layout direction is not taken into account).
4087            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4088            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4089            // defined.
4090            if (!mLeftPaddingDefined && startPaddingDefined) {
4091                leftPadding = startPadding;
4092            }
4093            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4094            if (!mRightPaddingDefined && endPaddingDefined) {
4095                rightPadding = endPadding;
4096            }
4097            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4098        } else {
4099            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4100            // values defined. Otherwise, left /right values are used.
4101            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4102            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4103            // defined.
4104            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4105
4106            if (mLeftPaddingDefined && !hasRelativePadding) {
4107                mUserPaddingLeftInitial = leftPadding;
4108            }
4109            if (mRightPaddingDefined && !hasRelativePadding) {
4110                mUserPaddingRightInitial = rightPadding;
4111            }
4112        }
4113
4114        internalSetPadding(
4115                mUserPaddingLeftInitial,
4116                topPadding >= 0 ? topPadding : mPaddingTop,
4117                mUserPaddingRightInitial,
4118                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4119
4120        if (viewFlagMasks != 0) {
4121            setFlags(viewFlagValues, viewFlagMasks);
4122        }
4123
4124        if (initializeScrollbars) {
4125            initializeScrollbarsInternal(a);
4126        }
4127
4128        a.recycle();
4129
4130        // Needs to be called after mViewFlags is set
4131        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4132            recomputePadding();
4133        }
4134
4135        if (x != 0 || y != 0) {
4136            scrollTo(x, y);
4137        }
4138
4139        if (transformSet) {
4140            setTranslationX(tx);
4141            setTranslationY(ty);
4142            setTranslationZ(tz);
4143            setElevation(elevation);
4144            setRotation(rotation);
4145            setRotationX(rotationX);
4146            setRotationY(rotationY);
4147            setScaleX(sx);
4148            setScaleY(sy);
4149        }
4150
4151        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4152            setScrollContainer(true);
4153        }
4154
4155        computeOpaqueFlags();
4156    }
4157
4158    /**
4159     * Non-public constructor for use in testing
4160     */
4161    View() {
4162        mResources = null;
4163        mRenderNode = RenderNode.create(getClass().getName(), this);
4164    }
4165
4166    private static SparseArray<String> getAttributeMap() {
4167        if (mAttributeMap == null) {
4168            mAttributeMap = new SparseArray<String>();
4169        }
4170        return mAttributeMap;
4171    }
4172
4173    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4174        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4175        mAttributes = new String[length];
4176
4177        int i = 0;
4178        if (attrs != null) {
4179            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4180                mAttributes[i] = attrs.getAttributeName(i);
4181                mAttributes[i + 1] = attrs.getAttributeValue(i);
4182            }
4183
4184        }
4185
4186        SparseArray<String> attributeMap = getAttributeMap();
4187        for (int j = 0; j < a.length(); ++j) {
4188            if (a.hasValue(j)) {
4189                try {
4190                    int resourceId = a.getResourceId(j, 0);
4191                    if (resourceId == 0) {
4192                        continue;
4193                    }
4194
4195                    String resourceName = attributeMap.get(resourceId);
4196                    if (resourceName == null) {
4197                        resourceName = a.getResources().getResourceName(resourceId);
4198                        attributeMap.put(resourceId, resourceName);
4199                    }
4200
4201                    mAttributes[i] = resourceName;
4202                    mAttributes[i + 1] = a.getText(j).toString();
4203                    i += 2;
4204                } catch (Resources.NotFoundException e) {
4205                    // if we can't get the resource name, we just ignore it
4206                }
4207            }
4208        }
4209    }
4210
4211    public String toString() {
4212        StringBuilder out = new StringBuilder(128);
4213        out.append(getClass().getName());
4214        out.append('{');
4215        out.append(Integer.toHexString(System.identityHashCode(this)));
4216        out.append(' ');
4217        switch (mViewFlags&VISIBILITY_MASK) {
4218            case VISIBLE: out.append('V'); break;
4219            case INVISIBLE: out.append('I'); break;
4220            case GONE: out.append('G'); break;
4221            default: out.append('.'); break;
4222        }
4223        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4224        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4225        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4226        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4227        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4228        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4229        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4230        out.append(' ');
4231        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4232        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4233        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4234        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4235            out.append('p');
4236        } else {
4237            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4238        }
4239        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4240        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4241        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4242        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4243        out.append(' ');
4244        out.append(mLeft);
4245        out.append(',');
4246        out.append(mTop);
4247        out.append('-');
4248        out.append(mRight);
4249        out.append(',');
4250        out.append(mBottom);
4251        final int id = getId();
4252        if (id != NO_ID) {
4253            out.append(" #");
4254            out.append(Integer.toHexString(id));
4255            final Resources r = mResources;
4256            if (Resources.resourceHasPackage(id) && r != null) {
4257                try {
4258                    String pkgname;
4259                    switch (id&0xff000000) {
4260                        case 0x7f000000:
4261                            pkgname="app";
4262                            break;
4263                        case 0x01000000:
4264                            pkgname="android";
4265                            break;
4266                        default:
4267                            pkgname = r.getResourcePackageName(id);
4268                            break;
4269                    }
4270                    String typename = r.getResourceTypeName(id);
4271                    String entryname = r.getResourceEntryName(id);
4272                    out.append(" ");
4273                    out.append(pkgname);
4274                    out.append(":");
4275                    out.append(typename);
4276                    out.append("/");
4277                    out.append(entryname);
4278                } catch (Resources.NotFoundException e) {
4279                }
4280            }
4281        }
4282        out.append("}");
4283        return out.toString();
4284    }
4285
4286    /**
4287     * <p>
4288     * Initializes the fading edges from a given set of styled attributes. This
4289     * method should be called by subclasses that need fading edges and when an
4290     * instance of these subclasses is created programmatically rather than
4291     * being inflated from XML. This method is automatically called when the XML
4292     * is inflated.
4293     * </p>
4294     *
4295     * @param a the styled attributes set to initialize the fading edges from
4296     *
4297     * @removed
4298     */
4299    protected void initializeFadingEdge(TypedArray a) {
4300        // This method probably shouldn't have been included in the SDK to begin with.
4301        // It relies on 'a' having been initialized using an attribute filter array that is
4302        // not publicly available to the SDK. The old method has been renamed
4303        // to initializeFadingEdgeInternal and hidden for framework use only;
4304        // this one initializes using defaults to make it safe to call for apps.
4305
4306        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4307
4308        initializeFadingEdgeInternal(arr);
4309
4310        arr.recycle();
4311    }
4312
4313    /**
4314     * <p>
4315     * Initializes the fading edges from a given set of styled attributes. This
4316     * method should be called by subclasses that need fading edges and when an
4317     * instance of these subclasses is created programmatically rather than
4318     * being inflated from XML. This method is automatically called when the XML
4319     * is inflated.
4320     * </p>
4321     *
4322     * @param a the styled attributes set to initialize the fading edges from
4323     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4324     */
4325    protected void initializeFadingEdgeInternal(TypedArray a) {
4326        initScrollCache();
4327
4328        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4329                R.styleable.View_fadingEdgeLength,
4330                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4331    }
4332
4333    /**
4334     * Returns the size of the vertical faded edges used to indicate that more
4335     * content in this view is visible.
4336     *
4337     * @return The size in pixels of the vertical faded edge or 0 if vertical
4338     *         faded edges are not enabled for this view.
4339     * @attr ref android.R.styleable#View_fadingEdgeLength
4340     */
4341    public int getVerticalFadingEdgeLength() {
4342        if (isVerticalFadingEdgeEnabled()) {
4343            ScrollabilityCache cache = mScrollCache;
4344            if (cache != null) {
4345                return cache.fadingEdgeLength;
4346            }
4347        }
4348        return 0;
4349    }
4350
4351    /**
4352     * Set the size of the faded edge used to indicate that more content in this
4353     * view is available.  Will not change whether the fading edge is enabled; use
4354     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4355     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4356     * for the vertical or horizontal fading edges.
4357     *
4358     * @param length The size in pixels of the faded edge used to indicate that more
4359     *        content in this view is visible.
4360     */
4361    public void setFadingEdgeLength(int length) {
4362        initScrollCache();
4363        mScrollCache.fadingEdgeLength = length;
4364    }
4365
4366    /**
4367     * Returns the size of the horizontal faded edges used to indicate that more
4368     * content in this view is visible.
4369     *
4370     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4371     *         faded edges are not enabled for this view.
4372     * @attr ref android.R.styleable#View_fadingEdgeLength
4373     */
4374    public int getHorizontalFadingEdgeLength() {
4375        if (isHorizontalFadingEdgeEnabled()) {
4376            ScrollabilityCache cache = mScrollCache;
4377            if (cache != null) {
4378                return cache.fadingEdgeLength;
4379            }
4380        }
4381        return 0;
4382    }
4383
4384    /**
4385     * Returns the width of the vertical scrollbar.
4386     *
4387     * @return The width in pixels of the vertical scrollbar or 0 if there
4388     *         is no vertical scrollbar.
4389     */
4390    public int getVerticalScrollbarWidth() {
4391        ScrollabilityCache cache = mScrollCache;
4392        if (cache != null) {
4393            ScrollBarDrawable scrollBar = cache.scrollBar;
4394            if (scrollBar != null) {
4395                int size = scrollBar.getSize(true);
4396                if (size <= 0) {
4397                    size = cache.scrollBarSize;
4398                }
4399                return size;
4400            }
4401            return 0;
4402        }
4403        return 0;
4404    }
4405
4406    /**
4407     * Returns the height of the horizontal scrollbar.
4408     *
4409     * @return The height in pixels of the horizontal scrollbar or 0 if
4410     *         there is no horizontal scrollbar.
4411     */
4412    protected int getHorizontalScrollbarHeight() {
4413        ScrollabilityCache cache = mScrollCache;
4414        if (cache != null) {
4415            ScrollBarDrawable scrollBar = cache.scrollBar;
4416            if (scrollBar != null) {
4417                int size = scrollBar.getSize(false);
4418                if (size <= 0) {
4419                    size = cache.scrollBarSize;
4420                }
4421                return size;
4422            }
4423            return 0;
4424        }
4425        return 0;
4426    }
4427
4428    /**
4429     * <p>
4430     * Initializes the scrollbars from a given set of styled attributes. This
4431     * method should be called by subclasses that need scrollbars and when an
4432     * instance of these subclasses is created programmatically rather than
4433     * being inflated from XML. This method is automatically called when the XML
4434     * is inflated.
4435     * </p>
4436     *
4437     * @param a the styled attributes set to initialize the scrollbars from
4438     *
4439     * @removed
4440     */
4441    protected void initializeScrollbars(TypedArray a) {
4442        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4443        // using the View filter array which is not available to the SDK. As such, internal
4444        // framework usage now uses initializeScrollbarsInternal and we grab a default
4445        // TypedArray with the right filter instead here.
4446        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4447
4448        initializeScrollbarsInternal(arr);
4449
4450        // We ignored the method parameter. Recycle the one we actually did use.
4451        arr.recycle();
4452    }
4453
4454    /**
4455     * <p>
4456     * Initializes the scrollbars from a given set of styled attributes. This
4457     * method should be called by subclasses that need scrollbars and when an
4458     * instance of these subclasses is created programmatically rather than
4459     * being inflated from XML. This method is automatically called when the XML
4460     * is inflated.
4461     * </p>
4462     *
4463     * @param a the styled attributes set to initialize the scrollbars from
4464     * @hide
4465     */
4466    protected void initializeScrollbarsInternal(TypedArray a) {
4467        initScrollCache();
4468
4469        final ScrollabilityCache scrollabilityCache = mScrollCache;
4470
4471        if (scrollabilityCache.scrollBar == null) {
4472            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4473            scrollabilityCache.scrollBar.setCallback(this);
4474            scrollabilityCache.scrollBar.setState(getDrawableState());
4475        }
4476
4477        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4478
4479        if (!fadeScrollbars) {
4480            scrollabilityCache.state = ScrollabilityCache.ON;
4481        }
4482        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4483
4484
4485        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4486                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4487                        .getScrollBarFadeDuration());
4488        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4489                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4490                ViewConfiguration.getScrollDefaultDelay());
4491
4492
4493        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4494                com.android.internal.R.styleable.View_scrollbarSize,
4495                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4496
4497        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4498        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4499
4500        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4501        if (thumb != null) {
4502            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4503        }
4504
4505        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4506                false);
4507        if (alwaysDraw) {
4508            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4509        }
4510
4511        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4512        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4513
4514        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4515        if (thumb != null) {
4516            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4517        }
4518
4519        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4520                false);
4521        if (alwaysDraw) {
4522            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4523        }
4524
4525        // Apply layout direction to the new Drawables if needed
4526        final int layoutDirection = getLayoutDirection();
4527        if (track != null) {
4528            track.setLayoutDirection(layoutDirection);
4529        }
4530        if (thumb != null) {
4531            thumb.setLayoutDirection(layoutDirection);
4532        }
4533
4534        // Re-apply user/background padding so that scrollbar(s) get added
4535        resolvePadding();
4536    }
4537
4538    /**
4539     * <p>
4540     * Initalizes the scrollability cache if necessary.
4541     * </p>
4542     */
4543    private void initScrollCache() {
4544        if (mScrollCache == null) {
4545            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4546        }
4547    }
4548
4549    private ScrollabilityCache getScrollCache() {
4550        initScrollCache();
4551        return mScrollCache;
4552    }
4553
4554    /**
4555     * Set the position of the vertical scroll bar. Should be one of
4556     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4557     * {@link #SCROLLBAR_POSITION_RIGHT}.
4558     *
4559     * @param position Where the vertical scroll bar should be positioned.
4560     */
4561    public void setVerticalScrollbarPosition(int position) {
4562        if (mVerticalScrollbarPosition != position) {
4563            mVerticalScrollbarPosition = position;
4564            computeOpaqueFlags();
4565            resolvePadding();
4566        }
4567    }
4568
4569    /**
4570     * @return The position where the vertical scroll bar will show, if applicable.
4571     * @see #setVerticalScrollbarPosition(int)
4572     */
4573    public int getVerticalScrollbarPosition() {
4574        return mVerticalScrollbarPosition;
4575    }
4576
4577    ListenerInfo getListenerInfo() {
4578        if (mListenerInfo != null) {
4579            return mListenerInfo;
4580        }
4581        mListenerInfo = new ListenerInfo();
4582        return mListenerInfo;
4583    }
4584
4585    /**
4586     * Register a callback to be invoked when the scroll X or Y positions of
4587     * this view change.
4588     * <p>
4589     * <b>Note:</b> Some views handle scrolling independently from View and may
4590     * have their own separate listeners for scroll-type events. For example,
4591     * {@link android.widget.ListView ListView} allows clients to register an
4592     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
4593     * to listen for changes in list scroll position.
4594     *
4595     * @param l The listener to notify when the scroll X or Y position changes.
4596     * @see android.view.View#getScrollX()
4597     * @see android.view.View#getScrollY()
4598     */
4599    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4600        getListenerInfo().mOnScrollChangeListener = l;
4601    }
4602
4603    /**
4604     * Register a callback to be invoked when focus of this view changed.
4605     *
4606     * @param l The callback that will run.
4607     */
4608    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4609        getListenerInfo().mOnFocusChangeListener = l;
4610    }
4611
4612    /**
4613     * Add a listener that will be called when the bounds of the view change due to
4614     * layout processing.
4615     *
4616     * @param listener The listener that will be called when layout bounds change.
4617     */
4618    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4619        ListenerInfo li = getListenerInfo();
4620        if (li.mOnLayoutChangeListeners == null) {
4621            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4622        }
4623        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4624            li.mOnLayoutChangeListeners.add(listener);
4625        }
4626    }
4627
4628    /**
4629     * Remove a listener for layout changes.
4630     *
4631     * @param listener The listener for layout bounds change.
4632     */
4633    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4634        ListenerInfo li = mListenerInfo;
4635        if (li == null || li.mOnLayoutChangeListeners == null) {
4636            return;
4637        }
4638        li.mOnLayoutChangeListeners.remove(listener);
4639    }
4640
4641    /**
4642     * Add a listener for attach state changes.
4643     *
4644     * This listener will be called whenever this view is attached or detached
4645     * from a window. Remove the listener using
4646     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4647     *
4648     * @param listener Listener to attach
4649     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4650     */
4651    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4652        ListenerInfo li = getListenerInfo();
4653        if (li.mOnAttachStateChangeListeners == null) {
4654            li.mOnAttachStateChangeListeners
4655                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4656        }
4657        li.mOnAttachStateChangeListeners.add(listener);
4658    }
4659
4660    /**
4661     * Remove a listener for attach state changes. The listener will receive no further
4662     * notification of window attach/detach events.
4663     *
4664     * @param listener Listener to remove
4665     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4666     */
4667    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4668        ListenerInfo li = mListenerInfo;
4669        if (li == null || li.mOnAttachStateChangeListeners == null) {
4670            return;
4671        }
4672        li.mOnAttachStateChangeListeners.remove(listener);
4673    }
4674
4675    /**
4676     * Returns the focus-change callback registered for this view.
4677     *
4678     * @return The callback, or null if one is not registered.
4679     */
4680    public OnFocusChangeListener getOnFocusChangeListener() {
4681        ListenerInfo li = mListenerInfo;
4682        return li != null ? li.mOnFocusChangeListener : null;
4683    }
4684
4685    /**
4686     * Register a callback to be invoked when this view is clicked. If this view is not
4687     * clickable, it becomes clickable.
4688     *
4689     * @param l The callback that will run
4690     *
4691     * @see #setClickable(boolean)
4692     */
4693    public void setOnClickListener(@Nullable OnClickListener l) {
4694        if (!isClickable()) {
4695            setClickable(true);
4696        }
4697        getListenerInfo().mOnClickListener = l;
4698    }
4699
4700    /**
4701     * Return whether this view has an attached OnClickListener.  Returns
4702     * true if there is a listener, false if there is none.
4703     */
4704    public boolean hasOnClickListeners() {
4705        ListenerInfo li = mListenerInfo;
4706        return (li != null && li.mOnClickListener != null);
4707    }
4708
4709    /**
4710     * Register a callback to be invoked when this view is clicked and held. If this view is not
4711     * long clickable, it becomes long clickable.
4712     *
4713     * @param l The callback that will run
4714     *
4715     * @see #setLongClickable(boolean)
4716     */
4717    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
4718        if (!isLongClickable()) {
4719            setLongClickable(true);
4720        }
4721        getListenerInfo().mOnLongClickListener = l;
4722    }
4723
4724    /**
4725     * Register a callback to be invoked when the context menu for this view is
4726     * being built. If this view is not long clickable, it becomes long clickable.
4727     *
4728     * @param l The callback that will run
4729     *
4730     */
4731    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4732        if (!isLongClickable()) {
4733            setLongClickable(true);
4734        }
4735        getListenerInfo().mOnCreateContextMenuListener = l;
4736    }
4737
4738    /**
4739     * Call this view's OnClickListener, if it is defined.  Performs all normal
4740     * actions associated with clicking: reporting accessibility event, playing
4741     * a sound, etc.
4742     *
4743     * @return True there was an assigned OnClickListener that was called, false
4744     *         otherwise is returned.
4745     */
4746    public boolean performClick() {
4747        final boolean result;
4748        final ListenerInfo li = mListenerInfo;
4749        if (li != null && li.mOnClickListener != null) {
4750            playSoundEffect(SoundEffectConstants.CLICK);
4751            li.mOnClickListener.onClick(this);
4752            result = true;
4753        } else {
4754            result = false;
4755        }
4756
4757        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4758        return result;
4759    }
4760
4761    /**
4762     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4763     * this only calls the listener, and does not do any associated clicking
4764     * actions like reporting an accessibility event.
4765     *
4766     * @return True there was an assigned OnClickListener that was called, false
4767     *         otherwise is returned.
4768     */
4769    public boolean callOnClick() {
4770        ListenerInfo li = mListenerInfo;
4771        if (li != null && li.mOnClickListener != null) {
4772            li.mOnClickListener.onClick(this);
4773            return true;
4774        }
4775        return false;
4776    }
4777
4778    /**
4779     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4780     * OnLongClickListener did not consume the event.
4781     *
4782     * @return True if one of the above receivers consumed the event, false otherwise.
4783     */
4784    public boolean performLongClick() {
4785        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4786
4787        boolean handled = false;
4788        ListenerInfo li = mListenerInfo;
4789        if (li != null && li.mOnLongClickListener != null) {
4790            handled = li.mOnLongClickListener.onLongClick(View.this);
4791        }
4792        if (!handled) {
4793            handled = showContextMenu();
4794        }
4795        if (handled) {
4796            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4797        }
4798        return handled;
4799    }
4800
4801    /**
4802     * Performs button-related actions during a touch down event.
4803     *
4804     * @param event The event.
4805     * @return True if the down was consumed.
4806     *
4807     * @hide
4808     */
4809    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4810        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4811            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4812                return true;
4813            }
4814        }
4815        return false;
4816    }
4817
4818    /**
4819     * Bring up the context menu for this view.
4820     *
4821     * @return Whether a context menu was displayed.
4822     */
4823    public boolean showContextMenu() {
4824        return getParent().showContextMenuForChild(this);
4825    }
4826
4827    /**
4828     * Bring up the context menu for this view, referring to the item under the specified point.
4829     *
4830     * @param x The referenced x coordinate.
4831     * @param y The referenced y coordinate.
4832     * @param metaState The keyboard modifiers that were pressed.
4833     * @return Whether a context menu was displayed.
4834     *
4835     * @hide
4836     */
4837    public boolean showContextMenu(float x, float y, int metaState) {
4838        return showContextMenu();
4839    }
4840
4841    /**
4842     * Start an action mode.
4843     *
4844     * @param callback Callback that will control the lifecycle of the action mode
4845     * @return The new action mode if it is started, null otherwise
4846     *
4847     * @see ActionMode
4848     */
4849    public ActionMode startActionMode(ActionMode.Callback callback) {
4850        ViewParent parent = getParent();
4851        if (parent == null) return null;
4852        return parent.startActionModeForChild(this, callback);
4853    }
4854
4855    /**
4856     * Register a callback to be invoked when a hardware key is pressed in this view.
4857     * Key presses in software input methods will generally not trigger the methods of
4858     * this listener.
4859     * @param l the key listener to attach to this view
4860     */
4861    public void setOnKeyListener(OnKeyListener l) {
4862        getListenerInfo().mOnKeyListener = l;
4863    }
4864
4865    /**
4866     * Register a callback to be invoked when a touch event is sent to this view.
4867     * @param l the touch listener to attach to this view
4868     */
4869    public void setOnTouchListener(OnTouchListener l) {
4870        getListenerInfo().mOnTouchListener = l;
4871    }
4872
4873    /**
4874     * Register a callback to be invoked when a generic motion event is sent to this view.
4875     * @param l the generic motion listener to attach to this view
4876     */
4877    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4878        getListenerInfo().mOnGenericMotionListener = l;
4879    }
4880
4881    /**
4882     * Register a callback to be invoked when a hover event is sent to this view.
4883     * @param l the hover listener to attach to this view
4884     */
4885    public void setOnHoverListener(OnHoverListener l) {
4886        getListenerInfo().mOnHoverListener = l;
4887    }
4888
4889    /**
4890     * Register a drag event listener callback object for this View. The parameter is
4891     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4892     * View, the system calls the
4893     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4894     * @param l An implementation of {@link android.view.View.OnDragListener}.
4895     */
4896    public void setOnDragListener(OnDragListener l) {
4897        getListenerInfo().mOnDragListener = l;
4898    }
4899
4900    /**
4901     * Give this view focus. This will cause
4902     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4903     *
4904     * Note: this does not check whether this {@link View} should get focus, it just
4905     * gives it focus no matter what.  It should only be called internally by framework
4906     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4907     *
4908     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4909     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4910     *        focus moved when requestFocus() is called. It may not always
4911     *        apply, in which case use the default View.FOCUS_DOWN.
4912     * @param previouslyFocusedRect The rectangle of the view that had focus
4913     *        prior in this View's coordinate system.
4914     */
4915    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4916        if (DBG) {
4917            System.out.println(this + " requestFocus()");
4918        }
4919
4920        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4921            mPrivateFlags |= PFLAG_FOCUSED;
4922
4923            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4924
4925            if (mParent != null) {
4926                mParent.requestChildFocus(this, this);
4927            }
4928
4929            if (mAttachInfo != null) {
4930                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4931            }
4932
4933            onFocusChanged(true, direction, previouslyFocusedRect);
4934            refreshDrawableState();
4935        }
4936    }
4937
4938    /**
4939     * Populates <code>outRect</code> with the hotspot bounds. By default,
4940     * the hotspot bounds are identical to the screen bounds.
4941     *
4942     * @param outRect rect to populate with hotspot bounds
4943     * @hide Only for internal use by views and widgets.
4944     */
4945    public void getHotspotBounds(Rect outRect) {
4946        final Drawable background = getBackground();
4947        if (background != null) {
4948            background.getHotspotBounds(outRect);
4949        } else {
4950            getBoundsOnScreen(outRect);
4951        }
4952    }
4953
4954    /**
4955     * Request that a rectangle of this view be visible on the screen,
4956     * scrolling if necessary just enough.
4957     *
4958     * <p>A View should call this if it maintains some notion of which part
4959     * of its content is interesting.  For example, a text editing view
4960     * should call this when its cursor moves.
4961     *
4962     * @param rectangle The rectangle.
4963     * @return Whether any parent scrolled.
4964     */
4965    public boolean requestRectangleOnScreen(Rect rectangle) {
4966        return requestRectangleOnScreen(rectangle, false);
4967    }
4968
4969    /**
4970     * Request that a rectangle of this view be visible on the screen,
4971     * scrolling if necessary just enough.
4972     *
4973     * <p>A View should call this if it maintains some notion of which part
4974     * of its content is interesting.  For example, a text editing view
4975     * should call this when its cursor moves.
4976     *
4977     * <p>When <code>immediate</code> is set to true, scrolling will not be
4978     * animated.
4979     *
4980     * @param rectangle The rectangle.
4981     * @param immediate True to forbid animated scrolling, false otherwise
4982     * @return Whether any parent scrolled.
4983     */
4984    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4985        if (mParent == null) {
4986            return false;
4987        }
4988
4989        View child = this;
4990
4991        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4992        position.set(rectangle);
4993
4994        ViewParent parent = mParent;
4995        boolean scrolled = false;
4996        while (parent != null) {
4997            rectangle.set((int) position.left, (int) position.top,
4998                    (int) position.right, (int) position.bottom);
4999
5000            scrolled |= parent.requestChildRectangleOnScreen(child,
5001                    rectangle, immediate);
5002
5003            if (!child.hasIdentityMatrix()) {
5004                child.getMatrix().mapRect(position);
5005            }
5006
5007            position.offset(child.mLeft, child.mTop);
5008
5009            if (!(parent instanceof View)) {
5010                break;
5011            }
5012
5013            View parentView = (View) parent;
5014
5015            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5016
5017            child = parentView;
5018            parent = child.getParent();
5019        }
5020
5021        return scrolled;
5022    }
5023
5024    /**
5025     * Called when this view wants to give up focus. If focus is cleared
5026     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5027     * <p>
5028     * <strong>Note:</strong> When a View clears focus the framework is trying
5029     * to give focus to the first focusable View from the top. Hence, if this
5030     * View is the first from the top that can take focus, then all callbacks
5031     * related to clearing focus will be invoked after which the framework will
5032     * give focus to this view.
5033     * </p>
5034     */
5035    public void clearFocus() {
5036        if (DBG) {
5037            System.out.println(this + " clearFocus()");
5038        }
5039
5040        clearFocusInternal(null, true, true);
5041    }
5042
5043    /**
5044     * Clears focus from the view, optionally propagating the change up through
5045     * the parent hierarchy and requesting that the root view place new focus.
5046     *
5047     * @param propagate whether to propagate the change up through the parent
5048     *            hierarchy
5049     * @param refocus when propagate is true, specifies whether to request the
5050     *            root view place new focus
5051     */
5052    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5053        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5054            mPrivateFlags &= ~PFLAG_FOCUSED;
5055
5056            if (propagate && mParent != null) {
5057                mParent.clearChildFocus(this);
5058            }
5059
5060            onFocusChanged(false, 0, null);
5061            refreshDrawableState();
5062
5063            if (propagate && (!refocus || !rootViewRequestFocus())) {
5064                notifyGlobalFocusCleared(this);
5065            }
5066        }
5067    }
5068
5069    void notifyGlobalFocusCleared(View oldFocus) {
5070        if (oldFocus != null && mAttachInfo != null) {
5071            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5072        }
5073    }
5074
5075    boolean rootViewRequestFocus() {
5076        final View root = getRootView();
5077        return root != null && root.requestFocus();
5078    }
5079
5080    /**
5081     * Called internally by the view system when a new view is getting focus.
5082     * This is what clears the old focus.
5083     * <p>
5084     * <b>NOTE:</b> The parent view's focused child must be updated manually
5085     * after calling this method. Otherwise, the view hierarchy may be left in
5086     * an inconstent state.
5087     */
5088    void unFocus(View focused) {
5089        if (DBG) {
5090            System.out.println(this + " unFocus()");
5091        }
5092
5093        clearFocusInternal(focused, false, false);
5094    }
5095
5096    /**
5097     * Returns true if this view has focus itself, or is the ancestor of the
5098     * view that has focus.
5099     *
5100     * @return True if this view has or contains focus, false otherwise.
5101     */
5102    @ViewDebug.ExportedProperty(category = "focus")
5103    public boolean hasFocus() {
5104        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5105    }
5106
5107    /**
5108     * Returns true if this view is focusable or if it contains a reachable View
5109     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5110     * is a View whose parents do not block descendants focus.
5111     *
5112     * Only {@link #VISIBLE} views are considered focusable.
5113     *
5114     * @return True if the view is focusable or if the view contains a focusable
5115     *         View, false otherwise.
5116     *
5117     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5118     * @see ViewGroup#getTouchscreenBlocksFocus()
5119     */
5120    public boolean hasFocusable() {
5121        if (!isFocusableInTouchMode()) {
5122            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5123                final ViewGroup g = (ViewGroup) p;
5124                if (g.shouldBlockFocusForTouchscreen()) {
5125                    return false;
5126                }
5127            }
5128        }
5129        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5130    }
5131
5132    /**
5133     * Called by the view system when the focus state of this view changes.
5134     * When the focus change event is caused by directional navigation, direction
5135     * and previouslyFocusedRect provide insight into where the focus is coming from.
5136     * When overriding, be sure to call up through to the super class so that
5137     * the standard focus handling will occur.
5138     *
5139     * @param gainFocus True if the View has focus; false otherwise.
5140     * @param direction The direction focus has moved when requestFocus()
5141     *                  is called to give this view focus. Values are
5142     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5143     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5144     *                  It may not always apply, in which case use the default.
5145     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5146     *        system, of the previously focused view.  If applicable, this will be
5147     *        passed in as finer grained information about where the focus is coming
5148     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5149     */
5150    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5151            @Nullable Rect previouslyFocusedRect) {
5152        if (gainFocus) {
5153            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5154        } else {
5155            notifyViewAccessibilityStateChangedIfNeeded(
5156                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5157        }
5158
5159        InputMethodManager imm = InputMethodManager.peekInstance();
5160        if (!gainFocus) {
5161            if (isPressed()) {
5162                setPressed(false);
5163            }
5164            if (imm != null && mAttachInfo != null
5165                    && mAttachInfo.mHasWindowFocus) {
5166                imm.focusOut(this);
5167            }
5168            onFocusLost();
5169        } else if (imm != null && mAttachInfo != null
5170                && mAttachInfo.mHasWindowFocus) {
5171            imm.focusIn(this);
5172        }
5173
5174        invalidate(true);
5175        ListenerInfo li = mListenerInfo;
5176        if (li != null && li.mOnFocusChangeListener != null) {
5177            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5178        }
5179
5180        if (mAttachInfo != null) {
5181            mAttachInfo.mKeyDispatchState.reset(this);
5182        }
5183    }
5184
5185    /**
5186     * Sends an accessibility event of the given type. If accessibility is
5187     * not enabled this method has no effect. The default implementation calls
5188     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5189     * to populate information about the event source (this View), then calls
5190     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5191     * populate the text content of the event source including its descendants,
5192     * and last calls
5193     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5194     * on its parent to request sending of the event to interested parties.
5195     * <p>
5196     * If an {@link AccessibilityDelegate} has been specified via calling
5197     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5198     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5199     * responsible for handling this call.
5200     * </p>
5201     *
5202     * @param eventType The type of the event to send, as defined by several types from
5203     * {@link android.view.accessibility.AccessibilityEvent}, such as
5204     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5205     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5206     *
5207     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5208     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5209     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5210     * @see AccessibilityDelegate
5211     */
5212    public void sendAccessibilityEvent(int eventType) {
5213        if (mAccessibilityDelegate != null) {
5214            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5215        } else {
5216            sendAccessibilityEventInternal(eventType);
5217        }
5218    }
5219
5220    /**
5221     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5222     * {@link AccessibilityEvent} to make an announcement which is related to some
5223     * sort of a context change for which none of the events representing UI transitions
5224     * is a good fit. For example, announcing a new page in a book. If accessibility
5225     * is not enabled this method does nothing.
5226     *
5227     * @param text The announcement text.
5228     */
5229    public void announceForAccessibility(CharSequence text) {
5230        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5231            AccessibilityEvent event = AccessibilityEvent.obtain(
5232                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5233            onInitializeAccessibilityEvent(event);
5234            event.getText().add(text);
5235            event.setContentDescription(null);
5236            mParent.requestSendAccessibilityEvent(this, event);
5237        }
5238    }
5239
5240    /**
5241     * @see #sendAccessibilityEvent(int)
5242     *
5243     * Note: Called from the default {@link AccessibilityDelegate}.
5244     *
5245     * @hide
5246     */
5247    public void sendAccessibilityEventInternal(int eventType) {
5248        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5249            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5250        }
5251    }
5252
5253    /**
5254     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5255     * takes as an argument an empty {@link AccessibilityEvent} and does not
5256     * perform a check whether accessibility is enabled.
5257     * <p>
5258     * If an {@link AccessibilityDelegate} has been specified via calling
5259     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5260     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5261     * is responsible for handling this call.
5262     * </p>
5263     *
5264     * @param event The event to send.
5265     *
5266     * @see #sendAccessibilityEvent(int)
5267     */
5268    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5269        if (mAccessibilityDelegate != null) {
5270            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5271        } else {
5272            sendAccessibilityEventUncheckedInternal(event);
5273        }
5274    }
5275
5276    /**
5277     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5278     *
5279     * Note: Called from the default {@link AccessibilityDelegate}.
5280     *
5281     * @hide
5282     */
5283    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5284        if (!isShown()) {
5285            return;
5286        }
5287        onInitializeAccessibilityEvent(event);
5288        // Only a subset of accessibility events populates text content.
5289        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5290            dispatchPopulateAccessibilityEvent(event);
5291        }
5292        // In the beginning we called #isShown(), so we know that getParent() is not null.
5293        getParent().requestSendAccessibilityEvent(this, event);
5294    }
5295
5296    /**
5297     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5298     * to its children for adding their text content to the event. Note that the
5299     * event text is populated in a separate dispatch path since we add to the
5300     * event not only the text of the source but also the text of all its descendants.
5301     * A typical implementation will call
5302     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5303     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5304     * on each child. Override this method if custom population of the event text
5305     * content is required.
5306     * <p>
5307     * If an {@link AccessibilityDelegate} has been specified via calling
5308     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5309     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5310     * is responsible for handling this call.
5311     * </p>
5312     * <p>
5313     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5314     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5315     * </p>
5316     *
5317     * @param event The event.
5318     *
5319     * @return True if the event population was completed.
5320     */
5321    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5322        if (mAccessibilityDelegate != null) {
5323            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5324        } else {
5325            return dispatchPopulateAccessibilityEventInternal(event);
5326        }
5327    }
5328
5329    /**
5330     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5331     *
5332     * Note: Called from the default {@link AccessibilityDelegate}.
5333     *
5334     * @hide
5335     */
5336    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5337        onPopulateAccessibilityEvent(event);
5338        return false;
5339    }
5340
5341    /**
5342     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5343     * giving a chance to this View to populate the accessibility event with its
5344     * text content. While this method is free to modify event
5345     * attributes other than text content, doing so should normally be performed in
5346     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5347     * <p>
5348     * Example: Adding formatted date string to an accessibility event in addition
5349     *          to the text added by the super implementation:
5350     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5351     *     super.onPopulateAccessibilityEvent(event);
5352     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5353     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5354     *         mCurrentDate.getTimeInMillis(), flags);
5355     *     event.getText().add(selectedDateUtterance);
5356     * }</pre>
5357     * <p>
5358     * If an {@link AccessibilityDelegate} has been specified via calling
5359     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5360     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5361     * is responsible for handling this call.
5362     * </p>
5363     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5364     * information to the event, in case the default implementation has basic information to add.
5365     * </p>
5366     *
5367     * @param event The accessibility event which to populate.
5368     *
5369     * @see #sendAccessibilityEvent(int)
5370     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5371     */
5372    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5373        if (mAccessibilityDelegate != null) {
5374            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5375        } else {
5376            onPopulateAccessibilityEventInternal(event);
5377        }
5378    }
5379
5380    /**
5381     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5382     *
5383     * Note: Called from the default {@link AccessibilityDelegate}.
5384     *
5385     * @hide
5386     */
5387    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5388    }
5389
5390    /**
5391     * Initializes an {@link AccessibilityEvent} with information about
5392     * this View which is the event source. In other words, the source of
5393     * an accessibility event is the view whose state change triggered firing
5394     * the event.
5395     * <p>
5396     * Example: Setting the password property of an event in addition
5397     *          to properties set by the super implementation:
5398     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5399     *     super.onInitializeAccessibilityEvent(event);
5400     *     event.setPassword(true);
5401     * }</pre>
5402     * <p>
5403     * If an {@link AccessibilityDelegate} has been specified via calling
5404     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5405     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5406     * is responsible for handling this call.
5407     * </p>
5408     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5409     * information to the event, in case the default implementation has basic information to add.
5410     * </p>
5411     * @param event The event to initialize.
5412     *
5413     * @see #sendAccessibilityEvent(int)
5414     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5415     */
5416    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5417        if (mAccessibilityDelegate != null) {
5418            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5419        } else {
5420            onInitializeAccessibilityEventInternal(event);
5421        }
5422    }
5423
5424    /**
5425     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5426     *
5427     * Note: Called from the default {@link AccessibilityDelegate}.
5428     *
5429     * @hide
5430     */
5431    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5432        event.setSource(this);
5433        event.setClassName(getAccessibilityClassName());
5434        event.setPackageName(getContext().getPackageName());
5435        event.setEnabled(isEnabled());
5436        event.setContentDescription(mContentDescription);
5437
5438        switch (event.getEventType()) {
5439            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5440                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5441                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5442                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5443                event.setItemCount(focusablesTempList.size());
5444                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5445                if (mAttachInfo != null) {
5446                    focusablesTempList.clear();
5447                }
5448            } break;
5449            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5450                CharSequence text = getIterableTextForAccessibility();
5451                if (text != null && text.length() > 0) {
5452                    event.setFromIndex(getAccessibilitySelectionStart());
5453                    event.setToIndex(getAccessibilitySelectionEnd());
5454                    event.setItemCount(text.length());
5455                }
5456            } break;
5457        }
5458    }
5459
5460    /**
5461     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5462     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5463     * This method is responsible for obtaining an accessibility node info from a
5464     * pool of reusable instances and calling
5465     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5466     * initialize the former.
5467     * <p>
5468     * Note: The client is responsible for recycling the obtained instance by calling
5469     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5470     * </p>
5471     *
5472     * @return A populated {@link AccessibilityNodeInfo}.
5473     *
5474     * @see AccessibilityNodeInfo
5475     */
5476    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5477        if (mAccessibilityDelegate != null) {
5478            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5479        } else {
5480            return createAccessibilityNodeInfoInternal();
5481        }
5482    }
5483
5484    /**
5485     * @see #createAccessibilityNodeInfo()
5486     *
5487     * @hide
5488     */
5489    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5490        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5491        if (provider != null) {
5492            return provider.createAccessibilityNodeInfo(View.NO_ID);
5493        } else {
5494            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5495            onInitializeAccessibilityNodeInfo(info);
5496            return info;
5497        }
5498    }
5499
5500    /**
5501     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5502     * The base implementation sets:
5503     * <ul>
5504     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5505     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5506     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5507     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5508     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5509     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5510     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5511     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5512     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5513     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5514     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5515     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5516     * </ul>
5517     * <p>
5518     * Subclasses should override this method, call the super implementation,
5519     * and set additional attributes.
5520     * </p>
5521     * <p>
5522     * If an {@link AccessibilityDelegate} has been specified via calling
5523     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5524     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5525     * is responsible for handling this call.
5526     * </p>
5527     *
5528     * @param info The instance to initialize.
5529     */
5530    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5531        if (mAccessibilityDelegate != null) {
5532            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5533        } else {
5534            onInitializeAccessibilityNodeInfoInternal(info);
5535        }
5536    }
5537
5538    /**
5539     * Gets the location of this view in screen coordinates.
5540     *
5541     * @param outRect The output location
5542     * @hide
5543     */
5544    public void getBoundsOnScreen(Rect outRect) {
5545        getBoundsOnScreen(outRect, false);
5546    }
5547
5548    /**
5549     * Gets the location of this view in screen coordinates.
5550     *
5551     * @param outRect The output location
5552     * @param clipToParent Whether to clip child bounds to the parent ones.
5553     * @hide
5554     */
5555    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
5556        if (mAttachInfo == null) {
5557            return;
5558        }
5559
5560        RectF position = mAttachInfo.mTmpTransformRect;
5561        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5562
5563        if (!hasIdentityMatrix()) {
5564            getMatrix().mapRect(position);
5565        }
5566
5567        position.offset(mLeft, mTop);
5568
5569        ViewParent parent = mParent;
5570        while (parent instanceof View) {
5571            View parentView = (View) parent;
5572
5573            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5574
5575            if (clipToParent) {
5576                position.left = Math.max(position.left, 0);
5577                position.top = Math.max(position.top, 0);
5578                position.right = Math.min(position.right, parentView.getWidth());
5579                position.bottom = Math.min(position.bottom, parentView.getHeight());
5580            }
5581
5582            if (!parentView.hasIdentityMatrix()) {
5583                parentView.getMatrix().mapRect(position);
5584            }
5585
5586            position.offset(parentView.mLeft, parentView.mTop);
5587
5588            parent = parentView.mParent;
5589        }
5590
5591        if (parent instanceof ViewRootImpl) {
5592            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5593            position.offset(0, -viewRootImpl.mCurScrollY);
5594        }
5595
5596        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5597
5598        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5599                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5600    }
5601
5602    /**
5603     * Return the class name of this object to be used for accessibility purposes.
5604     * Subclasses should only override this if they are implementing something that
5605     * should be seen as a completely new class of view when used by accessibility,
5606     * unrelated to the class it is deriving from.  This is used to fill in
5607     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
5608     */
5609    public CharSequence getAccessibilityClassName() {
5610        return View.class.getName();
5611    }
5612
5613    /**
5614     * Called when assist data is being retrieved from a view as part of
5615     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
5616     * @param data
5617     * @param extras
5618     */
5619    public void onProvideAssistData(ViewAssistData data, Bundle extras) {
5620    }
5621
5622    /**
5623     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5624     *
5625     * Note: Called from the default {@link AccessibilityDelegate}.
5626     *
5627     * @hide
5628     */
5629    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5630        Rect bounds = mAttachInfo.mTmpInvalRect;
5631
5632        getDrawingRect(bounds);
5633        info.setBoundsInParent(bounds);
5634
5635        getBoundsOnScreen(bounds, true);
5636        info.setBoundsInScreen(bounds);
5637
5638        ViewParent parent = getParentForAccessibility();
5639        if (parent instanceof View) {
5640            info.setParent((View) parent);
5641        }
5642
5643        if (mID != View.NO_ID) {
5644            View rootView = getRootView();
5645            if (rootView == null) {
5646                rootView = this;
5647            }
5648
5649            View label = rootView.findLabelForView(this, mID);
5650            if (label != null) {
5651                info.setLabeledBy(label);
5652            }
5653
5654            if ((mAttachInfo.mAccessibilityFetchFlags
5655                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5656                    && Resources.resourceHasPackage(mID)) {
5657                try {
5658                    String viewId = getResources().getResourceName(mID);
5659                    info.setViewIdResourceName(viewId);
5660                } catch (Resources.NotFoundException nfe) {
5661                    /* ignore */
5662                }
5663            }
5664        }
5665
5666        if (mLabelForId != View.NO_ID) {
5667            View rootView = getRootView();
5668            if (rootView == null) {
5669                rootView = this;
5670            }
5671            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5672            if (labeled != null) {
5673                info.setLabelFor(labeled);
5674            }
5675        }
5676
5677        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5678            View rootView = getRootView();
5679            if (rootView == null) {
5680                rootView = this;
5681            }
5682            View next = rootView.findViewInsideOutShouldExist(this,
5683                    mAccessibilityTraversalBeforeId);
5684            if (next != null) {
5685                info.setTraversalBefore(next);
5686            }
5687        }
5688
5689        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5690            View rootView = getRootView();
5691            if (rootView == null) {
5692                rootView = this;
5693            }
5694            View next = rootView.findViewInsideOutShouldExist(this,
5695                    mAccessibilityTraversalAfterId);
5696            if (next != null) {
5697                info.setTraversalAfter(next);
5698            }
5699        }
5700
5701        info.setVisibleToUser(isVisibleToUser());
5702
5703        info.setPackageName(mContext.getPackageName());
5704        info.setClassName(getAccessibilityClassName());
5705        info.setContentDescription(getContentDescription());
5706
5707        info.setEnabled(isEnabled());
5708        info.setClickable(isClickable());
5709        info.setFocusable(isFocusable());
5710        info.setFocused(isFocused());
5711        info.setAccessibilityFocused(isAccessibilityFocused());
5712        info.setSelected(isSelected());
5713        info.setLongClickable(isLongClickable());
5714        info.setLiveRegion(getAccessibilityLiveRegion());
5715
5716        // TODO: These make sense only if we are in an AdapterView but all
5717        // views can be selected. Maybe from accessibility perspective
5718        // we should report as selectable view in an AdapterView.
5719        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5720        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5721
5722        if (isFocusable()) {
5723            if (isFocused()) {
5724                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5725            } else {
5726                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5727            }
5728        }
5729
5730        if (!isAccessibilityFocused()) {
5731            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5732        } else {
5733            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5734        }
5735
5736        if (isClickable() && isEnabled()) {
5737            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5738        }
5739
5740        if (isLongClickable() && isEnabled()) {
5741            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5742        }
5743
5744        CharSequence text = getIterableTextForAccessibility();
5745        if (text != null && text.length() > 0) {
5746            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5747
5748            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5749            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5750            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5751            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5752                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5753                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5754        }
5755    }
5756
5757    private View findLabelForView(View view, int labeledId) {
5758        if (mMatchLabelForPredicate == null) {
5759            mMatchLabelForPredicate = new MatchLabelForPredicate();
5760        }
5761        mMatchLabelForPredicate.mLabeledId = labeledId;
5762        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5763    }
5764
5765    /**
5766     * Computes whether this view is visible to the user. Such a view is
5767     * attached, visible, all its predecessors are visible, it is not clipped
5768     * entirely by its predecessors, and has an alpha greater than zero.
5769     *
5770     * @return Whether the view is visible on the screen.
5771     *
5772     * @hide
5773     */
5774    protected boolean isVisibleToUser() {
5775        return isVisibleToUser(null);
5776    }
5777
5778    /**
5779     * Computes whether the given portion of this view is visible to the user.
5780     * Such a view is attached, visible, all its predecessors are visible,
5781     * has an alpha greater than zero, and the specified portion is not
5782     * clipped entirely by its predecessors.
5783     *
5784     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5785     *                    <code>null</code>, and the entire view will be tested in this case.
5786     *                    When <code>true</code> is returned by the function, the actual visible
5787     *                    region will be stored in this parameter; that is, if boundInView is fully
5788     *                    contained within the view, no modification will be made, otherwise regions
5789     *                    outside of the visible area of the view will be clipped.
5790     *
5791     * @return Whether the specified portion of the view is visible on the screen.
5792     *
5793     * @hide
5794     */
5795    protected boolean isVisibleToUser(Rect boundInView) {
5796        if (mAttachInfo != null) {
5797            // Attached to invisible window means this view is not visible.
5798            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5799                return false;
5800            }
5801            // An invisible predecessor or one with alpha zero means
5802            // that this view is not visible to the user.
5803            Object current = this;
5804            while (current instanceof View) {
5805                View view = (View) current;
5806                // We have attach info so this view is attached and there is no
5807                // need to check whether we reach to ViewRootImpl on the way up.
5808                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5809                        view.getVisibility() != VISIBLE) {
5810                    return false;
5811                }
5812                current = view.mParent;
5813            }
5814            // Check if the view is entirely covered by its predecessors.
5815            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5816            Point offset = mAttachInfo.mPoint;
5817            if (!getGlobalVisibleRect(visibleRect, offset)) {
5818                return false;
5819            }
5820            // Check if the visible portion intersects the rectangle of interest.
5821            if (boundInView != null) {
5822                visibleRect.offset(-offset.x, -offset.y);
5823                return boundInView.intersect(visibleRect);
5824            }
5825            return true;
5826        }
5827        return false;
5828    }
5829
5830    /**
5831     * Returns the delegate for implementing accessibility support via
5832     * composition. For more details see {@link AccessibilityDelegate}.
5833     *
5834     * @return The delegate, or null if none set.
5835     *
5836     * @hide
5837     */
5838    public AccessibilityDelegate getAccessibilityDelegate() {
5839        return mAccessibilityDelegate;
5840    }
5841
5842    /**
5843     * Sets a delegate for implementing accessibility support via composition as
5844     * opposed to inheritance. The delegate's primary use is for implementing
5845     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5846     *
5847     * @param delegate The delegate instance.
5848     *
5849     * @see AccessibilityDelegate
5850     */
5851    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5852        mAccessibilityDelegate = delegate;
5853    }
5854
5855    /**
5856     * Gets the provider for managing a virtual view hierarchy rooted at this View
5857     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5858     * that explore the window content.
5859     * <p>
5860     * If this method returns an instance, this instance is responsible for managing
5861     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5862     * View including the one representing the View itself. Similarly the returned
5863     * instance is responsible for performing accessibility actions on any virtual
5864     * view or the root view itself.
5865     * </p>
5866     * <p>
5867     * If an {@link AccessibilityDelegate} has been specified via calling
5868     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5869     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5870     * is responsible for handling this call.
5871     * </p>
5872     *
5873     * @return The provider.
5874     *
5875     * @see AccessibilityNodeProvider
5876     */
5877    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5878        if (mAccessibilityDelegate != null) {
5879            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5880        } else {
5881            return null;
5882        }
5883    }
5884
5885    /**
5886     * Gets the unique identifier of this view on the screen for accessibility purposes.
5887     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5888     *
5889     * @return The view accessibility id.
5890     *
5891     * @hide
5892     */
5893    public int getAccessibilityViewId() {
5894        if (mAccessibilityViewId == NO_ID) {
5895            mAccessibilityViewId = sNextAccessibilityViewId++;
5896        }
5897        return mAccessibilityViewId;
5898    }
5899
5900    /**
5901     * Gets the unique identifier of the window in which this View reseides.
5902     *
5903     * @return The window accessibility id.
5904     *
5905     * @hide
5906     */
5907    public int getAccessibilityWindowId() {
5908        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5909                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5910    }
5911
5912    /**
5913     * Gets the {@link View} description. It briefly describes the view and is
5914     * primarily used for accessibility support. Set this property to enable
5915     * better accessibility support for your application. This is especially
5916     * true for views that do not have textual representation (For example,
5917     * ImageButton).
5918     *
5919     * @return The content description.
5920     *
5921     * @attr ref android.R.styleable#View_contentDescription
5922     */
5923    @ViewDebug.ExportedProperty(category = "accessibility")
5924    public CharSequence getContentDescription() {
5925        return mContentDescription;
5926    }
5927
5928    /**
5929     * Sets the {@link View} description. It briefly describes the view and is
5930     * primarily used for accessibility support. Set this property to enable
5931     * better accessibility support for your application. This is especially
5932     * true for views that do not have textual representation (For example,
5933     * ImageButton).
5934     *
5935     * @param contentDescription The content description.
5936     *
5937     * @attr ref android.R.styleable#View_contentDescription
5938     */
5939    @RemotableViewMethod
5940    public void setContentDescription(CharSequence contentDescription) {
5941        if (mContentDescription == null) {
5942            if (contentDescription == null) {
5943                return;
5944            }
5945        } else if (mContentDescription.equals(contentDescription)) {
5946            return;
5947        }
5948        mContentDescription = contentDescription;
5949        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5950        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5951            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5952            notifySubtreeAccessibilityStateChangedIfNeeded();
5953        } else {
5954            notifyViewAccessibilityStateChangedIfNeeded(
5955                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5956        }
5957    }
5958
5959    /**
5960     * Sets the id of a view before which this one is visited in accessibility traversal.
5961     * A screen-reader must visit the content of this view before the content of the one
5962     * it precedes. For example, if view B is set to be before view A, then a screen-reader
5963     * will traverse the entire content of B before traversing the entire content of A,
5964     * regardles of what traversal strategy it is using.
5965     * <p>
5966     * Views that do not have specified before/after relationships are traversed in order
5967     * determined by the screen-reader.
5968     * </p>
5969     * <p>
5970     * Setting that this view is before a view that is not important for accessibility
5971     * or if this view is not important for accessibility will have no effect as the
5972     * screen-reader is not aware of unimportant views.
5973     * </p>
5974     *
5975     * @param beforeId The id of a view this one precedes in accessibility traversal.
5976     *
5977     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
5978     *
5979     * @see #setImportantForAccessibility(int)
5980     */
5981    @RemotableViewMethod
5982    public void setAccessibilityTraversalBefore(int beforeId) {
5983        if (mAccessibilityTraversalBeforeId == beforeId) {
5984            return;
5985        }
5986        mAccessibilityTraversalBeforeId = beforeId;
5987        notifyViewAccessibilityStateChangedIfNeeded(
5988                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5989    }
5990
5991    /**
5992     * Gets the id of a view before which this one is visited in accessibility traversal.
5993     *
5994     * @return The id of a view this one precedes in accessibility traversal if
5995     *         specified, otherwise {@link #NO_ID}.
5996     *
5997     * @see #setAccessibilityTraversalBefore(int)
5998     */
5999    public int getAccessibilityTraversalBefore() {
6000        return mAccessibilityTraversalBeforeId;
6001    }
6002
6003    /**
6004     * Sets the id of a view after which this one is visited in accessibility traversal.
6005     * A screen-reader must visit the content of the other view before the content of this
6006     * one. For example, if view B is set to be after view A, then a screen-reader
6007     * will traverse the entire content of A before traversing the entire content of B,
6008     * regardles of what traversal strategy it is using.
6009     * <p>
6010     * Views that do not have specified before/after relationships are traversed in order
6011     * determined by the screen-reader.
6012     * </p>
6013     * <p>
6014     * Setting that this view is after a view that is not important for accessibility
6015     * or if this view is not important for accessibility will have no effect as the
6016     * screen-reader is not aware of unimportant views.
6017     * </p>
6018     *
6019     * @param afterId The id of a view this one succedees in accessibility traversal.
6020     *
6021     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6022     *
6023     * @see #setImportantForAccessibility(int)
6024     */
6025    @RemotableViewMethod
6026    public void setAccessibilityTraversalAfter(int afterId) {
6027        if (mAccessibilityTraversalAfterId == afterId) {
6028            return;
6029        }
6030        mAccessibilityTraversalAfterId = afterId;
6031        notifyViewAccessibilityStateChangedIfNeeded(
6032                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6033    }
6034
6035    /**
6036     * Gets the id of a view after which this one is visited in accessibility traversal.
6037     *
6038     * @return The id of a view this one succeedes in accessibility traversal if
6039     *         specified, otherwise {@link #NO_ID}.
6040     *
6041     * @see #setAccessibilityTraversalAfter(int)
6042     */
6043    public int getAccessibilityTraversalAfter() {
6044        return mAccessibilityTraversalAfterId;
6045    }
6046
6047    /**
6048     * Gets the id of a view for which this view serves as a label for
6049     * accessibility purposes.
6050     *
6051     * @return The labeled view id.
6052     */
6053    @ViewDebug.ExportedProperty(category = "accessibility")
6054    public int getLabelFor() {
6055        return mLabelForId;
6056    }
6057
6058    /**
6059     * Sets the id of a view for which this view serves as a label for
6060     * accessibility purposes.
6061     *
6062     * @param id The labeled view id.
6063     */
6064    @RemotableViewMethod
6065    public void setLabelFor(int id) {
6066        if (mLabelForId == id) {
6067            return;
6068        }
6069        mLabelForId = id;
6070        if (mLabelForId != View.NO_ID
6071                && mID == View.NO_ID) {
6072            mID = generateViewId();
6073        }
6074        notifyViewAccessibilityStateChangedIfNeeded(
6075                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6076    }
6077
6078    /**
6079     * Invoked whenever this view loses focus, either by losing window focus or by losing
6080     * focus within its window. This method can be used to clear any state tied to the
6081     * focus. For instance, if a button is held pressed with the trackball and the window
6082     * loses focus, this method can be used to cancel the press.
6083     *
6084     * Subclasses of View overriding this method should always call super.onFocusLost().
6085     *
6086     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6087     * @see #onWindowFocusChanged(boolean)
6088     *
6089     * @hide pending API council approval
6090     */
6091    protected void onFocusLost() {
6092        resetPressedState();
6093    }
6094
6095    private void resetPressedState() {
6096        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6097            return;
6098        }
6099
6100        if (isPressed()) {
6101            setPressed(false);
6102
6103            if (!mHasPerformedLongPress) {
6104                removeLongPressCallback();
6105            }
6106        }
6107    }
6108
6109    /**
6110     * Returns true if this view has focus
6111     *
6112     * @return True if this view has focus, false otherwise.
6113     */
6114    @ViewDebug.ExportedProperty(category = "focus")
6115    public boolean isFocused() {
6116        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6117    }
6118
6119    /**
6120     * Find the view in the hierarchy rooted at this view that currently has
6121     * focus.
6122     *
6123     * @return The view that currently has focus, or null if no focused view can
6124     *         be found.
6125     */
6126    public View findFocus() {
6127        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6128    }
6129
6130    /**
6131     * Indicates whether this view is one of the set of scrollable containers in
6132     * its window.
6133     *
6134     * @return whether this view is one of the set of scrollable containers in
6135     * its window
6136     *
6137     * @attr ref android.R.styleable#View_isScrollContainer
6138     */
6139    public boolean isScrollContainer() {
6140        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6141    }
6142
6143    /**
6144     * Change whether this view is one of the set of scrollable containers in
6145     * its window.  This will be used to determine whether the window can
6146     * resize or must pan when a soft input area is open -- scrollable
6147     * containers allow the window to use resize mode since the container
6148     * will appropriately shrink.
6149     *
6150     * @attr ref android.R.styleable#View_isScrollContainer
6151     */
6152    public void setScrollContainer(boolean isScrollContainer) {
6153        if (isScrollContainer) {
6154            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6155                mAttachInfo.mScrollContainers.add(this);
6156                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6157            }
6158            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6159        } else {
6160            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6161                mAttachInfo.mScrollContainers.remove(this);
6162            }
6163            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6164        }
6165    }
6166
6167    /**
6168     * Returns the quality of the drawing cache.
6169     *
6170     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6171     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6172     *
6173     * @see #setDrawingCacheQuality(int)
6174     * @see #setDrawingCacheEnabled(boolean)
6175     * @see #isDrawingCacheEnabled()
6176     *
6177     * @attr ref android.R.styleable#View_drawingCacheQuality
6178     */
6179    @DrawingCacheQuality
6180    public int getDrawingCacheQuality() {
6181        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6182    }
6183
6184    /**
6185     * Set the drawing cache quality of this view. This value is used only when the
6186     * drawing cache is enabled
6187     *
6188     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6189     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6190     *
6191     * @see #getDrawingCacheQuality()
6192     * @see #setDrawingCacheEnabled(boolean)
6193     * @see #isDrawingCacheEnabled()
6194     *
6195     * @attr ref android.R.styleable#View_drawingCacheQuality
6196     */
6197    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6198        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6199    }
6200
6201    /**
6202     * Returns whether the screen should remain on, corresponding to the current
6203     * value of {@link #KEEP_SCREEN_ON}.
6204     *
6205     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6206     *
6207     * @see #setKeepScreenOn(boolean)
6208     *
6209     * @attr ref android.R.styleable#View_keepScreenOn
6210     */
6211    public boolean getKeepScreenOn() {
6212        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6213    }
6214
6215    /**
6216     * Controls whether the screen should remain on, modifying the
6217     * value of {@link #KEEP_SCREEN_ON}.
6218     *
6219     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6220     *
6221     * @see #getKeepScreenOn()
6222     *
6223     * @attr ref android.R.styleable#View_keepScreenOn
6224     */
6225    public void setKeepScreenOn(boolean keepScreenOn) {
6226        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6227    }
6228
6229    /**
6230     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6231     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6232     *
6233     * @attr ref android.R.styleable#View_nextFocusLeft
6234     */
6235    public int getNextFocusLeftId() {
6236        return mNextFocusLeftId;
6237    }
6238
6239    /**
6240     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6241     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6242     * decide automatically.
6243     *
6244     * @attr ref android.R.styleable#View_nextFocusLeft
6245     */
6246    public void setNextFocusLeftId(int nextFocusLeftId) {
6247        mNextFocusLeftId = nextFocusLeftId;
6248    }
6249
6250    /**
6251     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6252     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6253     *
6254     * @attr ref android.R.styleable#View_nextFocusRight
6255     */
6256    public int getNextFocusRightId() {
6257        return mNextFocusRightId;
6258    }
6259
6260    /**
6261     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6262     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6263     * decide automatically.
6264     *
6265     * @attr ref android.R.styleable#View_nextFocusRight
6266     */
6267    public void setNextFocusRightId(int nextFocusRightId) {
6268        mNextFocusRightId = nextFocusRightId;
6269    }
6270
6271    /**
6272     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6273     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6274     *
6275     * @attr ref android.R.styleable#View_nextFocusUp
6276     */
6277    public int getNextFocusUpId() {
6278        return mNextFocusUpId;
6279    }
6280
6281    /**
6282     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6283     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6284     * decide automatically.
6285     *
6286     * @attr ref android.R.styleable#View_nextFocusUp
6287     */
6288    public void setNextFocusUpId(int nextFocusUpId) {
6289        mNextFocusUpId = nextFocusUpId;
6290    }
6291
6292    /**
6293     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6294     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6295     *
6296     * @attr ref android.R.styleable#View_nextFocusDown
6297     */
6298    public int getNextFocusDownId() {
6299        return mNextFocusDownId;
6300    }
6301
6302    /**
6303     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6304     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6305     * decide automatically.
6306     *
6307     * @attr ref android.R.styleable#View_nextFocusDown
6308     */
6309    public void setNextFocusDownId(int nextFocusDownId) {
6310        mNextFocusDownId = nextFocusDownId;
6311    }
6312
6313    /**
6314     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6315     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6316     *
6317     * @attr ref android.R.styleable#View_nextFocusForward
6318     */
6319    public int getNextFocusForwardId() {
6320        return mNextFocusForwardId;
6321    }
6322
6323    /**
6324     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6325     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6326     * decide automatically.
6327     *
6328     * @attr ref android.R.styleable#View_nextFocusForward
6329     */
6330    public void setNextFocusForwardId(int nextFocusForwardId) {
6331        mNextFocusForwardId = nextFocusForwardId;
6332    }
6333
6334    /**
6335     * Returns the visibility of this view and all of its ancestors
6336     *
6337     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6338     */
6339    public boolean isShown() {
6340        View current = this;
6341        //noinspection ConstantConditions
6342        do {
6343            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6344                return false;
6345            }
6346            ViewParent parent = current.mParent;
6347            if (parent == null) {
6348                return false; // We are not attached to the view root
6349            }
6350            if (!(parent instanceof View)) {
6351                return true;
6352            }
6353            current = (View) parent;
6354        } while (current != null);
6355
6356        return false;
6357    }
6358
6359    /**
6360     * Called by the view hierarchy when the content insets for a window have
6361     * changed, to allow it to adjust its content to fit within those windows.
6362     * The content insets tell you the space that the status bar, input method,
6363     * and other system windows infringe on the application's window.
6364     *
6365     * <p>You do not normally need to deal with this function, since the default
6366     * window decoration given to applications takes care of applying it to the
6367     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6368     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6369     * and your content can be placed under those system elements.  You can then
6370     * use this method within your view hierarchy if you have parts of your UI
6371     * which you would like to ensure are not being covered.
6372     *
6373     * <p>The default implementation of this method simply applies the content
6374     * insets to the view's padding, consuming that content (modifying the
6375     * insets to be 0), and returning true.  This behavior is off by default, but can
6376     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6377     *
6378     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6379     * insets object is propagated down the hierarchy, so any changes made to it will
6380     * be seen by all following views (including potentially ones above in
6381     * the hierarchy since this is a depth-first traversal).  The first view
6382     * that returns true will abort the entire traversal.
6383     *
6384     * <p>The default implementation works well for a situation where it is
6385     * used with a container that covers the entire window, allowing it to
6386     * apply the appropriate insets to its content on all edges.  If you need
6387     * a more complicated layout (such as two different views fitting system
6388     * windows, one on the top of the window, and one on the bottom),
6389     * you can override the method and handle the insets however you would like.
6390     * Note that the insets provided by the framework are always relative to the
6391     * far edges of the window, not accounting for the location of the called view
6392     * within that window.  (In fact when this method is called you do not yet know
6393     * where the layout will place the view, as it is done before layout happens.)
6394     *
6395     * <p>Note: unlike many View methods, there is no dispatch phase to this
6396     * call.  If you are overriding it in a ViewGroup and want to allow the
6397     * call to continue to your children, you must be sure to call the super
6398     * implementation.
6399     *
6400     * <p>Here is a sample layout that makes use of fitting system windows
6401     * to have controls for a video view placed inside of the window decorations
6402     * that it hides and shows.  This can be used with code like the second
6403     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6404     *
6405     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6406     *
6407     * @param insets Current content insets of the window.  Prior to
6408     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6409     * the insets or else you and Android will be unhappy.
6410     *
6411     * @return {@code true} if this view applied the insets and it should not
6412     * continue propagating further down the hierarchy, {@code false} otherwise.
6413     * @see #getFitsSystemWindows()
6414     * @see #setFitsSystemWindows(boolean)
6415     * @see #setSystemUiVisibility(int)
6416     *
6417     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6418     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6419     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6420     * to implement handling their own insets.
6421     */
6422    protected boolean fitSystemWindows(Rect insets) {
6423        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6424            if (insets == null) {
6425                // Null insets by definition have already been consumed.
6426                // This call cannot apply insets since there are none to apply,
6427                // so return false.
6428                return false;
6429            }
6430            // If we're not in the process of dispatching the newer apply insets call,
6431            // that means we're not in the compatibility path. Dispatch into the newer
6432            // apply insets path and take things from there.
6433            try {
6434                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6435                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6436            } finally {
6437                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6438            }
6439        } else {
6440            // We're being called from the newer apply insets path.
6441            // Perform the standard fallback behavior.
6442            return fitSystemWindowsInt(insets);
6443        }
6444    }
6445
6446    private boolean fitSystemWindowsInt(Rect insets) {
6447        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6448            mUserPaddingStart = UNDEFINED_PADDING;
6449            mUserPaddingEnd = UNDEFINED_PADDING;
6450            Rect localInsets = sThreadLocal.get();
6451            if (localInsets == null) {
6452                localInsets = new Rect();
6453                sThreadLocal.set(localInsets);
6454            }
6455            boolean res = computeFitSystemWindows(insets, localInsets);
6456            mUserPaddingLeftInitial = localInsets.left;
6457            mUserPaddingRightInitial = localInsets.right;
6458            internalSetPadding(localInsets.left, localInsets.top,
6459                    localInsets.right, localInsets.bottom);
6460            return res;
6461        }
6462        return false;
6463    }
6464
6465    /**
6466     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6467     *
6468     * <p>This method should be overridden by views that wish to apply a policy different from or
6469     * in addition to the default behavior. Clients that wish to force a view subtree
6470     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6471     *
6472     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6473     * it will be called during dispatch instead of this method. The listener may optionally
6474     * call this method from its own implementation if it wishes to apply the view's default
6475     * insets policy in addition to its own.</p>
6476     *
6477     * <p>Implementations of this method should either return the insets parameter unchanged
6478     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6479     * that this view applied itself. This allows new inset types added in future platform
6480     * versions to pass through existing implementations unchanged without being erroneously
6481     * consumed.</p>
6482     *
6483     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6484     * property is set then the view will consume the system window insets and apply them
6485     * as padding for the view.</p>
6486     *
6487     * @param insets Insets to apply
6488     * @return The supplied insets with any applied insets consumed
6489     */
6490    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6491        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6492            // We weren't called from within a direct call to fitSystemWindows,
6493            // call into it as a fallback in case we're in a class that overrides it
6494            // and has logic to perform.
6495            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6496                return insets.consumeSystemWindowInsets();
6497            }
6498        } else {
6499            // We were called from within a direct call to fitSystemWindows.
6500            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6501                return insets.consumeSystemWindowInsets();
6502            }
6503        }
6504        return insets;
6505    }
6506
6507    /**
6508     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6509     * window insets to this view. The listener's
6510     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6511     * method will be called instead of the view's
6512     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6513     *
6514     * @param listener Listener to set
6515     *
6516     * @see #onApplyWindowInsets(WindowInsets)
6517     */
6518    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6519        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6520    }
6521
6522    /**
6523     * Request to apply the given window insets to this view or another view in its subtree.
6524     *
6525     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6526     * obscured by window decorations or overlays. This can include the status and navigation bars,
6527     * action bars, input methods and more. New inset categories may be added in the future.
6528     * The method returns the insets provided minus any that were applied by this view or its
6529     * children.</p>
6530     *
6531     * <p>Clients wishing to provide custom behavior should override the
6532     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6533     * {@link OnApplyWindowInsetsListener} via the
6534     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6535     * method.</p>
6536     *
6537     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6538     * </p>
6539     *
6540     * @param insets Insets to apply
6541     * @return The provided insets minus the insets that were consumed
6542     */
6543    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6544        try {
6545            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6546            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6547                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6548            } else {
6549                return onApplyWindowInsets(insets);
6550            }
6551        } finally {
6552            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6553        }
6554    }
6555
6556    /**
6557     * @hide Compute the insets that should be consumed by this view and the ones
6558     * that should propagate to those under it.
6559     */
6560    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6561        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6562                || mAttachInfo == null
6563                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6564                        && !mAttachInfo.mOverscanRequested)) {
6565            outLocalInsets.set(inoutInsets);
6566            inoutInsets.set(0, 0, 0, 0);
6567            return true;
6568        } else {
6569            // The application wants to take care of fitting system window for
6570            // the content...  however we still need to take care of any overscan here.
6571            final Rect overscan = mAttachInfo.mOverscanInsets;
6572            outLocalInsets.set(overscan);
6573            inoutInsets.left -= overscan.left;
6574            inoutInsets.top -= overscan.top;
6575            inoutInsets.right -= overscan.right;
6576            inoutInsets.bottom -= overscan.bottom;
6577            return false;
6578        }
6579    }
6580
6581    /**
6582     * Compute insets that should be consumed by this view and the ones that should propagate
6583     * to those under it.
6584     *
6585     * @param in Insets currently being processed by this View, likely received as a parameter
6586     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6587     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6588     *                       by this view
6589     * @return Insets that should be passed along to views under this one
6590     */
6591    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6592        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6593                || mAttachInfo == null
6594                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6595            outLocalInsets.set(in.getSystemWindowInsets());
6596            return in.consumeSystemWindowInsets();
6597        } else {
6598            outLocalInsets.set(0, 0, 0, 0);
6599            return in;
6600        }
6601    }
6602
6603    /**
6604     * Sets whether or not this view should account for system screen decorations
6605     * such as the status bar and inset its content; that is, controlling whether
6606     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6607     * executed.  See that method for more details.
6608     *
6609     * <p>Note that if you are providing your own implementation of
6610     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6611     * flag to true -- your implementation will be overriding the default
6612     * implementation that checks this flag.
6613     *
6614     * @param fitSystemWindows If true, then the default implementation of
6615     * {@link #fitSystemWindows(Rect)} will be executed.
6616     *
6617     * @attr ref android.R.styleable#View_fitsSystemWindows
6618     * @see #getFitsSystemWindows()
6619     * @see #fitSystemWindows(Rect)
6620     * @see #setSystemUiVisibility(int)
6621     */
6622    public void setFitsSystemWindows(boolean fitSystemWindows) {
6623        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6624    }
6625
6626    /**
6627     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6628     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6629     * will be executed.
6630     *
6631     * @return {@code true} if the default implementation of
6632     * {@link #fitSystemWindows(Rect)} will be executed.
6633     *
6634     * @attr ref android.R.styleable#View_fitsSystemWindows
6635     * @see #setFitsSystemWindows(boolean)
6636     * @see #fitSystemWindows(Rect)
6637     * @see #setSystemUiVisibility(int)
6638     */
6639    @ViewDebug.ExportedProperty
6640    public boolean getFitsSystemWindows() {
6641        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6642    }
6643
6644    /** @hide */
6645    public boolean fitsSystemWindows() {
6646        return getFitsSystemWindows();
6647    }
6648
6649    /**
6650     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6651     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6652     */
6653    public void requestFitSystemWindows() {
6654        if (mParent != null) {
6655            mParent.requestFitSystemWindows();
6656        }
6657    }
6658
6659    /**
6660     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6661     */
6662    public void requestApplyInsets() {
6663        requestFitSystemWindows();
6664    }
6665
6666    /**
6667     * For use by PhoneWindow to make its own system window fitting optional.
6668     * @hide
6669     */
6670    public void makeOptionalFitsSystemWindows() {
6671        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6672    }
6673
6674    /**
6675     * Returns the visibility status for this view.
6676     *
6677     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6678     * @attr ref android.R.styleable#View_visibility
6679     */
6680    @ViewDebug.ExportedProperty(mapping = {
6681        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6682        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6683        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6684    })
6685    @Visibility
6686    public int getVisibility() {
6687        return mViewFlags & VISIBILITY_MASK;
6688    }
6689
6690    /**
6691     * Set the enabled state of this view.
6692     *
6693     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6694     * @attr ref android.R.styleable#View_visibility
6695     */
6696    @RemotableViewMethod
6697    public void setVisibility(@Visibility int visibility) {
6698        setFlags(visibility, VISIBILITY_MASK);
6699    }
6700
6701    /**
6702     * Returns the enabled status for this view. The interpretation of the
6703     * enabled state varies by subclass.
6704     *
6705     * @return True if this view is enabled, false otherwise.
6706     */
6707    @ViewDebug.ExportedProperty
6708    public boolean isEnabled() {
6709        return (mViewFlags & ENABLED_MASK) == ENABLED;
6710    }
6711
6712    /**
6713     * Set the enabled state of this view. The interpretation of the enabled
6714     * state varies by subclass.
6715     *
6716     * @param enabled True if this view is enabled, false otherwise.
6717     */
6718    @RemotableViewMethod
6719    public void setEnabled(boolean enabled) {
6720        if (enabled == isEnabled()) return;
6721
6722        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6723
6724        /*
6725         * The View most likely has to change its appearance, so refresh
6726         * the drawable state.
6727         */
6728        refreshDrawableState();
6729
6730        // Invalidate too, since the default behavior for views is to be
6731        // be drawn at 50% alpha rather than to change the drawable.
6732        invalidate(true);
6733
6734        if (!enabled) {
6735            cancelPendingInputEvents();
6736        }
6737    }
6738
6739    /**
6740     * Set whether this view can receive the focus.
6741     *
6742     * Setting this to false will also ensure that this view is not focusable
6743     * in touch mode.
6744     *
6745     * @param focusable If true, this view can receive the focus.
6746     *
6747     * @see #setFocusableInTouchMode(boolean)
6748     * @attr ref android.R.styleable#View_focusable
6749     */
6750    public void setFocusable(boolean focusable) {
6751        if (!focusable) {
6752            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6753        }
6754        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6755    }
6756
6757    /**
6758     * Set whether this view can receive focus while in touch mode.
6759     *
6760     * Setting this to true will also ensure that this view is focusable.
6761     *
6762     * @param focusableInTouchMode If true, this view can receive the focus while
6763     *   in touch mode.
6764     *
6765     * @see #setFocusable(boolean)
6766     * @attr ref android.R.styleable#View_focusableInTouchMode
6767     */
6768    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6769        // Focusable in touch mode should always be set before the focusable flag
6770        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6771        // which, in touch mode, will not successfully request focus on this view
6772        // because the focusable in touch mode flag is not set
6773        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6774        if (focusableInTouchMode) {
6775            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6776        }
6777    }
6778
6779    /**
6780     * Set whether this view should have sound effects enabled for events such as
6781     * clicking and touching.
6782     *
6783     * <p>You may wish to disable sound effects for a view if you already play sounds,
6784     * for instance, a dial key that plays dtmf tones.
6785     *
6786     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6787     * @see #isSoundEffectsEnabled()
6788     * @see #playSoundEffect(int)
6789     * @attr ref android.R.styleable#View_soundEffectsEnabled
6790     */
6791    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6792        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6793    }
6794
6795    /**
6796     * @return whether this view should have sound effects enabled for events such as
6797     *     clicking and touching.
6798     *
6799     * @see #setSoundEffectsEnabled(boolean)
6800     * @see #playSoundEffect(int)
6801     * @attr ref android.R.styleable#View_soundEffectsEnabled
6802     */
6803    @ViewDebug.ExportedProperty
6804    public boolean isSoundEffectsEnabled() {
6805        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6806    }
6807
6808    /**
6809     * Set whether this view should have haptic feedback for events such as
6810     * long presses.
6811     *
6812     * <p>You may wish to disable haptic feedback if your view already controls
6813     * its own haptic feedback.
6814     *
6815     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6816     * @see #isHapticFeedbackEnabled()
6817     * @see #performHapticFeedback(int)
6818     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6819     */
6820    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6821        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6822    }
6823
6824    /**
6825     * @return whether this view should have haptic feedback enabled for events
6826     * long presses.
6827     *
6828     * @see #setHapticFeedbackEnabled(boolean)
6829     * @see #performHapticFeedback(int)
6830     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6831     */
6832    @ViewDebug.ExportedProperty
6833    public boolean isHapticFeedbackEnabled() {
6834        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6835    }
6836
6837    /**
6838     * Returns the layout direction for this view.
6839     *
6840     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6841     *   {@link #LAYOUT_DIRECTION_RTL},
6842     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6843     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6844     *
6845     * @attr ref android.R.styleable#View_layoutDirection
6846     *
6847     * @hide
6848     */
6849    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6850        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6851        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6852        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6853        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6854    })
6855    @LayoutDir
6856    public int getRawLayoutDirection() {
6857        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6858    }
6859
6860    /**
6861     * Set the layout direction for this view. This will propagate a reset of layout direction
6862     * resolution to the view's children and resolve layout direction for this view.
6863     *
6864     * @param layoutDirection the layout direction to set. Should be one of:
6865     *
6866     * {@link #LAYOUT_DIRECTION_LTR},
6867     * {@link #LAYOUT_DIRECTION_RTL},
6868     * {@link #LAYOUT_DIRECTION_INHERIT},
6869     * {@link #LAYOUT_DIRECTION_LOCALE}.
6870     *
6871     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6872     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6873     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6874     *
6875     * @attr ref android.R.styleable#View_layoutDirection
6876     */
6877    @RemotableViewMethod
6878    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6879        if (getRawLayoutDirection() != layoutDirection) {
6880            // Reset the current layout direction and the resolved one
6881            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6882            resetRtlProperties();
6883            // Set the new layout direction (filtered)
6884            mPrivateFlags2 |=
6885                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6886            // We need to resolve all RTL properties as they all depend on layout direction
6887            resolveRtlPropertiesIfNeeded();
6888            requestLayout();
6889            invalidate(true);
6890        }
6891    }
6892
6893    /**
6894     * Returns the resolved layout direction for this view.
6895     *
6896     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6897     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6898     *
6899     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6900     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6901     *
6902     * @attr ref android.R.styleable#View_layoutDirection
6903     */
6904    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6905        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6906        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6907    })
6908    @ResolvedLayoutDir
6909    public int getLayoutDirection() {
6910        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6911        if (targetSdkVersion < JELLY_BEAN_MR1) {
6912            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6913            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6914        }
6915        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6916                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6917    }
6918
6919    /**
6920     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6921     * layout attribute and/or the inherited value from the parent
6922     *
6923     * @return true if the layout is right-to-left.
6924     *
6925     * @hide
6926     */
6927    @ViewDebug.ExportedProperty(category = "layout")
6928    public boolean isLayoutRtl() {
6929        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6930    }
6931
6932    /**
6933     * Indicates whether the view is currently tracking transient state that the
6934     * app should not need to concern itself with saving and restoring, but that
6935     * the framework should take special note to preserve when possible.
6936     *
6937     * <p>A view with transient state cannot be trivially rebound from an external
6938     * data source, such as an adapter binding item views in a list. This may be
6939     * because the view is performing an animation, tracking user selection
6940     * of content, or similar.</p>
6941     *
6942     * @return true if the view has transient state
6943     */
6944    @ViewDebug.ExportedProperty(category = "layout")
6945    public boolean hasTransientState() {
6946        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6947    }
6948
6949    /**
6950     * Set whether this view is currently tracking transient state that the
6951     * framework should attempt to preserve when possible. This flag is reference counted,
6952     * so every call to setHasTransientState(true) should be paired with a later call
6953     * to setHasTransientState(false).
6954     *
6955     * <p>A view with transient state cannot be trivially rebound from an external
6956     * data source, such as an adapter binding item views in a list. This may be
6957     * because the view is performing an animation, tracking user selection
6958     * of content, or similar.</p>
6959     *
6960     * @param hasTransientState true if this view has transient state
6961     */
6962    public void setHasTransientState(boolean hasTransientState) {
6963        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6964                mTransientStateCount - 1;
6965        if (mTransientStateCount < 0) {
6966            mTransientStateCount = 0;
6967            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6968                    "unmatched pair of setHasTransientState calls");
6969        } else if ((hasTransientState && mTransientStateCount == 1) ||
6970                (!hasTransientState && mTransientStateCount == 0)) {
6971            // update flag if we've just incremented up from 0 or decremented down to 0
6972            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6973                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6974            if (mParent != null) {
6975                try {
6976                    mParent.childHasTransientStateChanged(this, hasTransientState);
6977                } catch (AbstractMethodError e) {
6978                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6979                            " does not fully implement ViewParent", e);
6980                }
6981            }
6982        }
6983    }
6984
6985    /**
6986     * Returns true if this view is currently attached to a window.
6987     */
6988    public boolean isAttachedToWindow() {
6989        return mAttachInfo != null;
6990    }
6991
6992    /**
6993     * Returns true if this view has been through at least one layout since it
6994     * was last attached to or detached from a window.
6995     */
6996    public boolean isLaidOut() {
6997        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6998    }
6999
7000    /**
7001     * If this view doesn't do any drawing on its own, set this flag to
7002     * allow further optimizations. By default, this flag is not set on
7003     * View, but could be set on some View subclasses such as ViewGroup.
7004     *
7005     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7006     * you should clear this flag.
7007     *
7008     * @param willNotDraw whether or not this View draw on its own
7009     */
7010    public void setWillNotDraw(boolean willNotDraw) {
7011        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7012    }
7013
7014    /**
7015     * Returns whether or not this View draws on its own.
7016     *
7017     * @return true if this view has nothing to draw, false otherwise
7018     */
7019    @ViewDebug.ExportedProperty(category = "drawing")
7020    public boolean willNotDraw() {
7021        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7022    }
7023
7024    /**
7025     * When a View's drawing cache is enabled, drawing is redirected to an
7026     * offscreen bitmap. Some views, like an ImageView, must be able to
7027     * bypass this mechanism if they already draw a single bitmap, to avoid
7028     * unnecessary usage of the memory.
7029     *
7030     * @param willNotCacheDrawing true if this view does not cache its
7031     *        drawing, false otherwise
7032     */
7033    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7034        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7035    }
7036
7037    /**
7038     * Returns whether or not this View can cache its drawing or not.
7039     *
7040     * @return true if this view does not cache its drawing, false otherwise
7041     */
7042    @ViewDebug.ExportedProperty(category = "drawing")
7043    public boolean willNotCacheDrawing() {
7044        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7045    }
7046
7047    /**
7048     * Indicates whether this view reacts to click events or not.
7049     *
7050     * @return true if the view is clickable, false otherwise
7051     *
7052     * @see #setClickable(boolean)
7053     * @attr ref android.R.styleable#View_clickable
7054     */
7055    @ViewDebug.ExportedProperty
7056    public boolean isClickable() {
7057        return (mViewFlags & CLICKABLE) == CLICKABLE;
7058    }
7059
7060    /**
7061     * Enables or disables click events for this view. When a view
7062     * is clickable it will change its state to "pressed" on every click.
7063     * Subclasses should set the view clickable to visually react to
7064     * user's clicks.
7065     *
7066     * @param clickable true to make the view clickable, false otherwise
7067     *
7068     * @see #isClickable()
7069     * @attr ref android.R.styleable#View_clickable
7070     */
7071    public void setClickable(boolean clickable) {
7072        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7073    }
7074
7075    /**
7076     * Indicates whether this view reacts to long click events or not.
7077     *
7078     * @return true if the view is long clickable, false otherwise
7079     *
7080     * @see #setLongClickable(boolean)
7081     * @attr ref android.R.styleable#View_longClickable
7082     */
7083    public boolean isLongClickable() {
7084        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7085    }
7086
7087    /**
7088     * Enables or disables long click events for this view. When a view is long
7089     * clickable it reacts to the user holding down the button for a longer
7090     * duration than a tap. This event can either launch the listener or a
7091     * context menu.
7092     *
7093     * @param longClickable true to make the view long clickable, false otherwise
7094     * @see #isLongClickable()
7095     * @attr ref android.R.styleable#View_longClickable
7096     */
7097    public void setLongClickable(boolean longClickable) {
7098        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7099    }
7100
7101    /**
7102     * Sets the pressed state for this view and provides a touch coordinate for
7103     * animation hinting.
7104     *
7105     * @param pressed Pass true to set the View's internal state to "pressed",
7106     *            or false to reverts the View's internal state from a
7107     *            previously set "pressed" state.
7108     * @param x The x coordinate of the touch that caused the press
7109     * @param y The y coordinate of the touch that caused the press
7110     */
7111    private void setPressed(boolean pressed, float x, float y) {
7112        if (pressed) {
7113            drawableHotspotChanged(x, y);
7114        }
7115
7116        setPressed(pressed);
7117    }
7118
7119    /**
7120     * Sets the pressed state for this view.
7121     *
7122     * @see #isClickable()
7123     * @see #setClickable(boolean)
7124     *
7125     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7126     *        the View's internal state from a previously set "pressed" state.
7127     */
7128    public void setPressed(boolean pressed) {
7129        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7130
7131        if (pressed) {
7132            mPrivateFlags |= PFLAG_PRESSED;
7133        } else {
7134            mPrivateFlags &= ~PFLAG_PRESSED;
7135        }
7136
7137        if (needsRefresh) {
7138            refreshDrawableState();
7139        }
7140        dispatchSetPressed(pressed);
7141    }
7142
7143    /**
7144     * Dispatch setPressed to all of this View's children.
7145     *
7146     * @see #setPressed(boolean)
7147     *
7148     * @param pressed The new pressed state
7149     */
7150    protected void dispatchSetPressed(boolean pressed) {
7151    }
7152
7153    /**
7154     * Indicates whether the view is currently in pressed state. Unless
7155     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7156     * the pressed state.
7157     *
7158     * @see #setPressed(boolean)
7159     * @see #isClickable()
7160     * @see #setClickable(boolean)
7161     *
7162     * @return true if the view is currently pressed, false otherwise
7163     */
7164    @ViewDebug.ExportedProperty
7165    public boolean isPressed() {
7166        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7167    }
7168
7169    /**
7170     * Indicates whether this view will save its state (that is,
7171     * whether its {@link #onSaveInstanceState} method will be called).
7172     *
7173     * @return Returns true if the view state saving is enabled, else false.
7174     *
7175     * @see #setSaveEnabled(boolean)
7176     * @attr ref android.R.styleable#View_saveEnabled
7177     */
7178    public boolean isSaveEnabled() {
7179        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7180    }
7181
7182    /**
7183     * Controls whether the saving of this view's state is
7184     * enabled (that is, whether its {@link #onSaveInstanceState} method
7185     * will be called).  Note that even if freezing is enabled, the
7186     * view still must have an id assigned to it (via {@link #setId(int)})
7187     * for its state to be saved.  This flag can only disable the
7188     * saving of this view; any child views may still have their state saved.
7189     *
7190     * @param enabled Set to false to <em>disable</em> state saving, or true
7191     * (the default) to allow it.
7192     *
7193     * @see #isSaveEnabled()
7194     * @see #setId(int)
7195     * @see #onSaveInstanceState()
7196     * @attr ref android.R.styleable#View_saveEnabled
7197     */
7198    public void setSaveEnabled(boolean enabled) {
7199        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7200    }
7201
7202    /**
7203     * Gets whether the framework should discard touches when the view's
7204     * window is obscured by another visible window.
7205     * Refer to the {@link View} security documentation for more details.
7206     *
7207     * @return True if touch filtering is enabled.
7208     *
7209     * @see #setFilterTouchesWhenObscured(boolean)
7210     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7211     */
7212    @ViewDebug.ExportedProperty
7213    public boolean getFilterTouchesWhenObscured() {
7214        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7215    }
7216
7217    /**
7218     * Sets whether the framework should discard touches when the view's
7219     * window is obscured by another visible window.
7220     * Refer to the {@link View} security documentation for more details.
7221     *
7222     * @param enabled True if touch filtering should be enabled.
7223     *
7224     * @see #getFilterTouchesWhenObscured
7225     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7226     */
7227    public void setFilterTouchesWhenObscured(boolean enabled) {
7228        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7229                FILTER_TOUCHES_WHEN_OBSCURED);
7230    }
7231
7232    /**
7233     * Indicates whether the entire hierarchy under this view will save its
7234     * state when a state saving traversal occurs from its parent.  The default
7235     * is true; if false, these views will not be saved unless
7236     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7237     *
7238     * @return Returns true if the view state saving from parent is enabled, else false.
7239     *
7240     * @see #setSaveFromParentEnabled(boolean)
7241     */
7242    public boolean isSaveFromParentEnabled() {
7243        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7244    }
7245
7246    /**
7247     * Controls whether the entire hierarchy under this view will save its
7248     * state when a state saving traversal occurs from its parent.  The default
7249     * is true; if false, these views will not be saved unless
7250     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7251     *
7252     * @param enabled Set to false to <em>disable</em> state saving, or true
7253     * (the default) to allow it.
7254     *
7255     * @see #isSaveFromParentEnabled()
7256     * @see #setId(int)
7257     * @see #onSaveInstanceState()
7258     */
7259    public void setSaveFromParentEnabled(boolean enabled) {
7260        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7261    }
7262
7263
7264    /**
7265     * Returns whether this View is able to take focus.
7266     *
7267     * @return True if this view can take focus, or false otherwise.
7268     * @attr ref android.R.styleable#View_focusable
7269     */
7270    @ViewDebug.ExportedProperty(category = "focus")
7271    public final boolean isFocusable() {
7272        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7273    }
7274
7275    /**
7276     * When a view is focusable, it may not want to take focus when in touch mode.
7277     * For example, a button would like focus when the user is navigating via a D-pad
7278     * so that the user can click on it, but once the user starts touching the screen,
7279     * the button shouldn't take focus
7280     * @return Whether the view is focusable in touch mode.
7281     * @attr ref android.R.styleable#View_focusableInTouchMode
7282     */
7283    @ViewDebug.ExportedProperty
7284    public final boolean isFocusableInTouchMode() {
7285        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7286    }
7287
7288    /**
7289     * Find the nearest view in the specified direction that can take focus.
7290     * This does not actually give focus to that view.
7291     *
7292     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7293     *
7294     * @return The nearest focusable in the specified direction, or null if none
7295     *         can be found.
7296     */
7297    public View focusSearch(@FocusRealDirection int direction) {
7298        if (mParent != null) {
7299            return mParent.focusSearch(this, direction);
7300        } else {
7301            return null;
7302        }
7303    }
7304
7305    /**
7306     * This method is the last chance for the focused view and its ancestors to
7307     * respond to an arrow key. This is called when the focused view did not
7308     * consume the key internally, nor could the view system find a new view in
7309     * the requested direction to give focus to.
7310     *
7311     * @param focused The currently focused view.
7312     * @param direction The direction focus wants to move. One of FOCUS_UP,
7313     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7314     * @return True if the this view consumed this unhandled move.
7315     */
7316    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7317        return false;
7318    }
7319
7320    /**
7321     * If a user manually specified the next view id for a particular direction,
7322     * use the root to look up the view.
7323     * @param root The root view of the hierarchy containing this view.
7324     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7325     * or FOCUS_BACKWARD.
7326     * @return The user specified next view, or null if there is none.
7327     */
7328    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7329        switch (direction) {
7330            case FOCUS_LEFT:
7331                if (mNextFocusLeftId == View.NO_ID) return null;
7332                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7333            case FOCUS_RIGHT:
7334                if (mNextFocusRightId == View.NO_ID) return null;
7335                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7336            case FOCUS_UP:
7337                if (mNextFocusUpId == View.NO_ID) return null;
7338                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7339            case FOCUS_DOWN:
7340                if (mNextFocusDownId == View.NO_ID) return null;
7341                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7342            case FOCUS_FORWARD:
7343                if (mNextFocusForwardId == View.NO_ID) return null;
7344                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7345            case FOCUS_BACKWARD: {
7346                if (mID == View.NO_ID) return null;
7347                final int id = mID;
7348                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7349                    @Override
7350                    public boolean apply(View t) {
7351                        return t.mNextFocusForwardId == id;
7352                    }
7353                });
7354            }
7355        }
7356        return null;
7357    }
7358
7359    private View findViewInsideOutShouldExist(View root, int id) {
7360        if (mMatchIdPredicate == null) {
7361            mMatchIdPredicate = new MatchIdPredicate();
7362        }
7363        mMatchIdPredicate.mId = id;
7364        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7365        if (result == null) {
7366            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7367        }
7368        return result;
7369    }
7370
7371    /**
7372     * Find and return all focusable views that are descendants of this view,
7373     * possibly including this view if it is focusable itself.
7374     *
7375     * @param direction The direction of the focus
7376     * @return A list of focusable views
7377     */
7378    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7379        ArrayList<View> result = new ArrayList<View>(24);
7380        addFocusables(result, direction);
7381        return result;
7382    }
7383
7384    /**
7385     * Add any focusable views that are descendants of this view (possibly
7386     * including this view if it is focusable itself) to views.  If we are in touch mode,
7387     * only add views that are also focusable in touch mode.
7388     *
7389     * @param views Focusable views found so far
7390     * @param direction The direction of the focus
7391     */
7392    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7393        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7394    }
7395
7396    /**
7397     * Adds any focusable views that are descendants of this view (possibly
7398     * including this view if it is focusable itself) to views. This method
7399     * adds all focusable views regardless if we are in touch mode or
7400     * only views focusable in touch mode if we are in touch mode or
7401     * only views that can take accessibility focus if accessibility is enabled
7402     * depending on the focusable mode parameter.
7403     *
7404     * @param views Focusable views found so far or null if all we are interested is
7405     *        the number of focusables.
7406     * @param direction The direction of the focus.
7407     * @param focusableMode The type of focusables to be added.
7408     *
7409     * @see #FOCUSABLES_ALL
7410     * @see #FOCUSABLES_TOUCH_MODE
7411     */
7412    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7413            @FocusableMode int focusableMode) {
7414        if (views == null) {
7415            return;
7416        }
7417        if (!isFocusable()) {
7418            return;
7419        }
7420        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7421                && isInTouchMode() && !isFocusableInTouchMode()) {
7422            return;
7423        }
7424        views.add(this);
7425    }
7426
7427    /**
7428     * Finds the Views that contain given text. The containment is case insensitive.
7429     * The search is performed by either the text that the View renders or the content
7430     * description that describes the view for accessibility purposes and the view does
7431     * not render or both. Clients can specify how the search is to be performed via
7432     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7433     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7434     *
7435     * @param outViews The output list of matching Views.
7436     * @param searched The text to match against.
7437     *
7438     * @see #FIND_VIEWS_WITH_TEXT
7439     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7440     * @see #setContentDescription(CharSequence)
7441     */
7442    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7443            @FindViewFlags int flags) {
7444        if (getAccessibilityNodeProvider() != null) {
7445            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7446                outViews.add(this);
7447            }
7448        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7449                && (searched != null && searched.length() > 0)
7450                && (mContentDescription != null && mContentDescription.length() > 0)) {
7451            String searchedLowerCase = searched.toString().toLowerCase();
7452            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7453            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7454                outViews.add(this);
7455            }
7456        }
7457    }
7458
7459    /**
7460     * Find and return all touchable views that are descendants of this view,
7461     * possibly including this view if it is touchable itself.
7462     *
7463     * @return A list of touchable views
7464     */
7465    public ArrayList<View> getTouchables() {
7466        ArrayList<View> result = new ArrayList<View>();
7467        addTouchables(result);
7468        return result;
7469    }
7470
7471    /**
7472     * Add any touchable views that are descendants of this view (possibly
7473     * including this view if it is touchable itself) to views.
7474     *
7475     * @param views Touchable views found so far
7476     */
7477    public void addTouchables(ArrayList<View> views) {
7478        final int viewFlags = mViewFlags;
7479
7480        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7481                && (viewFlags & ENABLED_MASK) == ENABLED) {
7482            views.add(this);
7483        }
7484    }
7485
7486    /**
7487     * Returns whether this View is accessibility focused.
7488     *
7489     * @return True if this View is accessibility focused.
7490     */
7491    public boolean isAccessibilityFocused() {
7492        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7493    }
7494
7495    /**
7496     * Call this to try to give accessibility focus to this view.
7497     *
7498     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7499     * returns false or the view is no visible or the view already has accessibility
7500     * focus.
7501     *
7502     * See also {@link #focusSearch(int)}, which is what you call to say that you
7503     * have focus, and you want your parent to look for the next one.
7504     *
7505     * @return Whether this view actually took accessibility focus.
7506     *
7507     * @hide
7508     */
7509    public boolean requestAccessibilityFocus() {
7510        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7511        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7512            return false;
7513        }
7514        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7515            return false;
7516        }
7517        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7518            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7519            ViewRootImpl viewRootImpl = getViewRootImpl();
7520            if (viewRootImpl != null) {
7521                viewRootImpl.setAccessibilityFocus(this, null);
7522            }
7523            invalidate();
7524            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7525            return true;
7526        }
7527        return false;
7528    }
7529
7530    /**
7531     * Call this to try to clear accessibility focus of this view.
7532     *
7533     * See also {@link #focusSearch(int)}, which is what you call to say that you
7534     * have focus, and you want your parent to look for the next one.
7535     *
7536     * @hide
7537     */
7538    public void clearAccessibilityFocus() {
7539        clearAccessibilityFocusNoCallbacks();
7540        // Clear the global reference of accessibility focus if this
7541        // view or any of its descendants had accessibility focus.
7542        ViewRootImpl viewRootImpl = getViewRootImpl();
7543        if (viewRootImpl != null) {
7544            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7545            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7546                viewRootImpl.setAccessibilityFocus(null, null);
7547            }
7548        }
7549    }
7550
7551    private void sendAccessibilityHoverEvent(int eventType) {
7552        // Since we are not delivering to a client accessibility events from not
7553        // important views (unless the clinet request that) we need to fire the
7554        // event from the deepest view exposed to the client. As a consequence if
7555        // the user crosses a not exposed view the client will see enter and exit
7556        // of the exposed predecessor followed by and enter and exit of that same
7557        // predecessor when entering and exiting the not exposed descendant. This
7558        // is fine since the client has a clear idea which view is hovered at the
7559        // price of a couple more events being sent. This is a simple and
7560        // working solution.
7561        View source = this;
7562        while (true) {
7563            if (source.includeForAccessibility()) {
7564                source.sendAccessibilityEvent(eventType);
7565                return;
7566            }
7567            ViewParent parent = source.getParent();
7568            if (parent instanceof View) {
7569                source = (View) parent;
7570            } else {
7571                return;
7572            }
7573        }
7574    }
7575
7576    /**
7577     * Clears accessibility focus without calling any callback methods
7578     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7579     * is used for clearing accessibility focus when giving this focus to
7580     * another view.
7581     */
7582    void clearAccessibilityFocusNoCallbacks() {
7583        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7584            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7585            invalidate();
7586            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7587        }
7588    }
7589
7590    /**
7591     * Call this to try to give focus to a specific view or to one of its
7592     * descendants.
7593     *
7594     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7595     * false), or if it is focusable and it is not focusable in touch mode
7596     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7597     *
7598     * See also {@link #focusSearch(int)}, which is what you call to say that you
7599     * have focus, and you want your parent to look for the next one.
7600     *
7601     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7602     * {@link #FOCUS_DOWN} and <code>null</code>.
7603     *
7604     * @return Whether this view or one of its descendants actually took focus.
7605     */
7606    public final boolean requestFocus() {
7607        return requestFocus(View.FOCUS_DOWN);
7608    }
7609
7610    /**
7611     * Call this to try to give focus to a specific view or to one of its
7612     * descendants and give it a hint about what direction focus is heading.
7613     *
7614     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7615     * false), or if it is focusable and it is not focusable in touch mode
7616     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7617     *
7618     * See also {@link #focusSearch(int)}, which is what you call to say that you
7619     * have focus, and you want your parent to look for the next one.
7620     *
7621     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7622     * <code>null</code> set for the previously focused rectangle.
7623     *
7624     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7625     * @return Whether this view or one of its descendants actually took focus.
7626     */
7627    public final boolean requestFocus(int direction) {
7628        return requestFocus(direction, null);
7629    }
7630
7631    /**
7632     * Call this to try to give focus to a specific view or to one of its descendants
7633     * and give it hints about the direction and a specific rectangle that the focus
7634     * is coming from.  The rectangle can help give larger views a finer grained hint
7635     * about where focus is coming from, and therefore, where to show selection, or
7636     * forward focus change internally.
7637     *
7638     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7639     * false), or if it is focusable and it is not focusable in touch mode
7640     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7641     *
7642     * A View will not take focus if it is not visible.
7643     *
7644     * A View will not take focus if one of its parents has
7645     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7646     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7647     *
7648     * See also {@link #focusSearch(int)}, which is what you call to say that you
7649     * have focus, and you want your parent to look for the next one.
7650     *
7651     * You may wish to override this method if your custom {@link View} has an internal
7652     * {@link View} that it wishes to forward the request to.
7653     *
7654     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7655     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7656     *        to give a finer grained hint about where focus is coming from.  May be null
7657     *        if there is no hint.
7658     * @return Whether this view or one of its descendants actually took focus.
7659     */
7660    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7661        return requestFocusNoSearch(direction, previouslyFocusedRect);
7662    }
7663
7664    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7665        // need to be focusable
7666        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7667                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7668            return false;
7669        }
7670
7671        // need to be focusable in touch mode if in touch mode
7672        if (isInTouchMode() &&
7673            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7674               return false;
7675        }
7676
7677        // need to not have any parents blocking us
7678        if (hasAncestorThatBlocksDescendantFocus()) {
7679            return false;
7680        }
7681
7682        handleFocusGainInternal(direction, previouslyFocusedRect);
7683        return true;
7684    }
7685
7686    /**
7687     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7688     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
7689     * touch mode to request focus when they are touched.
7690     *
7691     * @return Whether this view or one of its descendants actually took focus.
7692     *
7693     * @see #isInTouchMode()
7694     *
7695     */
7696    public final boolean requestFocusFromTouch() {
7697        // Leave touch mode if we need to
7698        if (isInTouchMode()) {
7699            ViewRootImpl viewRoot = getViewRootImpl();
7700            if (viewRoot != null) {
7701                viewRoot.ensureTouchMode(false);
7702            }
7703        }
7704        return requestFocus(View.FOCUS_DOWN);
7705    }
7706
7707    /**
7708     * @return Whether any ancestor of this view blocks descendant focus.
7709     */
7710    private boolean hasAncestorThatBlocksDescendantFocus() {
7711        final boolean focusableInTouchMode = isFocusableInTouchMode();
7712        ViewParent ancestor = mParent;
7713        while (ancestor instanceof ViewGroup) {
7714            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7715            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7716                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7717                return true;
7718            } else {
7719                ancestor = vgAncestor.getParent();
7720            }
7721        }
7722        return false;
7723    }
7724
7725    /**
7726     * Gets the mode for determining whether this View is important for accessibility
7727     * which is if it fires accessibility events and if it is reported to
7728     * accessibility services that query the screen.
7729     *
7730     * @return The mode for determining whether a View is important for accessibility.
7731     *
7732     * @attr ref android.R.styleable#View_importantForAccessibility
7733     *
7734     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7735     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7736     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7737     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7738     */
7739    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7740            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7741            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7742            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7743            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7744                    to = "noHideDescendants")
7745        })
7746    public int getImportantForAccessibility() {
7747        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7748                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7749    }
7750
7751    /**
7752     * Sets the live region mode for this view. This indicates to accessibility
7753     * services whether they should automatically notify the user about changes
7754     * to the view's content description or text, or to the content descriptions
7755     * or text of the view's children (where applicable).
7756     * <p>
7757     * For example, in a login screen with a TextView that displays an "incorrect
7758     * password" notification, that view should be marked as a live region with
7759     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7760     * <p>
7761     * To disable change notifications for this view, use
7762     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7763     * mode for most views.
7764     * <p>
7765     * To indicate that the user should be notified of changes, use
7766     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7767     * <p>
7768     * If the view's changes should interrupt ongoing speech and notify the user
7769     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7770     *
7771     * @param mode The live region mode for this view, one of:
7772     *        <ul>
7773     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7774     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7775     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7776     *        </ul>
7777     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7778     */
7779    public void setAccessibilityLiveRegion(int mode) {
7780        if (mode != getAccessibilityLiveRegion()) {
7781            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7782            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7783                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7784            notifyViewAccessibilityStateChangedIfNeeded(
7785                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7786        }
7787    }
7788
7789    /**
7790     * Gets the live region mode for this View.
7791     *
7792     * @return The live region mode for the view.
7793     *
7794     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7795     *
7796     * @see #setAccessibilityLiveRegion(int)
7797     */
7798    public int getAccessibilityLiveRegion() {
7799        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7800                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7801    }
7802
7803    /**
7804     * Sets how to determine whether this view is important for accessibility
7805     * which is if it fires accessibility events and if it is reported to
7806     * accessibility services that query the screen.
7807     *
7808     * @param mode How to determine whether this view is important for accessibility.
7809     *
7810     * @attr ref android.R.styleable#View_importantForAccessibility
7811     *
7812     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7813     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7814     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7815     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7816     */
7817    public void setImportantForAccessibility(int mode) {
7818        final int oldMode = getImportantForAccessibility();
7819        if (mode != oldMode) {
7820            // If we're moving between AUTO and another state, we might not need
7821            // to send a subtree changed notification. We'll store the computed
7822            // importance, since we'll need to check it later to make sure.
7823            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7824                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7825            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7826            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7827            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7828                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7829            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7830                notifySubtreeAccessibilityStateChangedIfNeeded();
7831            } else {
7832                notifyViewAccessibilityStateChangedIfNeeded(
7833                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7834            }
7835        }
7836    }
7837
7838    /**
7839     * Computes whether this view should be exposed for accessibility. In
7840     * general, views that are interactive or provide information are exposed
7841     * while views that serve only as containers are hidden.
7842     * <p>
7843     * If an ancestor of this view has importance
7844     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7845     * returns <code>false</code>.
7846     * <p>
7847     * Otherwise, the value is computed according to the view's
7848     * {@link #getImportantForAccessibility()} value:
7849     * <ol>
7850     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7851     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7852     * </code>
7853     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7854     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7855     * view satisfies any of the following:
7856     * <ul>
7857     * <li>Is actionable, e.g. {@link #isClickable()},
7858     * {@link #isLongClickable()}, or {@link #isFocusable()}
7859     * <li>Has an {@link AccessibilityDelegate}
7860     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7861     * {@link OnKeyListener}, etc.
7862     * <li>Is an accessibility live region, e.g.
7863     * {@link #getAccessibilityLiveRegion()} is not
7864     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7865     * </ul>
7866     * </ol>
7867     *
7868     * @return Whether the view is exposed for accessibility.
7869     * @see #setImportantForAccessibility(int)
7870     * @see #getImportantForAccessibility()
7871     */
7872    public boolean isImportantForAccessibility() {
7873        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7874                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7875        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7876                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7877            return false;
7878        }
7879
7880        // Check parent mode to ensure we're not hidden.
7881        ViewParent parent = mParent;
7882        while (parent instanceof View) {
7883            if (((View) parent).getImportantForAccessibility()
7884                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7885                return false;
7886            }
7887            parent = parent.getParent();
7888        }
7889
7890        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7891                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7892                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7893    }
7894
7895    /**
7896     * Gets the parent for accessibility purposes. Note that the parent for
7897     * accessibility is not necessary the immediate parent. It is the first
7898     * predecessor that is important for accessibility.
7899     *
7900     * @return The parent for accessibility purposes.
7901     */
7902    public ViewParent getParentForAccessibility() {
7903        if (mParent instanceof View) {
7904            View parentView = (View) mParent;
7905            if (parentView.includeForAccessibility()) {
7906                return mParent;
7907            } else {
7908                return mParent.getParentForAccessibility();
7909            }
7910        }
7911        return null;
7912    }
7913
7914    /**
7915     * Adds the children of a given View for accessibility. Since some Views are
7916     * not important for accessibility the children for accessibility are not
7917     * necessarily direct children of the view, rather they are the first level of
7918     * descendants important for accessibility.
7919     *
7920     * @param children The list of children for accessibility.
7921     */
7922    public void addChildrenForAccessibility(ArrayList<View> children) {
7923
7924    }
7925
7926    /**
7927     * Whether to regard this view for accessibility. A view is regarded for
7928     * accessibility if it is important for accessibility or the querying
7929     * accessibility service has explicitly requested that view not
7930     * important for accessibility are regarded.
7931     *
7932     * @return Whether to regard the view for accessibility.
7933     *
7934     * @hide
7935     */
7936    public boolean includeForAccessibility() {
7937        if (mAttachInfo != null) {
7938            return (mAttachInfo.mAccessibilityFetchFlags
7939                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7940                    || isImportantForAccessibility();
7941        }
7942        return false;
7943    }
7944
7945    /**
7946     * Returns whether the View is considered actionable from
7947     * accessibility perspective. Such view are important for
7948     * accessibility.
7949     *
7950     * @return True if the view is actionable for accessibility.
7951     *
7952     * @hide
7953     */
7954    public boolean isActionableForAccessibility() {
7955        return (isClickable() || isLongClickable() || isFocusable());
7956    }
7957
7958    /**
7959     * Returns whether the View has registered callbacks which makes it
7960     * important for accessibility.
7961     *
7962     * @return True if the view is actionable for accessibility.
7963     */
7964    private boolean hasListenersForAccessibility() {
7965        ListenerInfo info = getListenerInfo();
7966        return mTouchDelegate != null || info.mOnKeyListener != null
7967                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7968                || info.mOnHoverListener != null || info.mOnDragListener != null;
7969    }
7970
7971    /**
7972     * Notifies that the accessibility state of this view changed. The change
7973     * is local to this view and does not represent structural changes such
7974     * as children and parent. For example, the view became focusable. The
7975     * notification is at at most once every
7976     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7977     * to avoid unnecessary load to the system. Also once a view has a pending
7978     * notification this method is a NOP until the notification has been sent.
7979     *
7980     * @hide
7981     */
7982    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7983        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7984            return;
7985        }
7986        if (mSendViewStateChangedAccessibilityEvent == null) {
7987            mSendViewStateChangedAccessibilityEvent =
7988                    new SendViewStateChangedAccessibilityEvent();
7989        }
7990        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7991    }
7992
7993    /**
7994     * Notifies that the accessibility state of this view changed. The change
7995     * is *not* local to this view and does represent structural changes such
7996     * as children and parent. For example, the view size changed. The
7997     * notification is at at most once every
7998     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7999     * to avoid unnecessary load to the system. Also once a view has a pending
8000     * notification this method is a NOP until the notification has been sent.
8001     *
8002     * @hide
8003     */
8004    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8005        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8006            return;
8007        }
8008        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8009            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8010            if (mParent != null) {
8011                try {
8012                    mParent.notifySubtreeAccessibilityStateChanged(
8013                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8014                } catch (AbstractMethodError e) {
8015                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8016                            " does not fully implement ViewParent", e);
8017                }
8018            }
8019        }
8020    }
8021
8022    /**
8023     * Reset the flag indicating the accessibility state of the subtree rooted
8024     * at this view changed.
8025     */
8026    void resetSubtreeAccessibilityStateChanged() {
8027        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8028    }
8029
8030    /**
8031     * Report an accessibility action to this view's parents for delegated processing.
8032     *
8033     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8034     * call this method to delegate an accessibility action to a supporting parent. If the parent
8035     * returns true from its
8036     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8037     * method this method will return true to signify that the action was consumed.</p>
8038     *
8039     * <p>This method is useful for implementing nested scrolling child views. If
8040     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8041     * a custom view implementation may invoke this method to allow a parent to consume the
8042     * scroll first. If this method returns true the custom view should skip its own scrolling
8043     * behavior.</p>
8044     *
8045     * @param action Accessibility action to delegate
8046     * @param arguments Optional action arguments
8047     * @return true if the action was consumed by a parent
8048     */
8049    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8050        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8051            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8052                return true;
8053            }
8054        }
8055        return false;
8056    }
8057
8058    /**
8059     * Performs the specified accessibility action on the view. For
8060     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8061     * <p>
8062     * If an {@link AccessibilityDelegate} has been specified via calling
8063     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8064     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8065     * is responsible for handling this call.
8066     * </p>
8067     *
8068     * <p>The default implementation will delegate
8069     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8070     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8071     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8072     *
8073     * @param action The action to perform.
8074     * @param arguments Optional action arguments.
8075     * @return Whether the action was performed.
8076     */
8077    public boolean performAccessibilityAction(int action, Bundle arguments) {
8078      if (mAccessibilityDelegate != null) {
8079          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8080      } else {
8081          return performAccessibilityActionInternal(action, arguments);
8082      }
8083    }
8084
8085   /**
8086    * @see #performAccessibilityAction(int, Bundle)
8087    *
8088    * Note: Called from the default {@link AccessibilityDelegate}.
8089    *
8090    * @hide
8091    */
8092    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8093        if (isNestedScrollingEnabled()
8094                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8095                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
8096            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8097                return true;
8098            }
8099        }
8100
8101        switch (action) {
8102            case AccessibilityNodeInfo.ACTION_CLICK: {
8103                if (isClickable()) {
8104                    performClick();
8105                    return true;
8106                }
8107            } break;
8108            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8109                if (isLongClickable()) {
8110                    performLongClick();
8111                    return true;
8112                }
8113            } break;
8114            case AccessibilityNodeInfo.ACTION_FOCUS: {
8115                if (!hasFocus()) {
8116                    // Get out of touch mode since accessibility
8117                    // wants to move focus around.
8118                    getViewRootImpl().ensureTouchMode(false);
8119                    return requestFocus();
8120                }
8121            } break;
8122            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8123                if (hasFocus()) {
8124                    clearFocus();
8125                    return !isFocused();
8126                }
8127            } break;
8128            case AccessibilityNodeInfo.ACTION_SELECT: {
8129                if (!isSelected()) {
8130                    setSelected(true);
8131                    return isSelected();
8132                }
8133            } break;
8134            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8135                if (isSelected()) {
8136                    setSelected(false);
8137                    return !isSelected();
8138                }
8139            } break;
8140            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8141                if (!isAccessibilityFocused()) {
8142                    return requestAccessibilityFocus();
8143                }
8144            } break;
8145            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8146                if (isAccessibilityFocused()) {
8147                    clearAccessibilityFocus();
8148                    return true;
8149                }
8150            } break;
8151            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8152                if (arguments != null) {
8153                    final int granularity = arguments.getInt(
8154                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8155                    final boolean extendSelection = arguments.getBoolean(
8156                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8157                    return traverseAtGranularity(granularity, true, extendSelection);
8158                }
8159            } break;
8160            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8161                if (arguments != null) {
8162                    final int granularity = arguments.getInt(
8163                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8164                    final boolean extendSelection = arguments.getBoolean(
8165                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8166                    return traverseAtGranularity(granularity, false, extendSelection);
8167                }
8168            } break;
8169            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8170                CharSequence text = getIterableTextForAccessibility();
8171                if (text == null) {
8172                    return false;
8173                }
8174                final int start = (arguments != null) ? arguments.getInt(
8175                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8176                final int end = (arguments != null) ? arguments.getInt(
8177                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8178                // Only cursor position can be specified (selection length == 0)
8179                if ((getAccessibilitySelectionStart() != start
8180                        || getAccessibilitySelectionEnd() != end)
8181                        && (start == end)) {
8182                    setAccessibilitySelection(start, end);
8183                    notifyViewAccessibilityStateChangedIfNeeded(
8184                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8185                    return true;
8186                }
8187            } break;
8188        }
8189        return false;
8190    }
8191
8192    private boolean traverseAtGranularity(int granularity, boolean forward,
8193            boolean extendSelection) {
8194        CharSequence text = getIterableTextForAccessibility();
8195        if (text == null || text.length() == 0) {
8196            return false;
8197        }
8198        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8199        if (iterator == null) {
8200            return false;
8201        }
8202        int current = getAccessibilitySelectionEnd();
8203        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8204            current = forward ? 0 : text.length();
8205        }
8206        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8207        if (range == null) {
8208            return false;
8209        }
8210        final int segmentStart = range[0];
8211        final int segmentEnd = range[1];
8212        int selectionStart;
8213        int selectionEnd;
8214        if (extendSelection && isAccessibilitySelectionExtendable()) {
8215            selectionStart = getAccessibilitySelectionStart();
8216            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8217                selectionStart = forward ? segmentStart : segmentEnd;
8218            }
8219            selectionEnd = forward ? segmentEnd : segmentStart;
8220        } else {
8221            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8222        }
8223        setAccessibilitySelection(selectionStart, selectionEnd);
8224        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8225                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8226        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8227        return true;
8228    }
8229
8230    /**
8231     * Gets the text reported for accessibility purposes.
8232     *
8233     * @return The accessibility text.
8234     *
8235     * @hide
8236     */
8237    public CharSequence getIterableTextForAccessibility() {
8238        return getContentDescription();
8239    }
8240
8241    /**
8242     * Gets whether accessibility selection can be extended.
8243     *
8244     * @return If selection is extensible.
8245     *
8246     * @hide
8247     */
8248    public boolean isAccessibilitySelectionExtendable() {
8249        return false;
8250    }
8251
8252    /**
8253     * @hide
8254     */
8255    public int getAccessibilitySelectionStart() {
8256        return mAccessibilityCursorPosition;
8257    }
8258
8259    /**
8260     * @hide
8261     */
8262    public int getAccessibilitySelectionEnd() {
8263        return getAccessibilitySelectionStart();
8264    }
8265
8266    /**
8267     * @hide
8268     */
8269    public void setAccessibilitySelection(int start, int end) {
8270        if (start ==  end && end == mAccessibilityCursorPosition) {
8271            return;
8272        }
8273        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8274            mAccessibilityCursorPosition = start;
8275        } else {
8276            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8277        }
8278        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8279    }
8280
8281    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8282            int fromIndex, int toIndex) {
8283        if (mParent == null) {
8284            return;
8285        }
8286        AccessibilityEvent event = AccessibilityEvent.obtain(
8287                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8288        onInitializeAccessibilityEvent(event);
8289        onPopulateAccessibilityEvent(event);
8290        event.setFromIndex(fromIndex);
8291        event.setToIndex(toIndex);
8292        event.setAction(action);
8293        event.setMovementGranularity(granularity);
8294        mParent.requestSendAccessibilityEvent(this, event);
8295    }
8296
8297    /**
8298     * @hide
8299     */
8300    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8301        switch (granularity) {
8302            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8303                CharSequence text = getIterableTextForAccessibility();
8304                if (text != null && text.length() > 0) {
8305                    CharacterTextSegmentIterator iterator =
8306                        CharacterTextSegmentIterator.getInstance(
8307                                mContext.getResources().getConfiguration().locale);
8308                    iterator.initialize(text.toString());
8309                    return iterator;
8310                }
8311            } break;
8312            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8313                CharSequence text = getIterableTextForAccessibility();
8314                if (text != null && text.length() > 0) {
8315                    WordTextSegmentIterator iterator =
8316                        WordTextSegmentIterator.getInstance(
8317                                mContext.getResources().getConfiguration().locale);
8318                    iterator.initialize(text.toString());
8319                    return iterator;
8320                }
8321            } break;
8322            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8323                CharSequence text = getIterableTextForAccessibility();
8324                if (text != null && text.length() > 0) {
8325                    ParagraphTextSegmentIterator iterator =
8326                        ParagraphTextSegmentIterator.getInstance();
8327                    iterator.initialize(text.toString());
8328                    return iterator;
8329                }
8330            } break;
8331        }
8332        return null;
8333    }
8334
8335    /**
8336     * @hide
8337     */
8338    public void dispatchStartTemporaryDetach() {
8339        onStartTemporaryDetach();
8340    }
8341
8342    /**
8343     * This is called when a container is going to temporarily detach a child, with
8344     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8345     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8346     * {@link #onDetachedFromWindow()} when the container is done.
8347     */
8348    public void onStartTemporaryDetach() {
8349        removeUnsetPressCallback();
8350        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8351    }
8352
8353    /**
8354     * @hide
8355     */
8356    public void dispatchFinishTemporaryDetach() {
8357        onFinishTemporaryDetach();
8358    }
8359
8360    /**
8361     * Called after {@link #onStartTemporaryDetach} when the container is done
8362     * changing the view.
8363     */
8364    public void onFinishTemporaryDetach() {
8365    }
8366
8367    /**
8368     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8369     * for this view's window.  Returns null if the view is not currently attached
8370     * to the window.  Normally you will not need to use this directly, but
8371     * just use the standard high-level event callbacks like
8372     * {@link #onKeyDown(int, KeyEvent)}.
8373     */
8374    public KeyEvent.DispatcherState getKeyDispatcherState() {
8375        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8376    }
8377
8378    /**
8379     * Dispatch a key event before it is processed by any input method
8380     * associated with the view hierarchy.  This can be used to intercept
8381     * key events in special situations before the IME consumes them; a
8382     * typical example would be handling the BACK key to update the application's
8383     * UI instead of allowing the IME to see it and close itself.
8384     *
8385     * @param event The key event to be dispatched.
8386     * @return True if the event was handled, false otherwise.
8387     */
8388    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8389        return onKeyPreIme(event.getKeyCode(), event);
8390    }
8391
8392    /**
8393     * Dispatch a key event to the next view on the focus path. This path runs
8394     * from the top of the view tree down to the currently focused view. If this
8395     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8396     * the next node down the focus path. This method also fires any key
8397     * listeners.
8398     *
8399     * @param event The key event to be dispatched.
8400     * @return True if the event was handled, false otherwise.
8401     */
8402    public boolean dispatchKeyEvent(KeyEvent event) {
8403        if (mInputEventConsistencyVerifier != null) {
8404            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8405        }
8406
8407        // Give any attached key listener a first crack at the event.
8408        //noinspection SimplifiableIfStatement
8409        ListenerInfo li = mListenerInfo;
8410        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8411                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8412            return true;
8413        }
8414
8415        if (event.dispatch(this, mAttachInfo != null
8416                ? mAttachInfo.mKeyDispatchState : null, this)) {
8417            return true;
8418        }
8419
8420        if (mInputEventConsistencyVerifier != null) {
8421            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8422        }
8423        return false;
8424    }
8425
8426    /**
8427     * Dispatches a key shortcut event.
8428     *
8429     * @param event The key event to be dispatched.
8430     * @return True if the event was handled by the view, false otherwise.
8431     */
8432    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8433        return onKeyShortcut(event.getKeyCode(), event);
8434    }
8435
8436    /**
8437     * Pass the touch screen motion event down to the target view, or this
8438     * view if it is the target.
8439     *
8440     * @param event The motion event to be dispatched.
8441     * @return True if the event was handled by the view, false otherwise.
8442     */
8443    public boolean dispatchTouchEvent(MotionEvent event) {
8444        // If the event should be handled by accessibility focus first.
8445        if (event.isTargetAccessibilityFocus()) {
8446            // We don't have focus or no virtual descendant has it, do not handle the event.
8447            if (!isAccessibilityFocusedViewOrHost()) {
8448                return false;
8449            }
8450            // We have focus and got the event, then use normal event dispatch.
8451            event.setTargetAccessibilityFocus(false);
8452        }
8453
8454        boolean result = false;
8455
8456        if (mInputEventConsistencyVerifier != null) {
8457            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8458        }
8459
8460        final int actionMasked = event.getActionMasked();
8461        if (actionMasked == MotionEvent.ACTION_DOWN) {
8462            // Defensive cleanup for new gesture
8463            stopNestedScroll();
8464        }
8465
8466        if (onFilterTouchEventForSecurity(event)) {
8467            //noinspection SimplifiableIfStatement
8468            ListenerInfo li = mListenerInfo;
8469            if (li != null && li.mOnTouchListener != null
8470                    && (mViewFlags & ENABLED_MASK) == ENABLED
8471                    && li.mOnTouchListener.onTouch(this, event)) {
8472                result = true;
8473            }
8474
8475            if (!result && onTouchEvent(event)) {
8476                result = true;
8477            }
8478        }
8479
8480        if (!result && mInputEventConsistencyVerifier != null) {
8481            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8482        }
8483
8484        // Clean up after nested scrolls if this is the end of a gesture;
8485        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8486        // of the gesture.
8487        if (actionMasked == MotionEvent.ACTION_UP ||
8488                actionMasked == MotionEvent.ACTION_CANCEL ||
8489                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8490            stopNestedScroll();
8491        }
8492
8493        return result;
8494    }
8495
8496    boolean isAccessibilityFocusedViewOrHost() {
8497        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
8498                .getAccessibilityFocusedHost() == this);
8499    }
8500
8501    /**
8502     * Filter the touch event to apply security policies.
8503     *
8504     * @param event The motion event to be filtered.
8505     * @return True if the event should be dispatched, false if the event should be dropped.
8506     *
8507     * @see #getFilterTouchesWhenObscured
8508     */
8509    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8510        //noinspection RedundantIfStatement
8511        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8512                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8513            // Window is obscured, drop this touch.
8514            return false;
8515        }
8516        return true;
8517    }
8518
8519    /**
8520     * Pass a trackball motion event down to the focused view.
8521     *
8522     * @param event The motion event to be dispatched.
8523     * @return True if the event was handled by the view, false otherwise.
8524     */
8525    public boolean dispatchTrackballEvent(MotionEvent event) {
8526        if (mInputEventConsistencyVerifier != null) {
8527            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8528        }
8529
8530        return onTrackballEvent(event);
8531    }
8532
8533    /**
8534     * Dispatch a generic motion event.
8535     * <p>
8536     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8537     * are delivered to the view under the pointer.  All other generic motion events are
8538     * delivered to the focused view.  Hover events are handled specially and are delivered
8539     * to {@link #onHoverEvent(MotionEvent)}.
8540     * </p>
8541     *
8542     * @param event The motion event to be dispatched.
8543     * @return True if the event was handled by the view, false otherwise.
8544     */
8545    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8546        if (mInputEventConsistencyVerifier != null) {
8547            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8548        }
8549
8550        final int source = event.getSource();
8551        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8552            final int action = event.getAction();
8553            if (action == MotionEvent.ACTION_HOVER_ENTER
8554                    || action == MotionEvent.ACTION_HOVER_MOVE
8555                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8556                if (dispatchHoverEvent(event)) {
8557                    return true;
8558                }
8559            } else if (dispatchGenericPointerEvent(event)) {
8560                return true;
8561            }
8562        } else if (dispatchGenericFocusedEvent(event)) {
8563            return true;
8564        }
8565
8566        if (dispatchGenericMotionEventInternal(event)) {
8567            return true;
8568        }
8569
8570        if (mInputEventConsistencyVerifier != null) {
8571            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8572        }
8573        return false;
8574    }
8575
8576    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8577        //noinspection SimplifiableIfStatement
8578        ListenerInfo li = mListenerInfo;
8579        if (li != null && li.mOnGenericMotionListener != null
8580                && (mViewFlags & ENABLED_MASK) == ENABLED
8581                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8582            return true;
8583        }
8584
8585        if (onGenericMotionEvent(event)) {
8586            return true;
8587        }
8588
8589        if (mInputEventConsistencyVerifier != null) {
8590            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8591        }
8592        return false;
8593    }
8594
8595    /**
8596     * Dispatch a hover event.
8597     * <p>
8598     * Do not call this method directly.
8599     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8600     * </p>
8601     *
8602     * @param event The motion event to be dispatched.
8603     * @return True if the event was handled by the view, false otherwise.
8604     */
8605    protected boolean dispatchHoverEvent(MotionEvent event) {
8606        ListenerInfo li = mListenerInfo;
8607        //noinspection SimplifiableIfStatement
8608        if (li != null && li.mOnHoverListener != null
8609                && (mViewFlags & ENABLED_MASK) == ENABLED
8610                && li.mOnHoverListener.onHover(this, event)) {
8611            return true;
8612        }
8613
8614        return onHoverEvent(event);
8615    }
8616
8617    /**
8618     * Returns true if the view has a child to which it has recently sent
8619     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8620     * it does not have a hovered child, then it must be the innermost hovered view.
8621     * @hide
8622     */
8623    protected boolean hasHoveredChild() {
8624        return false;
8625    }
8626
8627    /**
8628     * Dispatch a generic motion event to the view under the first pointer.
8629     * <p>
8630     * Do not call this method directly.
8631     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8632     * </p>
8633     *
8634     * @param event The motion event to be dispatched.
8635     * @return True if the event was handled by the view, false otherwise.
8636     */
8637    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8638        return false;
8639    }
8640
8641    /**
8642     * Dispatch a generic motion event to the currently focused view.
8643     * <p>
8644     * Do not call this method directly.
8645     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8646     * </p>
8647     *
8648     * @param event The motion event to be dispatched.
8649     * @return True if the event was handled by the view, false otherwise.
8650     */
8651    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8652        return false;
8653    }
8654
8655    /**
8656     * Dispatch a pointer event.
8657     * <p>
8658     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8659     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8660     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8661     * and should not be expected to handle other pointing device features.
8662     * </p>
8663     *
8664     * @param event The motion event to be dispatched.
8665     * @return True if the event was handled by the view, false otherwise.
8666     * @hide
8667     */
8668    public final boolean dispatchPointerEvent(MotionEvent event) {
8669        if (event.isTouchEvent()) {
8670            return dispatchTouchEvent(event);
8671        } else {
8672            return dispatchGenericMotionEvent(event);
8673        }
8674    }
8675
8676    /**
8677     * Called when the window containing this view gains or loses window focus.
8678     * ViewGroups should override to route to their children.
8679     *
8680     * @param hasFocus True if the window containing this view now has focus,
8681     *        false otherwise.
8682     */
8683    public void dispatchWindowFocusChanged(boolean hasFocus) {
8684        onWindowFocusChanged(hasFocus);
8685    }
8686
8687    /**
8688     * Called when the window containing this view gains or loses focus.  Note
8689     * that this is separate from view focus: to receive key events, both
8690     * your view and its window must have focus.  If a window is displayed
8691     * on top of yours that takes input focus, then your own window will lose
8692     * focus but the view focus will remain unchanged.
8693     *
8694     * @param hasWindowFocus True if the window containing this view now has
8695     *        focus, false otherwise.
8696     */
8697    public void onWindowFocusChanged(boolean hasWindowFocus) {
8698        InputMethodManager imm = InputMethodManager.peekInstance();
8699        if (!hasWindowFocus) {
8700            if (isPressed()) {
8701                setPressed(false);
8702            }
8703            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8704                imm.focusOut(this);
8705            }
8706            removeLongPressCallback();
8707            removeTapCallback();
8708            onFocusLost();
8709        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8710            imm.focusIn(this);
8711        }
8712        refreshDrawableState();
8713    }
8714
8715    /**
8716     * Returns true if this view is in a window that currently has window focus.
8717     * Note that this is not the same as the view itself having focus.
8718     *
8719     * @return True if this view is in a window that currently has window focus.
8720     */
8721    public boolean hasWindowFocus() {
8722        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8723    }
8724
8725    /**
8726     * Dispatch a view visibility change down the view hierarchy.
8727     * ViewGroups should override to route to their children.
8728     * @param changedView The view whose visibility changed. Could be 'this' or
8729     * an ancestor view.
8730     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8731     * {@link #INVISIBLE} or {@link #GONE}.
8732     */
8733    protected void dispatchVisibilityChanged(@NonNull View changedView,
8734            @Visibility int visibility) {
8735        onVisibilityChanged(changedView, visibility);
8736    }
8737
8738    /**
8739     * Called when the visibility of the view or an ancestor of the view has
8740     * changed.
8741     *
8742     * @param changedView The view whose visibility changed. May be
8743     *                    {@code this} or an ancestor view.
8744     * @param visibility The new visibility, one of {@link #VISIBLE},
8745     *                   {@link #INVISIBLE} or {@link #GONE}.
8746     */
8747    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8748        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
8749        if (visible) {
8750            if (mAttachInfo != null) {
8751                initialAwakenScrollBars();
8752            } else {
8753                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8754            }
8755        }
8756
8757        final Drawable dr = mBackground;
8758        if (dr != null && visible != dr.isVisible()) {
8759            dr.setVisible(visible, false);
8760        }
8761    }
8762
8763    /**
8764     * Dispatch a hint about whether this view is displayed. For instance, when
8765     * a View moves out of the screen, it might receives a display hint indicating
8766     * the view is not displayed. Applications should not <em>rely</em> on this hint
8767     * as there is no guarantee that they will receive one.
8768     *
8769     * @param hint A hint about whether or not this view is displayed:
8770     * {@link #VISIBLE} or {@link #INVISIBLE}.
8771     */
8772    public void dispatchDisplayHint(@Visibility int hint) {
8773        onDisplayHint(hint);
8774    }
8775
8776    /**
8777     * Gives this view a hint about whether is displayed or not. For instance, when
8778     * a View moves out of the screen, it might receives a display hint indicating
8779     * the view is not displayed. Applications should not <em>rely</em> on this hint
8780     * as there is no guarantee that they will receive one.
8781     *
8782     * @param hint A hint about whether or not this view is displayed:
8783     * {@link #VISIBLE} or {@link #INVISIBLE}.
8784     */
8785    protected void onDisplayHint(@Visibility int hint) {
8786    }
8787
8788    /**
8789     * Dispatch a window visibility change down the view hierarchy.
8790     * ViewGroups should override to route to their children.
8791     *
8792     * @param visibility The new visibility of the window.
8793     *
8794     * @see #onWindowVisibilityChanged(int)
8795     */
8796    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8797        onWindowVisibilityChanged(visibility);
8798    }
8799
8800    /**
8801     * Called when the window containing has change its visibility
8802     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8803     * that this tells you whether or not your window is being made visible
8804     * to the window manager; this does <em>not</em> tell you whether or not
8805     * your window is obscured by other windows on the screen, even if it
8806     * is itself visible.
8807     *
8808     * @param visibility The new visibility of the window.
8809     */
8810    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8811        if (visibility == VISIBLE) {
8812            initialAwakenScrollBars();
8813        }
8814    }
8815
8816    /**
8817     * Returns the current visibility of the window this view is attached to
8818     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8819     *
8820     * @return Returns the current visibility of the view's window.
8821     */
8822    @Visibility
8823    public int getWindowVisibility() {
8824        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8825    }
8826
8827    /**
8828     * Retrieve the overall visible display size in which the window this view is
8829     * attached to has been positioned in.  This takes into account screen
8830     * decorations above the window, for both cases where the window itself
8831     * is being position inside of them or the window is being placed under
8832     * then and covered insets are used for the window to position its content
8833     * inside.  In effect, this tells you the available area where content can
8834     * be placed and remain visible to users.
8835     *
8836     * <p>This function requires an IPC back to the window manager to retrieve
8837     * the requested information, so should not be used in performance critical
8838     * code like drawing.
8839     *
8840     * @param outRect Filled in with the visible display frame.  If the view
8841     * is not attached to a window, this is simply the raw display size.
8842     */
8843    public void getWindowVisibleDisplayFrame(Rect outRect) {
8844        if (mAttachInfo != null) {
8845            try {
8846                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8847            } catch (RemoteException e) {
8848                return;
8849            }
8850            // XXX This is really broken, and probably all needs to be done
8851            // in the window manager, and we need to know more about whether
8852            // we want the area behind or in front of the IME.
8853            final Rect insets = mAttachInfo.mVisibleInsets;
8854            outRect.left += insets.left;
8855            outRect.top += insets.top;
8856            outRect.right -= insets.right;
8857            outRect.bottom -= insets.bottom;
8858            return;
8859        }
8860        // The view is not attached to a display so we don't have a context.
8861        // Make a best guess about the display size.
8862        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8863        d.getRectSize(outRect);
8864    }
8865
8866    /**
8867     * Dispatch a notification about a resource configuration change down
8868     * the view hierarchy.
8869     * ViewGroups should override to route to their children.
8870     *
8871     * @param newConfig The new resource configuration.
8872     *
8873     * @see #onConfigurationChanged(android.content.res.Configuration)
8874     */
8875    public void dispatchConfigurationChanged(Configuration newConfig) {
8876        onConfigurationChanged(newConfig);
8877    }
8878
8879    /**
8880     * Called when the current configuration of the resources being used
8881     * by the application have changed.  You can use this to decide when
8882     * to reload resources that can changed based on orientation and other
8883     * configuration characteristics.  You only need to use this if you are
8884     * not relying on the normal {@link android.app.Activity} mechanism of
8885     * recreating the activity instance upon a configuration change.
8886     *
8887     * @param newConfig The new resource configuration.
8888     */
8889    protected void onConfigurationChanged(Configuration newConfig) {
8890    }
8891
8892    /**
8893     * Private function to aggregate all per-view attributes in to the view
8894     * root.
8895     */
8896    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8897        performCollectViewAttributes(attachInfo, visibility);
8898    }
8899
8900    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8901        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8902            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8903                attachInfo.mKeepScreenOn = true;
8904            }
8905            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8906            ListenerInfo li = mListenerInfo;
8907            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8908                attachInfo.mHasSystemUiListeners = true;
8909            }
8910        }
8911    }
8912
8913    void needGlobalAttributesUpdate(boolean force) {
8914        final AttachInfo ai = mAttachInfo;
8915        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8916            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8917                    || ai.mHasSystemUiListeners) {
8918                ai.mRecomputeGlobalAttributes = true;
8919            }
8920        }
8921    }
8922
8923    /**
8924     * Returns whether the device is currently in touch mode.  Touch mode is entered
8925     * once the user begins interacting with the device by touch, and affects various
8926     * things like whether focus is always visible to the user.
8927     *
8928     * @return Whether the device is in touch mode.
8929     */
8930    @ViewDebug.ExportedProperty
8931    public boolean isInTouchMode() {
8932        if (mAttachInfo != null) {
8933            return mAttachInfo.mInTouchMode;
8934        } else {
8935            return ViewRootImpl.isInTouchMode();
8936        }
8937    }
8938
8939    /**
8940     * Returns the context the view is running in, through which it can
8941     * access the current theme, resources, etc.
8942     *
8943     * @return The view's Context.
8944     */
8945    @ViewDebug.CapturedViewProperty
8946    public final Context getContext() {
8947        return mContext;
8948    }
8949
8950    /**
8951     * Handle a key event before it is processed by any input method
8952     * associated with the view hierarchy.  This can be used to intercept
8953     * key events in special situations before the IME consumes them; a
8954     * typical example would be handling the BACK key to update the application's
8955     * UI instead of allowing the IME to see it and close itself.
8956     *
8957     * @param keyCode The value in event.getKeyCode().
8958     * @param event Description of the key event.
8959     * @return If you handled the event, return true. If you want to allow the
8960     *         event to be handled by the next receiver, return false.
8961     */
8962    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8963        return false;
8964    }
8965
8966    /**
8967     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8968     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8969     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8970     * is released, if the view is enabled and clickable.
8971     *
8972     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8973     * although some may elect to do so in some situations. Do not rely on this to
8974     * catch software key presses.
8975     *
8976     * @param keyCode A key code that represents the button pressed, from
8977     *                {@link android.view.KeyEvent}.
8978     * @param event   The KeyEvent object that defines the button action.
8979     */
8980    public boolean onKeyDown(int keyCode, KeyEvent event) {
8981        boolean result = false;
8982
8983        if (KeyEvent.isConfirmKey(keyCode)) {
8984            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8985                return true;
8986            }
8987            // Long clickable items don't necessarily have to be clickable
8988            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8989                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8990                    (event.getRepeatCount() == 0)) {
8991                setPressed(true);
8992                checkForLongClick(0);
8993                return true;
8994            }
8995        }
8996        return result;
8997    }
8998
8999    /**
9000     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9001     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9002     * the event).
9003     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9004     * although some may elect to do so in some situations. Do not rely on this to
9005     * catch software key presses.
9006     */
9007    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9008        return false;
9009    }
9010
9011    /**
9012     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9013     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9014     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9015     * {@link KeyEvent#KEYCODE_ENTER} is released.
9016     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9017     * although some may elect to do so in some situations. Do not rely on this to
9018     * catch software key presses.
9019     *
9020     * @param keyCode A key code that represents the button pressed, from
9021     *                {@link android.view.KeyEvent}.
9022     * @param event   The KeyEvent object that defines the button action.
9023     */
9024    public boolean onKeyUp(int keyCode, KeyEvent event) {
9025        if (KeyEvent.isConfirmKey(keyCode)) {
9026            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9027                return true;
9028            }
9029            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9030                setPressed(false);
9031
9032                if (!mHasPerformedLongPress) {
9033                    // This is a tap, so remove the longpress check
9034                    removeLongPressCallback();
9035                    return performClick();
9036                }
9037            }
9038        }
9039        return false;
9040    }
9041
9042    /**
9043     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9044     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9045     * the event).
9046     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9047     * although some may elect to do so in some situations. Do not rely on this to
9048     * catch software key presses.
9049     *
9050     * @param keyCode     A key code that represents the button pressed, from
9051     *                    {@link android.view.KeyEvent}.
9052     * @param repeatCount The number of times the action was made.
9053     * @param event       The KeyEvent object that defines the button action.
9054     */
9055    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9056        return false;
9057    }
9058
9059    /**
9060     * Called on the focused view when a key shortcut event is not handled.
9061     * Override this method to implement local key shortcuts for the View.
9062     * Key shortcuts can also be implemented by setting the
9063     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9064     *
9065     * @param keyCode The value in event.getKeyCode().
9066     * @param event Description of the key event.
9067     * @return If you handled the event, return true. If you want to allow the
9068     *         event to be handled by the next receiver, return false.
9069     */
9070    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9071        return false;
9072    }
9073
9074    /**
9075     * Check whether the called view is a text editor, in which case it
9076     * would make sense to automatically display a soft input window for
9077     * it.  Subclasses should override this if they implement
9078     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9079     * a call on that method would return a non-null InputConnection, and
9080     * they are really a first-class editor that the user would normally
9081     * start typing on when the go into a window containing your view.
9082     *
9083     * <p>The default implementation always returns false.  This does
9084     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9085     * will not be called or the user can not otherwise perform edits on your
9086     * view; it is just a hint to the system that this is not the primary
9087     * purpose of this view.
9088     *
9089     * @return Returns true if this view is a text editor, else false.
9090     */
9091    public boolean onCheckIsTextEditor() {
9092        return false;
9093    }
9094
9095    /**
9096     * Create a new InputConnection for an InputMethod to interact
9097     * with the view.  The default implementation returns null, since it doesn't
9098     * support input methods.  You can override this to implement such support.
9099     * This is only needed for views that take focus and text input.
9100     *
9101     * <p>When implementing this, you probably also want to implement
9102     * {@link #onCheckIsTextEditor()} to indicate you will return a
9103     * non-null InputConnection.</p>
9104     *
9105     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9106     * object correctly and in its entirety, so that the connected IME can rely
9107     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9108     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9109     * must be filled in with the correct cursor position for IMEs to work correctly
9110     * with your application.</p>
9111     *
9112     * @param outAttrs Fill in with attribute information about the connection.
9113     */
9114    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9115        return null;
9116    }
9117
9118    /**
9119     * Called by the {@link android.view.inputmethod.InputMethodManager}
9120     * when a view who is not the current
9121     * input connection target is trying to make a call on the manager.  The
9122     * default implementation returns false; you can override this to return
9123     * true for certain views if you are performing InputConnection proxying
9124     * to them.
9125     * @param view The View that is making the InputMethodManager call.
9126     * @return Return true to allow the call, false to reject.
9127     */
9128    public boolean checkInputConnectionProxy(View view) {
9129        return false;
9130    }
9131
9132    /**
9133     * Show the context menu for this view. It is not safe to hold on to the
9134     * menu after returning from this method.
9135     *
9136     * You should normally not overload this method. Overload
9137     * {@link #onCreateContextMenu(ContextMenu)} or define an
9138     * {@link OnCreateContextMenuListener} to add items to the context menu.
9139     *
9140     * @param menu The context menu to populate
9141     */
9142    public void createContextMenu(ContextMenu menu) {
9143        ContextMenuInfo menuInfo = getContextMenuInfo();
9144
9145        // Sets the current menu info so all items added to menu will have
9146        // my extra info set.
9147        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9148
9149        onCreateContextMenu(menu);
9150        ListenerInfo li = mListenerInfo;
9151        if (li != null && li.mOnCreateContextMenuListener != null) {
9152            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9153        }
9154
9155        // Clear the extra information so subsequent items that aren't mine don't
9156        // have my extra info.
9157        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9158
9159        if (mParent != null) {
9160            mParent.createContextMenu(menu);
9161        }
9162    }
9163
9164    /**
9165     * Views should implement this if they have extra information to associate
9166     * with the context menu. The return result is supplied as a parameter to
9167     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9168     * callback.
9169     *
9170     * @return Extra information about the item for which the context menu
9171     *         should be shown. This information will vary across different
9172     *         subclasses of View.
9173     */
9174    protected ContextMenuInfo getContextMenuInfo() {
9175        return null;
9176    }
9177
9178    /**
9179     * Views should implement this if the view itself is going to add items to
9180     * the context menu.
9181     *
9182     * @param menu the context menu to populate
9183     */
9184    protected void onCreateContextMenu(ContextMenu menu) {
9185    }
9186
9187    /**
9188     * Implement this method to handle trackball motion events.  The
9189     * <em>relative</em> movement of the trackball since the last event
9190     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9191     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9192     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9193     * they will often be fractional values, representing the more fine-grained
9194     * movement information available from a trackball).
9195     *
9196     * @param event The motion event.
9197     * @return True if the event was handled, false otherwise.
9198     */
9199    public boolean onTrackballEvent(MotionEvent event) {
9200        return false;
9201    }
9202
9203    /**
9204     * Implement this method to handle generic motion events.
9205     * <p>
9206     * Generic motion events describe joystick movements, mouse hovers, track pad
9207     * touches, scroll wheel movements and other input events.  The
9208     * {@link MotionEvent#getSource() source} of the motion event specifies
9209     * the class of input that was received.  Implementations of this method
9210     * must examine the bits in the source before processing the event.
9211     * The following code example shows how this is done.
9212     * </p><p>
9213     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9214     * are delivered to the view under the pointer.  All other generic motion events are
9215     * delivered to the focused view.
9216     * </p>
9217     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9218     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9219     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9220     *             // process the joystick movement...
9221     *             return true;
9222     *         }
9223     *     }
9224     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9225     *         switch (event.getAction()) {
9226     *             case MotionEvent.ACTION_HOVER_MOVE:
9227     *                 // process the mouse hover movement...
9228     *                 return true;
9229     *             case MotionEvent.ACTION_SCROLL:
9230     *                 // process the scroll wheel movement...
9231     *                 return true;
9232     *         }
9233     *     }
9234     *     return super.onGenericMotionEvent(event);
9235     * }</pre>
9236     *
9237     * @param event The generic motion event being processed.
9238     * @return True if the event was handled, false otherwise.
9239     */
9240    public boolean onGenericMotionEvent(MotionEvent event) {
9241        return false;
9242    }
9243
9244    /**
9245     * Implement this method to handle hover events.
9246     * <p>
9247     * This method is called whenever a pointer is hovering into, over, or out of the
9248     * bounds of a view and the view is not currently being touched.
9249     * Hover events are represented as pointer events with action
9250     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9251     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9252     * </p>
9253     * <ul>
9254     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9255     * when the pointer enters the bounds of the view.</li>
9256     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9257     * when the pointer has already entered the bounds of the view and has moved.</li>
9258     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9259     * when the pointer has exited the bounds of the view or when the pointer is
9260     * about to go down due to a button click, tap, or similar user action that
9261     * causes the view to be touched.</li>
9262     * </ul>
9263     * <p>
9264     * The view should implement this method to return true to indicate that it is
9265     * handling the hover event, such as by changing its drawable state.
9266     * </p><p>
9267     * The default implementation calls {@link #setHovered} to update the hovered state
9268     * of the view when a hover enter or hover exit event is received, if the view
9269     * is enabled and is clickable.  The default implementation also sends hover
9270     * accessibility events.
9271     * </p>
9272     *
9273     * @param event The motion event that describes the hover.
9274     * @return True if the view handled the hover event.
9275     *
9276     * @see #isHovered
9277     * @see #setHovered
9278     * @see #onHoverChanged
9279     */
9280    public boolean onHoverEvent(MotionEvent event) {
9281        // The root view may receive hover (or touch) events that are outside the bounds of
9282        // the window.  This code ensures that we only send accessibility events for
9283        // hovers that are actually within the bounds of the root view.
9284        final int action = event.getActionMasked();
9285        if (!mSendingHoverAccessibilityEvents) {
9286            if ((action == MotionEvent.ACTION_HOVER_ENTER
9287                    || action == MotionEvent.ACTION_HOVER_MOVE)
9288                    && !hasHoveredChild()
9289                    && pointInView(event.getX(), event.getY())) {
9290                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9291                mSendingHoverAccessibilityEvents = true;
9292            }
9293        } else {
9294            if (action == MotionEvent.ACTION_HOVER_EXIT
9295                    || (action == MotionEvent.ACTION_MOVE
9296                            && !pointInView(event.getX(), event.getY()))) {
9297                mSendingHoverAccessibilityEvents = false;
9298                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9299            }
9300        }
9301
9302        if (isHoverable()) {
9303            switch (action) {
9304                case MotionEvent.ACTION_HOVER_ENTER:
9305                    setHovered(true);
9306                    break;
9307                case MotionEvent.ACTION_HOVER_EXIT:
9308                    setHovered(false);
9309                    break;
9310            }
9311
9312            // Dispatch the event to onGenericMotionEvent before returning true.
9313            // This is to provide compatibility with existing applications that
9314            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9315            // break because of the new default handling for hoverable views
9316            // in onHoverEvent.
9317            // Note that onGenericMotionEvent will be called by default when
9318            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9319            dispatchGenericMotionEventInternal(event);
9320            // The event was already handled by calling setHovered(), so always
9321            // return true.
9322            return true;
9323        }
9324
9325        return false;
9326    }
9327
9328    /**
9329     * Returns true if the view should handle {@link #onHoverEvent}
9330     * by calling {@link #setHovered} to change its hovered state.
9331     *
9332     * @return True if the view is hoverable.
9333     */
9334    private boolean isHoverable() {
9335        final int viewFlags = mViewFlags;
9336        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9337            return false;
9338        }
9339
9340        return (viewFlags & CLICKABLE) == CLICKABLE
9341                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9342    }
9343
9344    /**
9345     * Returns true if the view is currently hovered.
9346     *
9347     * @return True if the view is currently hovered.
9348     *
9349     * @see #setHovered
9350     * @see #onHoverChanged
9351     */
9352    @ViewDebug.ExportedProperty
9353    public boolean isHovered() {
9354        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9355    }
9356
9357    /**
9358     * Sets whether the view is currently hovered.
9359     * <p>
9360     * Calling this method also changes the drawable state of the view.  This
9361     * enables the view to react to hover by using different drawable resources
9362     * to change its appearance.
9363     * </p><p>
9364     * The {@link #onHoverChanged} method is called when the hovered state changes.
9365     * </p>
9366     *
9367     * @param hovered True if the view is hovered.
9368     *
9369     * @see #isHovered
9370     * @see #onHoverChanged
9371     */
9372    public void setHovered(boolean hovered) {
9373        if (hovered) {
9374            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9375                mPrivateFlags |= PFLAG_HOVERED;
9376                refreshDrawableState();
9377                onHoverChanged(true);
9378            }
9379        } else {
9380            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9381                mPrivateFlags &= ~PFLAG_HOVERED;
9382                refreshDrawableState();
9383                onHoverChanged(false);
9384            }
9385        }
9386    }
9387
9388    /**
9389     * Implement this method to handle hover state changes.
9390     * <p>
9391     * This method is called whenever the hover state changes as a result of a
9392     * call to {@link #setHovered}.
9393     * </p>
9394     *
9395     * @param hovered The current hover state, as returned by {@link #isHovered}.
9396     *
9397     * @see #isHovered
9398     * @see #setHovered
9399     */
9400    public void onHoverChanged(boolean hovered) {
9401    }
9402
9403    /**
9404     * Implement this method to handle touch screen motion events.
9405     * <p>
9406     * If this method is used to detect click actions, it is recommended that
9407     * the actions be performed by implementing and calling
9408     * {@link #performClick()}. This will ensure consistent system behavior,
9409     * including:
9410     * <ul>
9411     * <li>obeying click sound preferences
9412     * <li>dispatching OnClickListener calls
9413     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9414     * accessibility features are enabled
9415     * </ul>
9416     *
9417     * @param event The motion event.
9418     * @return True if the event was handled, false otherwise.
9419     */
9420    public boolean onTouchEvent(MotionEvent event) {
9421        final float x = event.getX();
9422        final float y = event.getY();
9423        final int viewFlags = mViewFlags;
9424
9425        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9426            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9427                setPressed(false);
9428            }
9429            // A disabled view that is clickable still consumes the touch
9430            // events, it just doesn't respond to them.
9431            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9432                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9433        }
9434
9435        if (mTouchDelegate != null) {
9436            if (mTouchDelegate.onTouchEvent(event)) {
9437                return true;
9438            }
9439        }
9440
9441        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9442                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9443            switch (event.getAction()) {
9444                case MotionEvent.ACTION_UP:
9445                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9446                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9447                        // take focus if we don't have it already and we should in
9448                        // touch mode.
9449                        boolean focusTaken = false;
9450                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9451                            focusTaken = requestFocus();
9452                        }
9453
9454                        if (prepressed) {
9455                            // The button is being released before we actually
9456                            // showed it as pressed.  Make it show the pressed
9457                            // state now (before scheduling the click) to ensure
9458                            // the user sees it.
9459                            setPressed(true, x, y);
9460                       }
9461
9462                        if (!mHasPerformedLongPress) {
9463                            // This is a tap, so remove the longpress check
9464                            removeLongPressCallback();
9465
9466                            // Only perform take click actions if we were in the pressed state
9467                            if (!focusTaken) {
9468                                // Use a Runnable and post this rather than calling
9469                                // performClick directly. This lets other visual state
9470                                // of the view update before click actions start.
9471                                if (mPerformClick == null) {
9472                                    mPerformClick = new PerformClick();
9473                                }
9474                                if (!post(mPerformClick)) {
9475                                    performClick();
9476                                }
9477                            }
9478                        }
9479
9480                        if (mUnsetPressedState == null) {
9481                            mUnsetPressedState = new UnsetPressedState();
9482                        }
9483
9484                        if (prepressed) {
9485                            postDelayed(mUnsetPressedState,
9486                                    ViewConfiguration.getPressedStateDuration());
9487                        } else if (!post(mUnsetPressedState)) {
9488                            // If the post failed, unpress right now
9489                            mUnsetPressedState.run();
9490                        }
9491
9492                        removeTapCallback();
9493                    }
9494                    break;
9495
9496                case MotionEvent.ACTION_DOWN:
9497                    mHasPerformedLongPress = false;
9498
9499                    if (performButtonActionOnTouchDown(event)) {
9500                        break;
9501                    }
9502
9503                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9504                    boolean isInScrollingContainer = isInScrollingContainer();
9505
9506                    // For views inside a scrolling container, delay the pressed feedback for
9507                    // a short period in case this is a scroll.
9508                    if (isInScrollingContainer) {
9509                        mPrivateFlags |= PFLAG_PREPRESSED;
9510                        if (mPendingCheckForTap == null) {
9511                            mPendingCheckForTap = new CheckForTap();
9512                        }
9513                        mPendingCheckForTap.x = event.getX();
9514                        mPendingCheckForTap.y = event.getY();
9515                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9516                    } else {
9517                        // Not inside a scrolling container, so show the feedback right away
9518                        setPressed(true, x, y);
9519                        checkForLongClick(0);
9520                    }
9521                    break;
9522
9523                case MotionEvent.ACTION_CANCEL:
9524                    setPressed(false);
9525                    removeTapCallback();
9526                    removeLongPressCallback();
9527                    break;
9528
9529                case MotionEvent.ACTION_MOVE:
9530                    drawableHotspotChanged(x, y);
9531
9532                    // Be lenient about moving outside of buttons
9533                    if (!pointInView(x, y, mTouchSlop)) {
9534                        // Outside button
9535                        removeTapCallback();
9536                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9537                            // Remove any future long press/tap checks
9538                            removeLongPressCallback();
9539
9540                            setPressed(false);
9541                        }
9542                    }
9543                    break;
9544            }
9545
9546            return true;
9547        }
9548
9549        return false;
9550    }
9551
9552    /**
9553     * @hide
9554     */
9555    public boolean isInScrollingContainer() {
9556        ViewParent p = getParent();
9557        while (p != null && p instanceof ViewGroup) {
9558            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9559                return true;
9560            }
9561            p = p.getParent();
9562        }
9563        return false;
9564    }
9565
9566    /**
9567     * Remove the longpress detection timer.
9568     */
9569    private void removeLongPressCallback() {
9570        if (mPendingCheckForLongPress != null) {
9571          removeCallbacks(mPendingCheckForLongPress);
9572        }
9573    }
9574
9575    /**
9576     * Remove the pending click action
9577     */
9578    private void removePerformClickCallback() {
9579        if (mPerformClick != null) {
9580            removeCallbacks(mPerformClick);
9581        }
9582    }
9583
9584    /**
9585     * Remove the prepress detection timer.
9586     */
9587    private void removeUnsetPressCallback() {
9588        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9589            setPressed(false);
9590            removeCallbacks(mUnsetPressedState);
9591        }
9592    }
9593
9594    /**
9595     * Remove the tap detection timer.
9596     */
9597    private void removeTapCallback() {
9598        if (mPendingCheckForTap != null) {
9599            mPrivateFlags &= ~PFLAG_PREPRESSED;
9600            removeCallbacks(mPendingCheckForTap);
9601        }
9602    }
9603
9604    /**
9605     * Cancels a pending long press.  Your subclass can use this if you
9606     * want the context menu to come up if the user presses and holds
9607     * at the same place, but you don't want it to come up if they press
9608     * and then move around enough to cause scrolling.
9609     */
9610    public void cancelLongPress() {
9611        removeLongPressCallback();
9612
9613        /*
9614         * The prepressed state handled by the tap callback is a display
9615         * construct, but the tap callback will post a long press callback
9616         * less its own timeout. Remove it here.
9617         */
9618        removeTapCallback();
9619    }
9620
9621    /**
9622     * Remove the pending callback for sending a
9623     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9624     */
9625    private void removeSendViewScrolledAccessibilityEventCallback() {
9626        if (mSendViewScrolledAccessibilityEvent != null) {
9627            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9628            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9629        }
9630    }
9631
9632    /**
9633     * Sets the TouchDelegate for this View.
9634     */
9635    public void setTouchDelegate(TouchDelegate delegate) {
9636        mTouchDelegate = delegate;
9637    }
9638
9639    /**
9640     * Gets the TouchDelegate for this View.
9641     */
9642    public TouchDelegate getTouchDelegate() {
9643        return mTouchDelegate;
9644    }
9645
9646    /**
9647     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9648     *
9649     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9650     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9651     * available. This method should only be called for touch events.
9652     *
9653     * <p class="note">This api is not intended for most applications. Buffered dispatch
9654     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9655     * streams will not improve your input latency. Side effects include: increased latency,
9656     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9657     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9658     * you.</p>
9659     */
9660    public final void requestUnbufferedDispatch(MotionEvent event) {
9661        final int action = event.getAction();
9662        if (mAttachInfo == null
9663                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9664                || !event.isTouchEvent()) {
9665            return;
9666        }
9667        mAttachInfo.mUnbufferedDispatchRequested = true;
9668    }
9669
9670    /**
9671     * Set flags controlling behavior of this view.
9672     *
9673     * @param flags Constant indicating the value which should be set
9674     * @param mask Constant indicating the bit range that should be changed
9675     */
9676    void setFlags(int flags, int mask) {
9677        final boolean accessibilityEnabled =
9678                AccessibilityManager.getInstance(mContext).isEnabled();
9679        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9680
9681        int old = mViewFlags;
9682        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9683
9684        int changed = mViewFlags ^ old;
9685        if (changed == 0) {
9686            return;
9687        }
9688        int privateFlags = mPrivateFlags;
9689
9690        /* Check if the FOCUSABLE bit has changed */
9691        if (((changed & FOCUSABLE_MASK) != 0) &&
9692                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9693            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9694                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9695                /* Give up focus if we are no longer focusable */
9696                clearFocus();
9697            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9698                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9699                /*
9700                 * Tell the view system that we are now available to take focus
9701                 * if no one else already has it.
9702                 */
9703                if (mParent != null) mParent.focusableViewAvailable(this);
9704            }
9705        }
9706
9707        final int newVisibility = flags & VISIBILITY_MASK;
9708        if (newVisibility == VISIBLE) {
9709            if ((changed & VISIBILITY_MASK) != 0) {
9710                /*
9711                 * If this view is becoming visible, invalidate it in case it changed while
9712                 * it was not visible. Marking it drawn ensures that the invalidation will
9713                 * go through.
9714                 */
9715                mPrivateFlags |= PFLAG_DRAWN;
9716                invalidate(true);
9717
9718                needGlobalAttributesUpdate(true);
9719
9720                // a view becoming visible is worth notifying the parent
9721                // about in case nothing has focus.  even if this specific view
9722                // isn't focusable, it may contain something that is, so let
9723                // the root view try to give this focus if nothing else does.
9724                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9725                    mParent.focusableViewAvailable(this);
9726                }
9727            }
9728        }
9729
9730        /* Check if the GONE bit has changed */
9731        if ((changed & GONE) != 0) {
9732            needGlobalAttributesUpdate(false);
9733            requestLayout();
9734
9735            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9736                if (hasFocus()) clearFocus();
9737                clearAccessibilityFocus();
9738                destroyDrawingCache();
9739                if (mParent instanceof View) {
9740                    // GONE views noop invalidation, so invalidate the parent
9741                    ((View) mParent).invalidate(true);
9742                }
9743                // Mark the view drawn to ensure that it gets invalidated properly the next
9744                // time it is visible and gets invalidated
9745                mPrivateFlags |= PFLAG_DRAWN;
9746            }
9747            if (mAttachInfo != null) {
9748                mAttachInfo.mViewVisibilityChanged = true;
9749            }
9750        }
9751
9752        /* Check if the VISIBLE bit has changed */
9753        if ((changed & INVISIBLE) != 0) {
9754            needGlobalAttributesUpdate(false);
9755            /*
9756             * If this view is becoming invisible, set the DRAWN flag so that
9757             * the next invalidate() will not be skipped.
9758             */
9759            mPrivateFlags |= PFLAG_DRAWN;
9760
9761            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9762                // root view becoming invisible shouldn't clear focus and accessibility focus
9763                if (getRootView() != this) {
9764                    if (hasFocus()) clearFocus();
9765                    clearAccessibilityFocus();
9766                }
9767            }
9768            if (mAttachInfo != null) {
9769                mAttachInfo.mViewVisibilityChanged = true;
9770            }
9771        }
9772
9773        if ((changed & VISIBILITY_MASK) != 0) {
9774            // If the view is invisible, cleanup its display list to free up resources
9775            if (newVisibility != VISIBLE && mAttachInfo != null) {
9776                cleanupDraw();
9777            }
9778
9779            if (mParent instanceof ViewGroup) {
9780                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9781                        (changed & VISIBILITY_MASK), newVisibility);
9782                ((View) mParent).invalidate(true);
9783            } else if (mParent != null) {
9784                mParent.invalidateChild(this, null);
9785            }
9786            dispatchVisibilityChanged(this, newVisibility);
9787
9788            notifySubtreeAccessibilityStateChangedIfNeeded();
9789        }
9790
9791        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9792            destroyDrawingCache();
9793        }
9794
9795        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9796            destroyDrawingCache();
9797            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9798            invalidateParentCaches();
9799        }
9800
9801        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9802            destroyDrawingCache();
9803            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9804        }
9805
9806        if ((changed & DRAW_MASK) != 0) {
9807            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9808                if (mBackground != null) {
9809                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9810                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9811                } else {
9812                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9813                }
9814            } else {
9815                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9816            }
9817            requestLayout();
9818            invalidate(true);
9819        }
9820
9821        if ((changed & KEEP_SCREEN_ON) != 0) {
9822            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9823                mParent.recomputeViewAttributes(this);
9824            }
9825        }
9826
9827        if (accessibilityEnabled) {
9828            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9829                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9830                if (oldIncludeForAccessibility != includeForAccessibility()) {
9831                    notifySubtreeAccessibilityStateChangedIfNeeded();
9832                } else {
9833                    notifyViewAccessibilityStateChangedIfNeeded(
9834                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9835                }
9836            } else if ((changed & ENABLED_MASK) != 0) {
9837                notifyViewAccessibilityStateChangedIfNeeded(
9838                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9839            }
9840        }
9841    }
9842
9843    /**
9844     * Change the view's z order in the tree, so it's on top of other sibling
9845     * views. This ordering change may affect layout, if the parent container
9846     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9847     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9848     * method should be followed by calls to {@link #requestLayout()} and
9849     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9850     * with the new child ordering.
9851     *
9852     * @see ViewGroup#bringChildToFront(View)
9853     */
9854    public void bringToFront() {
9855        if (mParent != null) {
9856            mParent.bringChildToFront(this);
9857        }
9858    }
9859
9860    /**
9861     * This is called in response to an internal scroll in this view (i.e., the
9862     * view scrolled its own contents). This is typically as a result of
9863     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9864     * called.
9865     *
9866     * @param l Current horizontal scroll origin.
9867     * @param t Current vertical scroll origin.
9868     * @param oldl Previous horizontal scroll origin.
9869     * @param oldt Previous vertical scroll origin.
9870     */
9871    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9872        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9873            postSendViewScrolledAccessibilityEventCallback();
9874        }
9875
9876        mBackgroundSizeChanged = true;
9877
9878        final AttachInfo ai = mAttachInfo;
9879        if (ai != null) {
9880            ai.mViewScrollChanged = true;
9881        }
9882
9883        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
9884            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
9885        }
9886    }
9887
9888    /**
9889     * Interface definition for a callback to be invoked when the scroll
9890     * X or Y positions of a view change.
9891     * <p>
9892     * <b>Note:</b> Some views handle scrolling independently from View and may
9893     * have their own separate listeners for scroll-type events. For example,
9894     * {@link android.widget.ListView ListView} allows clients to register an
9895     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
9896     * to listen for changes in list scroll position.
9897     *
9898     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
9899     */
9900    public interface OnScrollChangeListener {
9901        /**
9902         * Called when the scroll position of a view changes.
9903         *
9904         * @param v The view whose scroll position has changed.
9905         * @param scrollX Current horizontal scroll origin.
9906         * @param scrollY Current vertical scroll origin.
9907         * @param oldScrollX Previous horizontal scroll origin.
9908         * @param oldScrollY Previous vertical scroll origin.
9909         */
9910        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
9911    }
9912
9913    /**
9914     * Interface definition for a callback to be invoked when the layout bounds of a view
9915     * changes due to layout processing.
9916     */
9917    public interface OnLayoutChangeListener {
9918        /**
9919         * Called when the layout bounds of a view changes due to layout processing.
9920         *
9921         * @param v The view whose bounds have changed.
9922         * @param left The new value of the view's left property.
9923         * @param top The new value of the view's top property.
9924         * @param right The new value of the view's right property.
9925         * @param bottom The new value of the view's bottom property.
9926         * @param oldLeft The previous value of the view's left property.
9927         * @param oldTop The previous value of the view's top property.
9928         * @param oldRight The previous value of the view's right property.
9929         * @param oldBottom The previous value of the view's bottom property.
9930         */
9931        void onLayoutChange(View v, int left, int top, int right, int bottom,
9932            int oldLeft, int oldTop, int oldRight, int oldBottom);
9933    }
9934
9935    /**
9936     * This is called during layout when the size of this view has changed. If
9937     * you were just added to the view hierarchy, you're called with the old
9938     * values of 0.
9939     *
9940     * @param w Current width of this view.
9941     * @param h Current height of this view.
9942     * @param oldw Old width of this view.
9943     * @param oldh Old height of this view.
9944     */
9945    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9946    }
9947
9948    /**
9949     * Called by draw to draw the child views. This may be overridden
9950     * by derived classes to gain control just before its children are drawn
9951     * (but after its own view has been drawn).
9952     * @param canvas the canvas on which to draw the view
9953     */
9954    protected void dispatchDraw(Canvas canvas) {
9955
9956    }
9957
9958    /**
9959     * Gets the parent of this view. Note that the parent is a
9960     * ViewParent and not necessarily a View.
9961     *
9962     * @return Parent of this view.
9963     */
9964    public final ViewParent getParent() {
9965        return mParent;
9966    }
9967
9968    /**
9969     * Set the horizontal scrolled position of your view. This will cause a call to
9970     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9971     * invalidated.
9972     * @param value the x position to scroll to
9973     */
9974    public void setScrollX(int value) {
9975        scrollTo(value, mScrollY);
9976    }
9977
9978    /**
9979     * Set the vertical scrolled position of your view. This will cause a call to
9980     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9981     * invalidated.
9982     * @param value the y position to scroll to
9983     */
9984    public void setScrollY(int value) {
9985        scrollTo(mScrollX, value);
9986    }
9987
9988    /**
9989     * Return the scrolled left position of this view. This is the left edge of
9990     * the displayed part of your view. You do not need to draw any pixels
9991     * farther left, since those are outside of the frame of your view on
9992     * screen.
9993     *
9994     * @return The left edge of the displayed part of your view, in pixels.
9995     */
9996    public final int getScrollX() {
9997        return mScrollX;
9998    }
9999
10000    /**
10001     * Return the scrolled top position of this view. This is the top edge of
10002     * the displayed part of your view. You do not need to draw any pixels above
10003     * it, since those are outside of the frame of your view on screen.
10004     *
10005     * @return The top edge of the displayed part of your view, in pixels.
10006     */
10007    public final int getScrollY() {
10008        return mScrollY;
10009    }
10010
10011    /**
10012     * Return the width of the your view.
10013     *
10014     * @return The width of your view, in pixels.
10015     */
10016    @ViewDebug.ExportedProperty(category = "layout")
10017    public final int getWidth() {
10018        return mRight - mLeft;
10019    }
10020
10021    /**
10022     * Return the height of your view.
10023     *
10024     * @return The height of your view, in pixels.
10025     */
10026    @ViewDebug.ExportedProperty(category = "layout")
10027    public final int getHeight() {
10028        return mBottom - mTop;
10029    }
10030
10031    /**
10032     * Return the visible drawing bounds of your view. Fills in the output
10033     * rectangle with the values from getScrollX(), getScrollY(),
10034     * getWidth(), and getHeight(). These bounds do not account for any
10035     * transformation properties currently set on the view, such as
10036     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10037     *
10038     * @param outRect The (scrolled) drawing bounds of the view.
10039     */
10040    public void getDrawingRect(Rect outRect) {
10041        outRect.left = mScrollX;
10042        outRect.top = mScrollY;
10043        outRect.right = mScrollX + (mRight - mLeft);
10044        outRect.bottom = mScrollY + (mBottom - mTop);
10045    }
10046
10047    /**
10048     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10049     * raw width component (that is the result is masked by
10050     * {@link #MEASURED_SIZE_MASK}).
10051     *
10052     * @return The raw measured width of this view.
10053     */
10054    public final int getMeasuredWidth() {
10055        return mMeasuredWidth & MEASURED_SIZE_MASK;
10056    }
10057
10058    /**
10059     * Return the full width measurement information for this view as computed
10060     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10061     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10062     * This should be used during measurement and layout calculations only. Use
10063     * {@link #getWidth()} to see how wide a view is after layout.
10064     *
10065     * @return The measured width of this view as a bit mask.
10066     */
10067    public final int getMeasuredWidthAndState() {
10068        return mMeasuredWidth;
10069    }
10070
10071    /**
10072     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10073     * raw width component (that is the result is masked by
10074     * {@link #MEASURED_SIZE_MASK}).
10075     *
10076     * @return The raw measured height of this view.
10077     */
10078    public final int getMeasuredHeight() {
10079        return mMeasuredHeight & MEASURED_SIZE_MASK;
10080    }
10081
10082    /**
10083     * Return the full height measurement information for this view as computed
10084     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10085     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10086     * This should be used during measurement and layout calculations only. Use
10087     * {@link #getHeight()} to see how wide a view is after layout.
10088     *
10089     * @return The measured width of this view as a bit mask.
10090     */
10091    public final int getMeasuredHeightAndState() {
10092        return mMeasuredHeight;
10093    }
10094
10095    /**
10096     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10097     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10098     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10099     * and the height component is at the shifted bits
10100     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10101     */
10102    public final int getMeasuredState() {
10103        return (mMeasuredWidth&MEASURED_STATE_MASK)
10104                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10105                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10106    }
10107
10108    /**
10109     * The transform matrix of this view, which is calculated based on the current
10110     * rotation, scale, and pivot properties.
10111     *
10112     * @see #getRotation()
10113     * @see #getScaleX()
10114     * @see #getScaleY()
10115     * @see #getPivotX()
10116     * @see #getPivotY()
10117     * @return The current transform matrix for the view
10118     */
10119    public Matrix getMatrix() {
10120        ensureTransformationInfo();
10121        final Matrix matrix = mTransformationInfo.mMatrix;
10122        mRenderNode.getMatrix(matrix);
10123        return matrix;
10124    }
10125
10126    /**
10127     * Returns true if the transform matrix is the identity matrix.
10128     * Recomputes the matrix if necessary.
10129     *
10130     * @return True if the transform matrix is the identity matrix, false otherwise.
10131     */
10132    final boolean hasIdentityMatrix() {
10133        return mRenderNode.hasIdentityMatrix();
10134    }
10135
10136    void ensureTransformationInfo() {
10137        if (mTransformationInfo == null) {
10138            mTransformationInfo = new TransformationInfo();
10139        }
10140    }
10141
10142   /**
10143     * Utility method to retrieve the inverse of the current mMatrix property.
10144     * We cache the matrix to avoid recalculating it when transform properties
10145     * have not changed.
10146     *
10147     * @return The inverse of the current matrix of this view.
10148     * @hide
10149     */
10150    public final Matrix getInverseMatrix() {
10151        ensureTransformationInfo();
10152        if (mTransformationInfo.mInverseMatrix == null) {
10153            mTransformationInfo.mInverseMatrix = new Matrix();
10154        }
10155        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10156        mRenderNode.getInverseMatrix(matrix);
10157        return matrix;
10158    }
10159
10160    /**
10161     * Gets the distance along the Z axis from the camera to this view.
10162     *
10163     * @see #setCameraDistance(float)
10164     *
10165     * @return The distance along the Z axis.
10166     */
10167    public float getCameraDistance() {
10168        final float dpi = mResources.getDisplayMetrics().densityDpi;
10169        return -(mRenderNode.getCameraDistance() * dpi);
10170    }
10171
10172    /**
10173     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10174     * views are drawn) from the camera to this view. The camera's distance
10175     * affects 3D transformations, for instance rotations around the X and Y
10176     * axis. If the rotationX or rotationY properties are changed and this view is
10177     * large (more than half the size of the screen), it is recommended to always
10178     * use a camera distance that's greater than the height (X axis rotation) or
10179     * the width (Y axis rotation) of this view.</p>
10180     *
10181     * <p>The distance of the camera from the view plane can have an affect on the
10182     * perspective distortion of the view when it is rotated around the x or y axis.
10183     * For example, a large distance will result in a large viewing angle, and there
10184     * will not be much perspective distortion of the view as it rotates. A short
10185     * distance may cause much more perspective distortion upon rotation, and can
10186     * also result in some drawing artifacts if the rotated view ends up partially
10187     * behind the camera (which is why the recommendation is to use a distance at
10188     * least as far as the size of the view, if the view is to be rotated.)</p>
10189     *
10190     * <p>The distance is expressed in "depth pixels." The default distance depends
10191     * on the screen density. For instance, on a medium density display, the
10192     * default distance is 1280. On a high density display, the default distance
10193     * is 1920.</p>
10194     *
10195     * <p>If you want to specify a distance that leads to visually consistent
10196     * results across various densities, use the following formula:</p>
10197     * <pre>
10198     * float scale = context.getResources().getDisplayMetrics().density;
10199     * view.setCameraDistance(distance * scale);
10200     * </pre>
10201     *
10202     * <p>The density scale factor of a high density display is 1.5,
10203     * and 1920 = 1280 * 1.5.</p>
10204     *
10205     * @param distance The distance in "depth pixels", if negative the opposite
10206     *        value is used
10207     *
10208     * @see #setRotationX(float)
10209     * @see #setRotationY(float)
10210     */
10211    public void setCameraDistance(float distance) {
10212        final float dpi = mResources.getDisplayMetrics().densityDpi;
10213
10214        invalidateViewProperty(true, false);
10215        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10216        invalidateViewProperty(false, false);
10217
10218        invalidateParentIfNeededAndWasQuickRejected();
10219    }
10220
10221    /**
10222     * The degrees that the view is rotated around the pivot point.
10223     *
10224     * @see #setRotation(float)
10225     * @see #getPivotX()
10226     * @see #getPivotY()
10227     *
10228     * @return The degrees of rotation.
10229     */
10230    @ViewDebug.ExportedProperty(category = "drawing")
10231    public float getRotation() {
10232        return mRenderNode.getRotation();
10233    }
10234
10235    /**
10236     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10237     * result in clockwise rotation.
10238     *
10239     * @param rotation The degrees of rotation.
10240     *
10241     * @see #getRotation()
10242     * @see #getPivotX()
10243     * @see #getPivotY()
10244     * @see #setRotationX(float)
10245     * @see #setRotationY(float)
10246     *
10247     * @attr ref android.R.styleable#View_rotation
10248     */
10249    public void setRotation(float rotation) {
10250        if (rotation != getRotation()) {
10251            // Double-invalidation is necessary to capture view's old and new areas
10252            invalidateViewProperty(true, false);
10253            mRenderNode.setRotation(rotation);
10254            invalidateViewProperty(false, true);
10255
10256            invalidateParentIfNeededAndWasQuickRejected();
10257            notifySubtreeAccessibilityStateChangedIfNeeded();
10258        }
10259    }
10260
10261    /**
10262     * The degrees that the view is rotated around the vertical axis through the pivot point.
10263     *
10264     * @see #getPivotX()
10265     * @see #getPivotY()
10266     * @see #setRotationY(float)
10267     *
10268     * @return The degrees of Y rotation.
10269     */
10270    @ViewDebug.ExportedProperty(category = "drawing")
10271    public float getRotationY() {
10272        return mRenderNode.getRotationY();
10273    }
10274
10275    /**
10276     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10277     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10278     * down the y axis.
10279     *
10280     * When rotating large views, it is recommended to adjust the camera distance
10281     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10282     *
10283     * @param rotationY The degrees of Y rotation.
10284     *
10285     * @see #getRotationY()
10286     * @see #getPivotX()
10287     * @see #getPivotY()
10288     * @see #setRotation(float)
10289     * @see #setRotationX(float)
10290     * @see #setCameraDistance(float)
10291     *
10292     * @attr ref android.R.styleable#View_rotationY
10293     */
10294    public void setRotationY(float rotationY) {
10295        if (rotationY != getRotationY()) {
10296            invalidateViewProperty(true, false);
10297            mRenderNode.setRotationY(rotationY);
10298            invalidateViewProperty(false, true);
10299
10300            invalidateParentIfNeededAndWasQuickRejected();
10301            notifySubtreeAccessibilityStateChangedIfNeeded();
10302        }
10303    }
10304
10305    /**
10306     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10307     *
10308     * @see #getPivotX()
10309     * @see #getPivotY()
10310     * @see #setRotationX(float)
10311     *
10312     * @return The degrees of X rotation.
10313     */
10314    @ViewDebug.ExportedProperty(category = "drawing")
10315    public float getRotationX() {
10316        return mRenderNode.getRotationX();
10317    }
10318
10319    /**
10320     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10321     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10322     * x axis.
10323     *
10324     * When rotating large views, it is recommended to adjust the camera distance
10325     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10326     *
10327     * @param rotationX The degrees of X rotation.
10328     *
10329     * @see #getRotationX()
10330     * @see #getPivotX()
10331     * @see #getPivotY()
10332     * @see #setRotation(float)
10333     * @see #setRotationY(float)
10334     * @see #setCameraDistance(float)
10335     *
10336     * @attr ref android.R.styleable#View_rotationX
10337     */
10338    public void setRotationX(float rotationX) {
10339        if (rotationX != getRotationX()) {
10340            invalidateViewProperty(true, false);
10341            mRenderNode.setRotationX(rotationX);
10342            invalidateViewProperty(false, true);
10343
10344            invalidateParentIfNeededAndWasQuickRejected();
10345            notifySubtreeAccessibilityStateChangedIfNeeded();
10346        }
10347    }
10348
10349    /**
10350     * The amount that the view is scaled in x around the pivot point, as a proportion of
10351     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10352     *
10353     * <p>By default, this is 1.0f.
10354     *
10355     * @see #getPivotX()
10356     * @see #getPivotY()
10357     * @return The scaling factor.
10358     */
10359    @ViewDebug.ExportedProperty(category = "drawing")
10360    public float getScaleX() {
10361        return mRenderNode.getScaleX();
10362    }
10363
10364    /**
10365     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10366     * the view's unscaled width. A value of 1 means that no scaling is applied.
10367     *
10368     * @param scaleX The scaling factor.
10369     * @see #getPivotX()
10370     * @see #getPivotY()
10371     *
10372     * @attr ref android.R.styleable#View_scaleX
10373     */
10374    public void setScaleX(float scaleX) {
10375        if (scaleX != getScaleX()) {
10376            invalidateViewProperty(true, false);
10377            mRenderNode.setScaleX(scaleX);
10378            invalidateViewProperty(false, true);
10379
10380            invalidateParentIfNeededAndWasQuickRejected();
10381            notifySubtreeAccessibilityStateChangedIfNeeded();
10382        }
10383    }
10384
10385    /**
10386     * The amount that the view is scaled in y around the pivot point, as a proportion of
10387     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10388     *
10389     * <p>By default, this is 1.0f.
10390     *
10391     * @see #getPivotX()
10392     * @see #getPivotY()
10393     * @return The scaling factor.
10394     */
10395    @ViewDebug.ExportedProperty(category = "drawing")
10396    public float getScaleY() {
10397        return mRenderNode.getScaleY();
10398    }
10399
10400    /**
10401     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10402     * the view's unscaled width. A value of 1 means that no scaling is applied.
10403     *
10404     * @param scaleY The scaling factor.
10405     * @see #getPivotX()
10406     * @see #getPivotY()
10407     *
10408     * @attr ref android.R.styleable#View_scaleY
10409     */
10410    public void setScaleY(float scaleY) {
10411        if (scaleY != getScaleY()) {
10412            invalidateViewProperty(true, false);
10413            mRenderNode.setScaleY(scaleY);
10414            invalidateViewProperty(false, true);
10415
10416            invalidateParentIfNeededAndWasQuickRejected();
10417            notifySubtreeAccessibilityStateChangedIfNeeded();
10418        }
10419    }
10420
10421    /**
10422     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10423     * and {@link #setScaleX(float) scaled}.
10424     *
10425     * @see #getRotation()
10426     * @see #getScaleX()
10427     * @see #getScaleY()
10428     * @see #getPivotY()
10429     * @return The x location of the pivot point.
10430     *
10431     * @attr ref android.R.styleable#View_transformPivotX
10432     */
10433    @ViewDebug.ExportedProperty(category = "drawing")
10434    public float getPivotX() {
10435        return mRenderNode.getPivotX();
10436    }
10437
10438    /**
10439     * Sets the x location of the point around which the view is
10440     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10441     * By default, the pivot point is centered on the object.
10442     * Setting this property disables this behavior and causes the view to use only the
10443     * explicitly set pivotX and pivotY values.
10444     *
10445     * @param pivotX The x location of the pivot point.
10446     * @see #getRotation()
10447     * @see #getScaleX()
10448     * @see #getScaleY()
10449     * @see #getPivotY()
10450     *
10451     * @attr ref android.R.styleable#View_transformPivotX
10452     */
10453    public void setPivotX(float pivotX) {
10454        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10455            invalidateViewProperty(true, false);
10456            mRenderNode.setPivotX(pivotX);
10457            invalidateViewProperty(false, true);
10458
10459            invalidateParentIfNeededAndWasQuickRejected();
10460        }
10461    }
10462
10463    /**
10464     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10465     * and {@link #setScaleY(float) scaled}.
10466     *
10467     * @see #getRotation()
10468     * @see #getScaleX()
10469     * @see #getScaleY()
10470     * @see #getPivotY()
10471     * @return The y location of the pivot point.
10472     *
10473     * @attr ref android.R.styleable#View_transformPivotY
10474     */
10475    @ViewDebug.ExportedProperty(category = "drawing")
10476    public float getPivotY() {
10477        return mRenderNode.getPivotY();
10478    }
10479
10480    /**
10481     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10482     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10483     * Setting this property disables this behavior and causes the view to use only the
10484     * explicitly set pivotX and pivotY values.
10485     *
10486     * @param pivotY The y location of the pivot point.
10487     * @see #getRotation()
10488     * @see #getScaleX()
10489     * @see #getScaleY()
10490     * @see #getPivotY()
10491     *
10492     * @attr ref android.R.styleable#View_transformPivotY
10493     */
10494    public void setPivotY(float pivotY) {
10495        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10496            invalidateViewProperty(true, false);
10497            mRenderNode.setPivotY(pivotY);
10498            invalidateViewProperty(false, true);
10499
10500            invalidateParentIfNeededAndWasQuickRejected();
10501        }
10502    }
10503
10504    /**
10505     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10506     * completely transparent and 1 means the view is completely opaque.
10507     *
10508     * <p>By default this is 1.0f.
10509     * @return The opacity of the view.
10510     */
10511    @ViewDebug.ExportedProperty(category = "drawing")
10512    public float getAlpha() {
10513        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10514    }
10515
10516    /**
10517     * Returns whether this View has content which overlaps.
10518     *
10519     * <p>This function, intended to be overridden by specific View types, is an optimization when
10520     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10521     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10522     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10523     * directly. An example of overlapping rendering is a TextView with a background image, such as
10524     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10525     * ImageView with only the foreground image. The default implementation returns true; subclasses
10526     * should override if they have cases which can be optimized.</p>
10527     *
10528     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10529     * necessitates that a View return true if it uses the methods internally without passing the
10530     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10531     *
10532     * @return true if the content in this view might overlap, false otherwise.
10533     */
10534    @ViewDebug.ExportedProperty(category = "drawing")
10535    public boolean hasOverlappingRendering() {
10536        return true;
10537    }
10538
10539    /**
10540     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10541     * completely transparent and 1 means the view is completely opaque.</p>
10542     *
10543     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10544     * performance implications, especially for large views. It is best to use the alpha property
10545     * sparingly and transiently, as in the case of fading animations.</p>
10546     *
10547     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10548     * strongly recommended for performance reasons to either override
10549     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10550     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10551     *
10552     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10553     * responsible for applying the opacity itself.</p>
10554     *
10555     * <p>Note that if the view is backed by a
10556     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10557     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10558     * 1.0 will supersede the alpha of the layer paint.</p>
10559     *
10560     * @param alpha The opacity of the view.
10561     *
10562     * @see #hasOverlappingRendering()
10563     * @see #setLayerType(int, android.graphics.Paint)
10564     *
10565     * @attr ref android.R.styleable#View_alpha
10566     */
10567    public void setAlpha(float alpha) {
10568        ensureTransformationInfo();
10569        if (mTransformationInfo.mAlpha != alpha) {
10570            mTransformationInfo.mAlpha = alpha;
10571            if (onSetAlpha((int) (alpha * 255))) {
10572                mPrivateFlags |= PFLAG_ALPHA_SET;
10573                // subclass is handling alpha - don't optimize rendering cache invalidation
10574                invalidateParentCaches();
10575                invalidate(true);
10576            } else {
10577                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10578                invalidateViewProperty(true, false);
10579                mRenderNode.setAlpha(getFinalAlpha());
10580                notifyViewAccessibilityStateChangedIfNeeded(
10581                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10582            }
10583        }
10584    }
10585
10586    /**
10587     * Faster version of setAlpha() which performs the same steps except there are
10588     * no calls to invalidate(). The caller of this function should perform proper invalidation
10589     * on the parent and this object. The return value indicates whether the subclass handles
10590     * alpha (the return value for onSetAlpha()).
10591     *
10592     * @param alpha The new value for the alpha property
10593     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10594     *         the new value for the alpha property is different from the old value
10595     */
10596    boolean setAlphaNoInvalidation(float alpha) {
10597        ensureTransformationInfo();
10598        if (mTransformationInfo.mAlpha != alpha) {
10599            mTransformationInfo.mAlpha = alpha;
10600            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10601            if (subclassHandlesAlpha) {
10602                mPrivateFlags |= PFLAG_ALPHA_SET;
10603                return true;
10604            } else {
10605                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10606                mRenderNode.setAlpha(getFinalAlpha());
10607            }
10608        }
10609        return false;
10610    }
10611
10612    /**
10613     * This property is hidden and intended only for use by the Fade transition, which
10614     * animates it to produce a visual translucency that does not side-effect (or get
10615     * affected by) the real alpha property. This value is composited with the other
10616     * alpha value (and the AlphaAnimation value, when that is present) to produce
10617     * a final visual translucency result, which is what is passed into the DisplayList.
10618     *
10619     * @hide
10620     */
10621    public void setTransitionAlpha(float alpha) {
10622        ensureTransformationInfo();
10623        if (mTransformationInfo.mTransitionAlpha != alpha) {
10624            mTransformationInfo.mTransitionAlpha = alpha;
10625            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10626            invalidateViewProperty(true, false);
10627            mRenderNode.setAlpha(getFinalAlpha());
10628        }
10629    }
10630
10631    /**
10632     * Calculates the visual alpha of this view, which is a combination of the actual
10633     * alpha value and the transitionAlpha value (if set).
10634     */
10635    private float getFinalAlpha() {
10636        if (mTransformationInfo != null) {
10637            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10638        }
10639        return 1;
10640    }
10641
10642    /**
10643     * This property is hidden and intended only for use by the Fade transition, which
10644     * animates it to produce a visual translucency that does not side-effect (or get
10645     * affected by) the real alpha property. This value is composited with the other
10646     * alpha value (and the AlphaAnimation value, when that is present) to produce
10647     * a final visual translucency result, which is what is passed into the DisplayList.
10648     *
10649     * @hide
10650     */
10651    @ViewDebug.ExportedProperty(category = "drawing")
10652    public float getTransitionAlpha() {
10653        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10654    }
10655
10656    /**
10657     * Top position of this view relative to its parent.
10658     *
10659     * @return The top of this view, in pixels.
10660     */
10661    @ViewDebug.CapturedViewProperty
10662    public final int getTop() {
10663        return mTop;
10664    }
10665
10666    /**
10667     * Sets the top position of this view relative to its parent. This method is meant to be called
10668     * by the layout system and should not generally be called otherwise, because the property
10669     * may be changed at any time by the layout.
10670     *
10671     * @param top The top of this view, in pixels.
10672     */
10673    public final void setTop(int top) {
10674        if (top != mTop) {
10675            final boolean matrixIsIdentity = hasIdentityMatrix();
10676            if (matrixIsIdentity) {
10677                if (mAttachInfo != null) {
10678                    int minTop;
10679                    int yLoc;
10680                    if (top < mTop) {
10681                        minTop = top;
10682                        yLoc = top - mTop;
10683                    } else {
10684                        minTop = mTop;
10685                        yLoc = 0;
10686                    }
10687                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10688                }
10689            } else {
10690                // Double-invalidation is necessary to capture view's old and new areas
10691                invalidate(true);
10692            }
10693
10694            int width = mRight - mLeft;
10695            int oldHeight = mBottom - mTop;
10696
10697            mTop = top;
10698            mRenderNode.setTop(mTop);
10699
10700            sizeChange(width, mBottom - mTop, width, oldHeight);
10701
10702            if (!matrixIsIdentity) {
10703                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10704                invalidate(true);
10705            }
10706            mBackgroundSizeChanged = true;
10707            invalidateParentIfNeeded();
10708            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10709                // View was rejected last time it was drawn by its parent; this may have changed
10710                invalidateParentIfNeeded();
10711            }
10712        }
10713    }
10714
10715    /**
10716     * Bottom position of this view relative to its parent.
10717     *
10718     * @return The bottom of this view, in pixels.
10719     */
10720    @ViewDebug.CapturedViewProperty
10721    public final int getBottom() {
10722        return mBottom;
10723    }
10724
10725    /**
10726     * True if this view has changed since the last time being drawn.
10727     *
10728     * @return The dirty state of this view.
10729     */
10730    public boolean isDirty() {
10731        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10732    }
10733
10734    /**
10735     * Sets the bottom position of this view relative to its parent. This method is meant to be
10736     * called by the layout system and should not generally be called otherwise, because the
10737     * property may be changed at any time by the layout.
10738     *
10739     * @param bottom The bottom of this view, in pixels.
10740     */
10741    public final void setBottom(int bottom) {
10742        if (bottom != mBottom) {
10743            final boolean matrixIsIdentity = hasIdentityMatrix();
10744            if (matrixIsIdentity) {
10745                if (mAttachInfo != null) {
10746                    int maxBottom;
10747                    if (bottom < mBottom) {
10748                        maxBottom = mBottom;
10749                    } else {
10750                        maxBottom = bottom;
10751                    }
10752                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10753                }
10754            } else {
10755                // Double-invalidation is necessary to capture view's old and new areas
10756                invalidate(true);
10757            }
10758
10759            int width = mRight - mLeft;
10760            int oldHeight = mBottom - mTop;
10761
10762            mBottom = bottom;
10763            mRenderNode.setBottom(mBottom);
10764
10765            sizeChange(width, mBottom - mTop, width, oldHeight);
10766
10767            if (!matrixIsIdentity) {
10768                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10769                invalidate(true);
10770            }
10771            mBackgroundSizeChanged = true;
10772            invalidateParentIfNeeded();
10773            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10774                // View was rejected last time it was drawn by its parent; this may have changed
10775                invalidateParentIfNeeded();
10776            }
10777        }
10778    }
10779
10780    /**
10781     * Left position of this view relative to its parent.
10782     *
10783     * @return The left edge of this view, in pixels.
10784     */
10785    @ViewDebug.CapturedViewProperty
10786    public final int getLeft() {
10787        return mLeft;
10788    }
10789
10790    /**
10791     * Sets the left position of this view relative to its parent. This method is meant to be called
10792     * by the layout system and should not generally be called otherwise, because the property
10793     * may be changed at any time by the layout.
10794     *
10795     * @param left The left of this view, in pixels.
10796     */
10797    public final void setLeft(int left) {
10798        if (left != mLeft) {
10799            final boolean matrixIsIdentity = hasIdentityMatrix();
10800            if (matrixIsIdentity) {
10801                if (mAttachInfo != null) {
10802                    int minLeft;
10803                    int xLoc;
10804                    if (left < mLeft) {
10805                        minLeft = left;
10806                        xLoc = left - mLeft;
10807                    } else {
10808                        minLeft = mLeft;
10809                        xLoc = 0;
10810                    }
10811                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10812                }
10813            } else {
10814                // Double-invalidation is necessary to capture view's old and new areas
10815                invalidate(true);
10816            }
10817
10818            int oldWidth = mRight - mLeft;
10819            int height = mBottom - mTop;
10820
10821            mLeft = left;
10822            mRenderNode.setLeft(left);
10823
10824            sizeChange(mRight - mLeft, height, oldWidth, height);
10825
10826            if (!matrixIsIdentity) {
10827                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10828                invalidate(true);
10829            }
10830            mBackgroundSizeChanged = true;
10831            invalidateParentIfNeeded();
10832            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10833                // View was rejected last time it was drawn by its parent; this may have changed
10834                invalidateParentIfNeeded();
10835            }
10836        }
10837    }
10838
10839    /**
10840     * Right position of this view relative to its parent.
10841     *
10842     * @return The right edge of this view, in pixels.
10843     */
10844    @ViewDebug.CapturedViewProperty
10845    public final int getRight() {
10846        return mRight;
10847    }
10848
10849    /**
10850     * Sets the right position of this view relative to its parent. This method is meant to be called
10851     * by the layout system and should not generally be called otherwise, because the property
10852     * may be changed at any time by the layout.
10853     *
10854     * @param right The right of this view, in pixels.
10855     */
10856    public final void setRight(int right) {
10857        if (right != mRight) {
10858            final boolean matrixIsIdentity = hasIdentityMatrix();
10859            if (matrixIsIdentity) {
10860                if (mAttachInfo != null) {
10861                    int maxRight;
10862                    if (right < mRight) {
10863                        maxRight = mRight;
10864                    } else {
10865                        maxRight = right;
10866                    }
10867                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10868                }
10869            } else {
10870                // Double-invalidation is necessary to capture view's old and new areas
10871                invalidate(true);
10872            }
10873
10874            int oldWidth = mRight - mLeft;
10875            int height = mBottom - mTop;
10876
10877            mRight = right;
10878            mRenderNode.setRight(mRight);
10879
10880            sizeChange(mRight - mLeft, height, oldWidth, height);
10881
10882            if (!matrixIsIdentity) {
10883                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10884                invalidate(true);
10885            }
10886            mBackgroundSizeChanged = true;
10887            invalidateParentIfNeeded();
10888            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10889                // View was rejected last time it was drawn by its parent; this may have changed
10890                invalidateParentIfNeeded();
10891            }
10892        }
10893    }
10894
10895    /**
10896     * The visual x position of this view, in pixels. This is equivalent to the
10897     * {@link #setTranslationX(float) translationX} property plus the current
10898     * {@link #getLeft() left} property.
10899     *
10900     * @return The visual x position of this view, in pixels.
10901     */
10902    @ViewDebug.ExportedProperty(category = "drawing")
10903    public float getX() {
10904        return mLeft + getTranslationX();
10905    }
10906
10907    /**
10908     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10909     * {@link #setTranslationX(float) translationX} property to be the difference between
10910     * the x value passed in and the current {@link #getLeft() left} property.
10911     *
10912     * @param x The visual x position of this view, in pixels.
10913     */
10914    public void setX(float x) {
10915        setTranslationX(x - mLeft);
10916    }
10917
10918    /**
10919     * The visual y position of this view, in pixels. This is equivalent to the
10920     * {@link #setTranslationY(float) translationY} property plus the current
10921     * {@link #getTop() top} property.
10922     *
10923     * @return The visual y position of this view, in pixels.
10924     */
10925    @ViewDebug.ExportedProperty(category = "drawing")
10926    public float getY() {
10927        return mTop + getTranslationY();
10928    }
10929
10930    /**
10931     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10932     * {@link #setTranslationY(float) translationY} property to be the difference between
10933     * the y value passed in and the current {@link #getTop() top} property.
10934     *
10935     * @param y The visual y position of this view, in pixels.
10936     */
10937    public void setY(float y) {
10938        setTranslationY(y - mTop);
10939    }
10940
10941    /**
10942     * The visual z position of this view, in pixels. This is equivalent to the
10943     * {@link #setTranslationZ(float) translationZ} property plus the current
10944     * {@link #getElevation() elevation} property.
10945     *
10946     * @return The visual z position of this view, in pixels.
10947     */
10948    @ViewDebug.ExportedProperty(category = "drawing")
10949    public float getZ() {
10950        return getElevation() + getTranslationZ();
10951    }
10952
10953    /**
10954     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10955     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10956     * the x value passed in and the current {@link #getElevation() elevation} property.
10957     *
10958     * @param z The visual z position of this view, in pixels.
10959     */
10960    public void setZ(float z) {
10961        setTranslationZ(z - getElevation());
10962    }
10963
10964    /**
10965     * The base elevation of this view relative to its parent, in pixels.
10966     *
10967     * @return The base depth position of the view, in pixels.
10968     */
10969    @ViewDebug.ExportedProperty(category = "drawing")
10970    public float getElevation() {
10971        return mRenderNode.getElevation();
10972    }
10973
10974    /**
10975     * Sets the base elevation of this view, in pixels.
10976     *
10977     * @attr ref android.R.styleable#View_elevation
10978     */
10979    public void setElevation(float elevation) {
10980        if (elevation != getElevation()) {
10981            invalidateViewProperty(true, false);
10982            mRenderNode.setElevation(elevation);
10983            invalidateViewProperty(false, true);
10984
10985            invalidateParentIfNeededAndWasQuickRejected();
10986        }
10987    }
10988
10989    /**
10990     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10991     * This position is post-layout, in addition to wherever the object's
10992     * layout placed it.
10993     *
10994     * @return The horizontal position of this view relative to its left position, in pixels.
10995     */
10996    @ViewDebug.ExportedProperty(category = "drawing")
10997    public float getTranslationX() {
10998        return mRenderNode.getTranslationX();
10999    }
11000
11001    /**
11002     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11003     * This effectively positions the object post-layout, in addition to wherever the object's
11004     * layout placed it.
11005     *
11006     * @param translationX The horizontal position of this view relative to its left position,
11007     * in pixels.
11008     *
11009     * @attr ref android.R.styleable#View_translationX
11010     */
11011    public void setTranslationX(float translationX) {
11012        if (translationX != getTranslationX()) {
11013            invalidateViewProperty(true, false);
11014            mRenderNode.setTranslationX(translationX);
11015            invalidateViewProperty(false, true);
11016
11017            invalidateParentIfNeededAndWasQuickRejected();
11018            notifySubtreeAccessibilityStateChangedIfNeeded();
11019        }
11020    }
11021
11022    /**
11023     * The vertical location of this view relative to its {@link #getTop() top} position.
11024     * This position is post-layout, in addition to wherever the object's
11025     * layout placed it.
11026     *
11027     * @return The vertical position of this view relative to its top position,
11028     * in pixels.
11029     */
11030    @ViewDebug.ExportedProperty(category = "drawing")
11031    public float getTranslationY() {
11032        return mRenderNode.getTranslationY();
11033    }
11034
11035    /**
11036     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11037     * This effectively positions the object post-layout, in addition to wherever the object's
11038     * layout placed it.
11039     *
11040     * @param translationY The vertical position of this view relative to its top position,
11041     * in pixels.
11042     *
11043     * @attr ref android.R.styleable#View_translationY
11044     */
11045    public void setTranslationY(float translationY) {
11046        if (translationY != getTranslationY()) {
11047            invalidateViewProperty(true, false);
11048            mRenderNode.setTranslationY(translationY);
11049            invalidateViewProperty(false, true);
11050
11051            invalidateParentIfNeededAndWasQuickRejected();
11052        }
11053    }
11054
11055    /**
11056     * The depth location of this view relative to its {@link #getElevation() elevation}.
11057     *
11058     * @return The depth of this view relative to its elevation.
11059     */
11060    @ViewDebug.ExportedProperty(category = "drawing")
11061    public float getTranslationZ() {
11062        return mRenderNode.getTranslationZ();
11063    }
11064
11065    /**
11066     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11067     *
11068     * @attr ref android.R.styleable#View_translationZ
11069     */
11070    public void setTranslationZ(float translationZ) {
11071        if (translationZ != getTranslationZ()) {
11072            invalidateViewProperty(true, false);
11073            mRenderNode.setTranslationZ(translationZ);
11074            invalidateViewProperty(false, true);
11075
11076            invalidateParentIfNeededAndWasQuickRejected();
11077        }
11078    }
11079
11080    /** @hide */
11081    public void setAnimationMatrix(Matrix matrix) {
11082        invalidateViewProperty(true, false);
11083        mRenderNode.setAnimationMatrix(matrix);
11084        invalidateViewProperty(false, true);
11085
11086        invalidateParentIfNeededAndWasQuickRejected();
11087    }
11088
11089    /**
11090     * Returns the current StateListAnimator if exists.
11091     *
11092     * @return StateListAnimator or null if it does not exists
11093     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11094     */
11095    public StateListAnimator getStateListAnimator() {
11096        return mStateListAnimator;
11097    }
11098
11099    /**
11100     * Attaches the provided StateListAnimator to this View.
11101     * <p>
11102     * Any previously attached StateListAnimator will be detached.
11103     *
11104     * @param stateListAnimator The StateListAnimator to update the view
11105     * @see {@link android.animation.StateListAnimator}
11106     */
11107    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11108        if (mStateListAnimator == stateListAnimator) {
11109            return;
11110        }
11111        if (mStateListAnimator != null) {
11112            mStateListAnimator.setTarget(null);
11113        }
11114        mStateListAnimator = stateListAnimator;
11115        if (stateListAnimator != null) {
11116            stateListAnimator.setTarget(this);
11117            if (isAttachedToWindow()) {
11118                stateListAnimator.setState(getDrawableState());
11119            }
11120        }
11121    }
11122
11123    /**
11124     * Returns whether the Outline should be used to clip the contents of the View.
11125     * <p>
11126     * Note that this flag will only be respected if the View's Outline returns true from
11127     * {@link Outline#canClip()}.
11128     *
11129     * @see #setOutlineProvider(ViewOutlineProvider)
11130     * @see #setClipToOutline(boolean)
11131     */
11132    public final boolean getClipToOutline() {
11133        return mRenderNode.getClipToOutline();
11134    }
11135
11136    /**
11137     * Sets whether the View's Outline should be used to clip the contents of the View.
11138     * <p>
11139     * Only a single non-rectangular clip can be applied on a View at any time.
11140     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11141     * circular reveal} animation take priority over Outline clipping, and
11142     * child Outline clipping takes priority over Outline clipping done by a
11143     * parent.
11144     * <p>
11145     * Note that this flag will only be respected if the View's Outline returns true from
11146     * {@link Outline#canClip()}.
11147     *
11148     * @see #setOutlineProvider(ViewOutlineProvider)
11149     * @see #getClipToOutline()
11150     */
11151    public void setClipToOutline(boolean clipToOutline) {
11152        damageInParent();
11153        if (getClipToOutline() != clipToOutline) {
11154            mRenderNode.setClipToOutline(clipToOutline);
11155        }
11156    }
11157
11158    // correspond to the enum values of View_outlineProvider
11159    private static final int PROVIDER_BACKGROUND = 0;
11160    private static final int PROVIDER_NONE = 1;
11161    private static final int PROVIDER_BOUNDS = 2;
11162    private static final int PROVIDER_PADDED_BOUNDS = 3;
11163    private void setOutlineProviderFromAttribute(int providerInt) {
11164        switch (providerInt) {
11165            case PROVIDER_BACKGROUND:
11166                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11167                break;
11168            case PROVIDER_NONE:
11169                setOutlineProvider(null);
11170                break;
11171            case PROVIDER_BOUNDS:
11172                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11173                break;
11174            case PROVIDER_PADDED_BOUNDS:
11175                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11176                break;
11177        }
11178    }
11179
11180    /**
11181     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11182     * the shape of the shadow it casts, and enables outline clipping.
11183     * <p>
11184     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11185     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11186     * outline provider with this method allows this behavior to be overridden.
11187     * <p>
11188     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11189     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11190     * <p>
11191     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11192     *
11193     * @see #setClipToOutline(boolean)
11194     * @see #getClipToOutline()
11195     * @see #getOutlineProvider()
11196     */
11197    public void setOutlineProvider(ViewOutlineProvider provider) {
11198        mOutlineProvider = provider;
11199        invalidateOutline();
11200    }
11201
11202    /**
11203     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11204     * that defines the shape of the shadow it casts, and enables outline clipping.
11205     *
11206     * @see #setOutlineProvider(ViewOutlineProvider)
11207     */
11208    public ViewOutlineProvider getOutlineProvider() {
11209        return mOutlineProvider;
11210    }
11211
11212    /**
11213     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11214     *
11215     * @see #setOutlineProvider(ViewOutlineProvider)
11216     */
11217    public void invalidateOutline() {
11218        rebuildOutline();
11219
11220        notifySubtreeAccessibilityStateChangedIfNeeded();
11221        invalidateViewProperty(false, false);
11222    }
11223
11224    /**
11225     * Internal version of {@link #invalidateOutline()} which invalidates the
11226     * outline without invalidating the view itself. This is intended to be called from
11227     * within methods in the View class itself which are the result of the view being
11228     * invalidated already. For example, when we are drawing the background of a View,
11229     * we invalidate the outline in case it changed in the meantime, but we do not
11230     * need to invalidate the view because we're already drawing the background as part
11231     * of drawing the view in response to an earlier invalidation of the view.
11232     */
11233    private void rebuildOutline() {
11234        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11235        if (mAttachInfo == null) return;
11236
11237        if (mOutlineProvider == null) {
11238            // no provider, remove outline
11239            mRenderNode.setOutline(null);
11240        } else {
11241            final Outline outline = mAttachInfo.mTmpOutline;
11242            outline.setEmpty();
11243            outline.setAlpha(1.0f);
11244
11245            mOutlineProvider.getOutline(this, outline);
11246            mRenderNode.setOutline(outline);
11247        }
11248    }
11249
11250    /**
11251     * HierarchyViewer only
11252     *
11253     * @hide
11254     */
11255    @ViewDebug.ExportedProperty(category = "drawing")
11256    public boolean hasShadow() {
11257        return mRenderNode.hasShadow();
11258    }
11259
11260
11261    /** @hide */
11262    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11263        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11264        invalidateViewProperty(false, false);
11265    }
11266
11267    /**
11268     * Hit rectangle in parent's coordinates
11269     *
11270     * @param outRect The hit rectangle of the view.
11271     */
11272    public void getHitRect(Rect outRect) {
11273        if (hasIdentityMatrix() || mAttachInfo == null) {
11274            outRect.set(mLeft, mTop, mRight, mBottom);
11275        } else {
11276            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11277            tmpRect.set(0, 0, getWidth(), getHeight());
11278            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11279            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11280                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11281        }
11282    }
11283
11284    /**
11285     * Determines whether the given point, in local coordinates is inside the view.
11286     */
11287    /*package*/ final boolean pointInView(float localX, float localY) {
11288        return localX >= 0 && localX < (mRight - mLeft)
11289                && localY >= 0 && localY < (mBottom - mTop);
11290    }
11291
11292    /**
11293     * Utility method to determine whether the given point, in local coordinates,
11294     * is inside the view, where the area of the view is expanded by the slop factor.
11295     * This method is called while processing touch-move events to determine if the event
11296     * is still within the view.
11297     *
11298     * @hide
11299     */
11300    public boolean pointInView(float localX, float localY, float slop) {
11301        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11302                localY < ((mBottom - mTop) + slop);
11303    }
11304
11305    /**
11306     * When a view has focus and the user navigates away from it, the next view is searched for
11307     * starting from the rectangle filled in by this method.
11308     *
11309     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11310     * of the view.  However, if your view maintains some idea of internal selection,
11311     * such as a cursor, or a selected row or column, you should override this method and
11312     * fill in a more specific rectangle.
11313     *
11314     * @param r The rectangle to fill in, in this view's coordinates.
11315     */
11316    public void getFocusedRect(Rect r) {
11317        getDrawingRect(r);
11318    }
11319
11320    /**
11321     * If some part of this view is not clipped by any of its parents, then
11322     * return that area in r in global (root) coordinates. To convert r to local
11323     * coordinates (without taking possible View rotations into account), offset
11324     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11325     * If the view is completely clipped or translated out, return false.
11326     *
11327     * @param r If true is returned, r holds the global coordinates of the
11328     *        visible portion of this view.
11329     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11330     *        between this view and its root. globalOffet may be null.
11331     * @return true if r is non-empty (i.e. part of the view is visible at the
11332     *         root level.
11333     */
11334    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11335        int width = mRight - mLeft;
11336        int height = mBottom - mTop;
11337        if (width > 0 && height > 0) {
11338            r.set(0, 0, width, height);
11339            if (globalOffset != null) {
11340                globalOffset.set(-mScrollX, -mScrollY);
11341            }
11342            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11343        }
11344        return false;
11345    }
11346
11347    public final boolean getGlobalVisibleRect(Rect r) {
11348        return getGlobalVisibleRect(r, null);
11349    }
11350
11351    public final boolean getLocalVisibleRect(Rect r) {
11352        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11353        if (getGlobalVisibleRect(r, offset)) {
11354            r.offset(-offset.x, -offset.y); // make r local
11355            return true;
11356        }
11357        return false;
11358    }
11359
11360    /**
11361     * Offset this view's vertical location by the specified number of pixels.
11362     *
11363     * @param offset the number of pixels to offset the view by
11364     */
11365    public void offsetTopAndBottom(int offset) {
11366        if (offset != 0) {
11367            final boolean matrixIsIdentity = hasIdentityMatrix();
11368            if (matrixIsIdentity) {
11369                if (isHardwareAccelerated()) {
11370                    invalidateViewProperty(false, false);
11371                } else {
11372                    final ViewParent p = mParent;
11373                    if (p != null && mAttachInfo != null) {
11374                        final Rect r = mAttachInfo.mTmpInvalRect;
11375                        int minTop;
11376                        int maxBottom;
11377                        int yLoc;
11378                        if (offset < 0) {
11379                            minTop = mTop + offset;
11380                            maxBottom = mBottom;
11381                            yLoc = offset;
11382                        } else {
11383                            minTop = mTop;
11384                            maxBottom = mBottom + offset;
11385                            yLoc = 0;
11386                        }
11387                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11388                        p.invalidateChild(this, r);
11389                    }
11390                }
11391            } else {
11392                invalidateViewProperty(false, false);
11393            }
11394
11395            mTop += offset;
11396            mBottom += offset;
11397            mRenderNode.offsetTopAndBottom(offset);
11398            if (isHardwareAccelerated()) {
11399                invalidateViewProperty(false, false);
11400            } else {
11401                if (!matrixIsIdentity) {
11402                    invalidateViewProperty(false, true);
11403                }
11404                invalidateParentIfNeeded();
11405            }
11406            notifySubtreeAccessibilityStateChangedIfNeeded();
11407        }
11408    }
11409
11410    /**
11411     * Offset this view's horizontal location by the specified amount of pixels.
11412     *
11413     * @param offset the number of pixels to offset the view by
11414     */
11415    public void offsetLeftAndRight(int offset) {
11416        if (offset != 0) {
11417            final boolean matrixIsIdentity = hasIdentityMatrix();
11418            if (matrixIsIdentity) {
11419                if (isHardwareAccelerated()) {
11420                    invalidateViewProperty(false, false);
11421                } else {
11422                    final ViewParent p = mParent;
11423                    if (p != null && mAttachInfo != null) {
11424                        final Rect r = mAttachInfo.mTmpInvalRect;
11425                        int minLeft;
11426                        int maxRight;
11427                        if (offset < 0) {
11428                            minLeft = mLeft + offset;
11429                            maxRight = mRight;
11430                        } else {
11431                            minLeft = mLeft;
11432                            maxRight = mRight + offset;
11433                        }
11434                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11435                        p.invalidateChild(this, r);
11436                    }
11437                }
11438            } else {
11439                invalidateViewProperty(false, false);
11440            }
11441
11442            mLeft += offset;
11443            mRight += offset;
11444            mRenderNode.offsetLeftAndRight(offset);
11445            if (isHardwareAccelerated()) {
11446                invalidateViewProperty(false, false);
11447            } else {
11448                if (!matrixIsIdentity) {
11449                    invalidateViewProperty(false, true);
11450                }
11451                invalidateParentIfNeeded();
11452            }
11453            notifySubtreeAccessibilityStateChangedIfNeeded();
11454        }
11455    }
11456
11457    /**
11458     * Get the LayoutParams associated with this view. All views should have
11459     * layout parameters. These supply parameters to the <i>parent</i> of this
11460     * view specifying how it should be arranged. There are many subclasses of
11461     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11462     * of ViewGroup that are responsible for arranging their children.
11463     *
11464     * This method may return null if this View is not attached to a parent
11465     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11466     * was not invoked successfully. When a View is attached to a parent
11467     * ViewGroup, this method must not return null.
11468     *
11469     * @return The LayoutParams associated with this view, or null if no
11470     *         parameters have been set yet
11471     */
11472    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11473    public ViewGroup.LayoutParams getLayoutParams() {
11474        return mLayoutParams;
11475    }
11476
11477    /**
11478     * Set the layout parameters associated with this view. These supply
11479     * parameters to the <i>parent</i> of this view specifying how it should be
11480     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11481     * correspond to the different subclasses of ViewGroup that are responsible
11482     * for arranging their children.
11483     *
11484     * @param params The layout parameters for this view, cannot be null
11485     */
11486    public void setLayoutParams(ViewGroup.LayoutParams params) {
11487        if (params == null) {
11488            throw new NullPointerException("Layout parameters cannot be null");
11489        }
11490        mLayoutParams = params;
11491        resolveLayoutParams();
11492        if (mParent instanceof ViewGroup) {
11493            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11494        }
11495        requestLayout();
11496    }
11497
11498    /**
11499     * Resolve the layout parameters depending on the resolved layout direction
11500     *
11501     * @hide
11502     */
11503    public void resolveLayoutParams() {
11504        if (mLayoutParams != null) {
11505            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11506        }
11507    }
11508
11509    /**
11510     * Set the scrolled position of your view. This will cause a call to
11511     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11512     * invalidated.
11513     * @param x the x position to scroll to
11514     * @param y the y position to scroll to
11515     */
11516    public void scrollTo(int x, int y) {
11517        if (mScrollX != x || mScrollY != y) {
11518            int oldX = mScrollX;
11519            int oldY = mScrollY;
11520            mScrollX = x;
11521            mScrollY = y;
11522            invalidateParentCaches();
11523            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11524            if (!awakenScrollBars()) {
11525                postInvalidateOnAnimation();
11526            }
11527        }
11528    }
11529
11530    /**
11531     * Move the scrolled position of your view. This will cause a call to
11532     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11533     * invalidated.
11534     * @param x the amount of pixels to scroll by horizontally
11535     * @param y the amount of pixels to scroll by vertically
11536     */
11537    public void scrollBy(int x, int y) {
11538        scrollTo(mScrollX + x, mScrollY + y);
11539    }
11540
11541    /**
11542     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11543     * animation to fade the scrollbars out after a default delay. If a subclass
11544     * provides animated scrolling, the start delay should equal the duration
11545     * of the scrolling animation.</p>
11546     *
11547     * <p>The animation starts only if at least one of the scrollbars is
11548     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11549     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11550     * this method returns true, and false otherwise. If the animation is
11551     * started, this method calls {@link #invalidate()}; in that case the
11552     * caller should not call {@link #invalidate()}.</p>
11553     *
11554     * <p>This method should be invoked every time a subclass directly updates
11555     * the scroll parameters.</p>
11556     *
11557     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11558     * and {@link #scrollTo(int, int)}.</p>
11559     *
11560     * @return true if the animation is played, false otherwise
11561     *
11562     * @see #awakenScrollBars(int)
11563     * @see #scrollBy(int, int)
11564     * @see #scrollTo(int, int)
11565     * @see #isHorizontalScrollBarEnabled()
11566     * @see #isVerticalScrollBarEnabled()
11567     * @see #setHorizontalScrollBarEnabled(boolean)
11568     * @see #setVerticalScrollBarEnabled(boolean)
11569     */
11570    protected boolean awakenScrollBars() {
11571        return mScrollCache != null &&
11572                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11573    }
11574
11575    /**
11576     * Trigger the scrollbars to draw.
11577     * This method differs from awakenScrollBars() only in its default duration.
11578     * initialAwakenScrollBars() will show the scroll bars for longer than
11579     * usual to give the user more of a chance to notice them.
11580     *
11581     * @return true if the animation is played, false otherwise.
11582     */
11583    private boolean initialAwakenScrollBars() {
11584        return mScrollCache != null &&
11585                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11586    }
11587
11588    /**
11589     * <p>
11590     * Trigger the scrollbars to draw. When invoked this method starts an
11591     * animation to fade the scrollbars out after a fixed delay. If a subclass
11592     * provides animated scrolling, the start delay should equal the duration of
11593     * the scrolling animation.
11594     * </p>
11595     *
11596     * <p>
11597     * The animation starts only if at least one of the scrollbars is enabled,
11598     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11599     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11600     * this method returns true, and false otherwise. If the animation is
11601     * started, this method calls {@link #invalidate()}; in that case the caller
11602     * should not call {@link #invalidate()}.
11603     * </p>
11604     *
11605     * <p>
11606     * This method should be invoked every time a subclass directly updates the
11607     * scroll parameters.
11608     * </p>
11609     *
11610     * @param startDelay the delay, in milliseconds, after which the animation
11611     *        should start; when the delay is 0, the animation starts
11612     *        immediately
11613     * @return true if the animation is played, false otherwise
11614     *
11615     * @see #scrollBy(int, int)
11616     * @see #scrollTo(int, int)
11617     * @see #isHorizontalScrollBarEnabled()
11618     * @see #isVerticalScrollBarEnabled()
11619     * @see #setHorizontalScrollBarEnabled(boolean)
11620     * @see #setVerticalScrollBarEnabled(boolean)
11621     */
11622    protected boolean awakenScrollBars(int startDelay) {
11623        return awakenScrollBars(startDelay, true);
11624    }
11625
11626    /**
11627     * <p>
11628     * Trigger the scrollbars to draw. When invoked this method starts an
11629     * animation to fade the scrollbars out after a fixed delay. If a subclass
11630     * provides animated scrolling, the start delay should equal the duration of
11631     * the scrolling animation.
11632     * </p>
11633     *
11634     * <p>
11635     * The animation starts only if at least one of the scrollbars is enabled,
11636     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11637     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11638     * this method returns true, and false otherwise. If the animation is
11639     * started, this method calls {@link #invalidate()} if the invalidate parameter
11640     * is set to true; in that case the caller
11641     * should not call {@link #invalidate()}.
11642     * </p>
11643     *
11644     * <p>
11645     * This method should be invoked every time a subclass directly updates the
11646     * scroll parameters.
11647     * </p>
11648     *
11649     * @param startDelay the delay, in milliseconds, after which the animation
11650     *        should start; when the delay is 0, the animation starts
11651     *        immediately
11652     *
11653     * @param invalidate Whether this method should call invalidate
11654     *
11655     * @return true if the animation is played, false otherwise
11656     *
11657     * @see #scrollBy(int, int)
11658     * @see #scrollTo(int, int)
11659     * @see #isHorizontalScrollBarEnabled()
11660     * @see #isVerticalScrollBarEnabled()
11661     * @see #setHorizontalScrollBarEnabled(boolean)
11662     * @see #setVerticalScrollBarEnabled(boolean)
11663     */
11664    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11665        final ScrollabilityCache scrollCache = mScrollCache;
11666
11667        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11668            return false;
11669        }
11670
11671        if (scrollCache.scrollBar == null) {
11672            scrollCache.scrollBar = new ScrollBarDrawable();
11673            scrollCache.scrollBar.setCallback(this);
11674            scrollCache.scrollBar.setState(getDrawableState());
11675        }
11676
11677        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11678
11679            if (invalidate) {
11680                // Invalidate to show the scrollbars
11681                postInvalidateOnAnimation();
11682            }
11683
11684            if (scrollCache.state == ScrollabilityCache.OFF) {
11685                // FIXME: this is copied from WindowManagerService.
11686                // We should get this value from the system when it
11687                // is possible to do so.
11688                final int KEY_REPEAT_FIRST_DELAY = 750;
11689                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11690            }
11691
11692            // Tell mScrollCache when we should start fading. This may
11693            // extend the fade start time if one was already scheduled
11694            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11695            scrollCache.fadeStartTime = fadeStartTime;
11696            scrollCache.state = ScrollabilityCache.ON;
11697
11698            // Schedule our fader to run, unscheduling any old ones first
11699            if (mAttachInfo != null) {
11700                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11701                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11702            }
11703
11704            return true;
11705        }
11706
11707        return false;
11708    }
11709
11710    /**
11711     * Do not invalidate views which are not visible and which are not running an animation. They
11712     * will not get drawn and they should not set dirty flags as if they will be drawn
11713     */
11714    private boolean skipInvalidate() {
11715        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11716                (!(mParent instanceof ViewGroup) ||
11717                        !((ViewGroup) mParent).isViewTransitioning(this));
11718    }
11719
11720    /**
11721     * Mark the area defined by dirty as needing to be drawn. If the view is
11722     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11723     * point in the future.
11724     * <p>
11725     * This must be called from a UI thread. To call from a non-UI thread, call
11726     * {@link #postInvalidate()}.
11727     * <p>
11728     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11729     * {@code dirty}.
11730     *
11731     * @param dirty the rectangle representing the bounds of the dirty region
11732     */
11733    public void invalidate(Rect dirty) {
11734        final int scrollX = mScrollX;
11735        final int scrollY = mScrollY;
11736        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11737                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11738    }
11739
11740    /**
11741     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11742     * coordinates of the dirty rect are relative to the view. If the view is
11743     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11744     * point in the future.
11745     * <p>
11746     * This must be called from a UI thread. To call from a non-UI thread, call
11747     * {@link #postInvalidate()}.
11748     *
11749     * @param l the left position of the dirty region
11750     * @param t the top position of the dirty region
11751     * @param r the right position of the dirty region
11752     * @param b the bottom position of the dirty region
11753     */
11754    public void invalidate(int l, int t, int r, int b) {
11755        final int scrollX = mScrollX;
11756        final int scrollY = mScrollY;
11757        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11758    }
11759
11760    /**
11761     * Invalidate the whole view. If the view is visible,
11762     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11763     * the future.
11764     * <p>
11765     * This must be called from a UI thread. To call from a non-UI thread, call
11766     * {@link #postInvalidate()}.
11767     */
11768    public void invalidate() {
11769        invalidate(true);
11770    }
11771
11772    /**
11773     * This is where the invalidate() work actually happens. A full invalidate()
11774     * causes the drawing cache to be invalidated, but this function can be
11775     * called with invalidateCache set to false to skip that invalidation step
11776     * for cases that do not need it (for example, a component that remains at
11777     * the same dimensions with the same content).
11778     *
11779     * @param invalidateCache Whether the drawing cache for this view should be
11780     *            invalidated as well. This is usually true for a full
11781     *            invalidate, but may be set to false if the View's contents or
11782     *            dimensions have not changed.
11783     */
11784    void invalidate(boolean invalidateCache) {
11785        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11786    }
11787
11788    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11789            boolean fullInvalidate) {
11790        if (mGhostView != null) {
11791            mGhostView.invalidate(true);
11792            return;
11793        }
11794
11795        if (skipInvalidate()) {
11796            return;
11797        }
11798
11799        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11800                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11801                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11802                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11803            if (fullInvalidate) {
11804                mLastIsOpaque = isOpaque();
11805                mPrivateFlags &= ~PFLAG_DRAWN;
11806            }
11807
11808            mPrivateFlags |= PFLAG_DIRTY;
11809
11810            if (invalidateCache) {
11811                mPrivateFlags |= PFLAG_INVALIDATED;
11812                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11813            }
11814
11815            // Propagate the damage rectangle to the parent view.
11816            final AttachInfo ai = mAttachInfo;
11817            final ViewParent p = mParent;
11818            if (p != null && ai != null && l < r && t < b) {
11819                final Rect damage = ai.mTmpInvalRect;
11820                damage.set(l, t, r, b);
11821                p.invalidateChild(this, damage);
11822            }
11823
11824            // Damage the entire projection receiver, if necessary.
11825            if (mBackground != null && mBackground.isProjected()) {
11826                final View receiver = getProjectionReceiver();
11827                if (receiver != null) {
11828                    receiver.damageInParent();
11829                }
11830            }
11831
11832            // Damage the entire IsolatedZVolume receiving this view's shadow.
11833            if (isHardwareAccelerated() && getZ() != 0) {
11834                damageShadowReceiver();
11835            }
11836        }
11837    }
11838
11839    /**
11840     * @return this view's projection receiver, or {@code null} if none exists
11841     */
11842    private View getProjectionReceiver() {
11843        ViewParent p = getParent();
11844        while (p != null && p instanceof View) {
11845            final View v = (View) p;
11846            if (v.isProjectionReceiver()) {
11847                return v;
11848            }
11849            p = p.getParent();
11850        }
11851
11852        return null;
11853    }
11854
11855    /**
11856     * @return whether the view is a projection receiver
11857     */
11858    private boolean isProjectionReceiver() {
11859        return mBackground != null;
11860    }
11861
11862    /**
11863     * Damage area of the screen that can be covered by this View's shadow.
11864     *
11865     * This method will guarantee that any changes to shadows cast by a View
11866     * are damaged on the screen for future redraw.
11867     */
11868    private void damageShadowReceiver() {
11869        final AttachInfo ai = mAttachInfo;
11870        if (ai != null) {
11871            ViewParent p = getParent();
11872            if (p != null && p instanceof ViewGroup) {
11873                final ViewGroup vg = (ViewGroup) p;
11874                vg.damageInParent();
11875            }
11876        }
11877    }
11878
11879    /**
11880     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11881     * set any flags or handle all of the cases handled by the default invalidation methods.
11882     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11883     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11884     * walk up the hierarchy, transforming the dirty rect as necessary.
11885     *
11886     * The method also handles normal invalidation logic if display list properties are not
11887     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11888     * backup approach, to handle these cases used in the various property-setting methods.
11889     *
11890     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11891     * are not being used in this view
11892     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11893     * list properties are not being used in this view
11894     */
11895    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11896        if (!isHardwareAccelerated()
11897                || !mRenderNode.isValid()
11898                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11899            if (invalidateParent) {
11900                invalidateParentCaches();
11901            }
11902            if (forceRedraw) {
11903                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11904            }
11905            invalidate(false);
11906        } else {
11907            damageInParent();
11908        }
11909        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11910            damageShadowReceiver();
11911        }
11912    }
11913
11914    /**
11915     * Tells the parent view to damage this view's bounds.
11916     *
11917     * @hide
11918     */
11919    protected void damageInParent() {
11920        final AttachInfo ai = mAttachInfo;
11921        final ViewParent p = mParent;
11922        if (p != null && ai != null) {
11923            final Rect r = ai.mTmpInvalRect;
11924            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11925            if (mParent instanceof ViewGroup) {
11926                ((ViewGroup) mParent).damageChild(this, r);
11927            } else {
11928                mParent.invalidateChild(this, r);
11929            }
11930        }
11931    }
11932
11933    /**
11934     * Utility method to transform a given Rect by the current matrix of this view.
11935     */
11936    void transformRect(final Rect rect) {
11937        if (!getMatrix().isIdentity()) {
11938            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11939            boundingRect.set(rect);
11940            getMatrix().mapRect(boundingRect);
11941            rect.set((int) Math.floor(boundingRect.left),
11942                    (int) Math.floor(boundingRect.top),
11943                    (int) Math.ceil(boundingRect.right),
11944                    (int) Math.ceil(boundingRect.bottom));
11945        }
11946    }
11947
11948    /**
11949     * Used to indicate that the parent of this view should clear its caches. This functionality
11950     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11951     * which is necessary when various parent-managed properties of the view change, such as
11952     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11953     * clears the parent caches and does not causes an invalidate event.
11954     *
11955     * @hide
11956     */
11957    protected void invalidateParentCaches() {
11958        if (mParent instanceof View) {
11959            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11960        }
11961    }
11962
11963    /**
11964     * Used to indicate that the parent of this view should be invalidated. This functionality
11965     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11966     * which is necessary when various parent-managed properties of the view change, such as
11967     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11968     * an invalidation event to the parent.
11969     *
11970     * @hide
11971     */
11972    protected void invalidateParentIfNeeded() {
11973        if (isHardwareAccelerated() && mParent instanceof View) {
11974            ((View) mParent).invalidate(true);
11975        }
11976    }
11977
11978    /**
11979     * @hide
11980     */
11981    protected void invalidateParentIfNeededAndWasQuickRejected() {
11982        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11983            // View was rejected last time it was drawn by its parent; this may have changed
11984            invalidateParentIfNeeded();
11985        }
11986    }
11987
11988    /**
11989     * Indicates whether this View is opaque. An opaque View guarantees that it will
11990     * draw all the pixels overlapping its bounds using a fully opaque color.
11991     *
11992     * Subclasses of View should override this method whenever possible to indicate
11993     * whether an instance is opaque. Opaque Views are treated in a special way by
11994     * the View hierarchy, possibly allowing it to perform optimizations during
11995     * invalidate/draw passes.
11996     *
11997     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11998     */
11999    @ViewDebug.ExportedProperty(category = "drawing")
12000    public boolean isOpaque() {
12001        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12002                getFinalAlpha() >= 1.0f;
12003    }
12004
12005    /**
12006     * @hide
12007     */
12008    protected void computeOpaqueFlags() {
12009        // Opaque if:
12010        //   - Has a background
12011        //   - Background is opaque
12012        //   - Doesn't have scrollbars or scrollbars overlay
12013
12014        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12015            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12016        } else {
12017            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12018        }
12019
12020        final int flags = mViewFlags;
12021        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12022                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12023                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12024            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12025        } else {
12026            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12027        }
12028    }
12029
12030    /**
12031     * @hide
12032     */
12033    protected boolean hasOpaqueScrollbars() {
12034        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12035    }
12036
12037    /**
12038     * @return A handler associated with the thread running the View. This
12039     * handler can be used to pump events in the UI events queue.
12040     */
12041    public Handler getHandler() {
12042        final AttachInfo attachInfo = mAttachInfo;
12043        if (attachInfo != null) {
12044            return attachInfo.mHandler;
12045        }
12046        return null;
12047    }
12048
12049    /**
12050     * Gets the view root associated with the View.
12051     * @return The view root, or null if none.
12052     * @hide
12053     */
12054    public ViewRootImpl getViewRootImpl() {
12055        if (mAttachInfo != null) {
12056            return mAttachInfo.mViewRootImpl;
12057        }
12058        return null;
12059    }
12060
12061    /**
12062     * @hide
12063     */
12064    public HardwareRenderer getHardwareRenderer() {
12065        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12066    }
12067
12068    /**
12069     * <p>Causes the Runnable to be added to the message queue.
12070     * The runnable will be run on the user interface thread.</p>
12071     *
12072     * @param action The Runnable that will be executed.
12073     *
12074     * @return Returns true if the Runnable was successfully placed in to the
12075     *         message queue.  Returns false on failure, usually because the
12076     *         looper processing the message queue is exiting.
12077     *
12078     * @see #postDelayed
12079     * @see #removeCallbacks
12080     */
12081    public boolean post(Runnable action) {
12082        final AttachInfo attachInfo = mAttachInfo;
12083        if (attachInfo != null) {
12084            return attachInfo.mHandler.post(action);
12085        }
12086        // Assume that post will succeed later
12087        ViewRootImpl.getRunQueue().post(action);
12088        return true;
12089    }
12090
12091    /**
12092     * <p>Causes the Runnable to be added to the message queue, to be run
12093     * after the specified amount of time elapses.
12094     * The runnable will be run on the user interface thread.</p>
12095     *
12096     * @param action The Runnable that will be executed.
12097     * @param delayMillis The delay (in milliseconds) until the Runnable
12098     *        will be executed.
12099     *
12100     * @return true if the Runnable was successfully placed in to the
12101     *         message queue.  Returns false on failure, usually because the
12102     *         looper processing the message queue is exiting.  Note that a
12103     *         result of true does not mean the Runnable will be processed --
12104     *         if the looper is quit before the delivery time of the message
12105     *         occurs then the message will be dropped.
12106     *
12107     * @see #post
12108     * @see #removeCallbacks
12109     */
12110    public boolean postDelayed(Runnable action, long delayMillis) {
12111        final AttachInfo attachInfo = mAttachInfo;
12112        if (attachInfo != null) {
12113            return attachInfo.mHandler.postDelayed(action, delayMillis);
12114        }
12115        // Assume that post will succeed later
12116        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12117        return true;
12118    }
12119
12120    /**
12121     * <p>Causes the Runnable to execute on the next animation time step.
12122     * The runnable will be run on the user interface thread.</p>
12123     *
12124     * @param action The Runnable that will be executed.
12125     *
12126     * @see #postOnAnimationDelayed
12127     * @see #removeCallbacks
12128     */
12129    public void postOnAnimation(Runnable action) {
12130        final AttachInfo attachInfo = mAttachInfo;
12131        if (attachInfo != null) {
12132            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12133                    Choreographer.CALLBACK_ANIMATION, action, null);
12134        } else {
12135            // Assume that post will succeed later
12136            ViewRootImpl.getRunQueue().post(action);
12137        }
12138    }
12139
12140    /**
12141     * <p>Causes the Runnable to execute on the next animation time step,
12142     * after the specified amount of time elapses.
12143     * The runnable will be run on the user interface thread.</p>
12144     *
12145     * @param action The Runnable that will be executed.
12146     * @param delayMillis The delay (in milliseconds) until the Runnable
12147     *        will be executed.
12148     *
12149     * @see #postOnAnimation
12150     * @see #removeCallbacks
12151     */
12152    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12153        final AttachInfo attachInfo = mAttachInfo;
12154        if (attachInfo != null) {
12155            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12156                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12157        } else {
12158            // Assume that post will succeed later
12159            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12160        }
12161    }
12162
12163    /**
12164     * <p>Removes the specified Runnable from the message queue.</p>
12165     *
12166     * @param action The Runnable to remove from the message handling queue
12167     *
12168     * @return true if this view could ask the Handler to remove the Runnable,
12169     *         false otherwise. When the returned value is true, the Runnable
12170     *         may or may not have been actually removed from the message queue
12171     *         (for instance, if the Runnable was not in the queue already.)
12172     *
12173     * @see #post
12174     * @see #postDelayed
12175     * @see #postOnAnimation
12176     * @see #postOnAnimationDelayed
12177     */
12178    public boolean removeCallbacks(Runnable action) {
12179        if (action != null) {
12180            final AttachInfo attachInfo = mAttachInfo;
12181            if (attachInfo != null) {
12182                attachInfo.mHandler.removeCallbacks(action);
12183                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12184                        Choreographer.CALLBACK_ANIMATION, action, null);
12185            }
12186            // Assume that post will succeed later
12187            ViewRootImpl.getRunQueue().removeCallbacks(action);
12188        }
12189        return true;
12190    }
12191
12192    /**
12193     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12194     * Use this to invalidate the View from a non-UI thread.</p>
12195     *
12196     * <p>This method can be invoked from outside of the UI thread
12197     * only when this View is attached to a window.</p>
12198     *
12199     * @see #invalidate()
12200     * @see #postInvalidateDelayed(long)
12201     */
12202    public void postInvalidate() {
12203        postInvalidateDelayed(0);
12204    }
12205
12206    /**
12207     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12208     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12209     *
12210     * <p>This method can be invoked from outside of the UI thread
12211     * only when this View is attached to a window.</p>
12212     *
12213     * @param left The left coordinate of the rectangle to invalidate.
12214     * @param top The top coordinate of the rectangle to invalidate.
12215     * @param right The right coordinate of the rectangle to invalidate.
12216     * @param bottom The bottom coordinate of the rectangle to invalidate.
12217     *
12218     * @see #invalidate(int, int, int, int)
12219     * @see #invalidate(Rect)
12220     * @see #postInvalidateDelayed(long, int, int, int, int)
12221     */
12222    public void postInvalidate(int left, int top, int right, int bottom) {
12223        postInvalidateDelayed(0, left, top, right, bottom);
12224    }
12225
12226    /**
12227     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12228     * loop. Waits for the specified amount of time.</p>
12229     *
12230     * <p>This method can be invoked from outside of the UI thread
12231     * only when this View is attached to a window.</p>
12232     *
12233     * @param delayMilliseconds the duration in milliseconds to delay the
12234     *         invalidation by
12235     *
12236     * @see #invalidate()
12237     * @see #postInvalidate()
12238     */
12239    public void postInvalidateDelayed(long delayMilliseconds) {
12240        // We try only with the AttachInfo because there's no point in invalidating
12241        // if we are not attached to our window
12242        final AttachInfo attachInfo = mAttachInfo;
12243        if (attachInfo != null) {
12244            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12245        }
12246    }
12247
12248    /**
12249     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12250     * through the event loop. Waits for the specified amount of time.</p>
12251     *
12252     * <p>This method can be invoked from outside of the UI thread
12253     * only when this View is attached to a window.</p>
12254     *
12255     * @param delayMilliseconds the duration in milliseconds to delay the
12256     *         invalidation by
12257     * @param left The left coordinate of the rectangle to invalidate.
12258     * @param top The top coordinate of the rectangle to invalidate.
12259     * @param right The right coordinate of the rectangle to invalidate.
12260     * @param bottom The bottom coordinate of the rectangle to invalidate.
12261     *
12262     * @see #invalidate(int, int, int, int)
12263     * @see #invalidate(Rect)
12264     * @see #postInvalidate(int, int, int, int)
12265     */
12266    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12267            int right, int bottom) {
12268
12269        // We try only with the AttachInfo because there's no point in invalidating
12270        // if we are not attached to our window
12271        final AttachInfo attachInfo = mAttachInfo;
12272        if (attachInfo != null) {
12273            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12274            info.target = this;
12275            info.left = left;
12276            info.top = top;
12277            info.right = right;
12278            info.bottom = bottom;
12279
12280            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12281        }
12282    }
12283
12284    /**
12285     * <p>Cause an invalidate to happen on the next animation time step, typically the
12286     * next display frame.</p>
12287     *
12288     * <p>This method can be invoked from outside of the UI thread
12289     * only when this View is attached to a window.</p>
12290     *
12291     * @see #invalidate()
12292     */
12293    public void postInvalidateOnAnimation() {
12294        // We try only with the AttachInfo because there's no point in invalidating
12295        // if we are not attached to our window
12296        final AttachInfo attachInfo = mAttachInfo;
12297        if (attachInfo != null) {
12298            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12299        }
12300    }
12301
12302    /**
12303     * <p>Cause an invalidate of the specified area to happen on the next animation
12304     * time step, typically the next display frame.</p>
12305     *
12306     * <p>This method can be invoked from outside of the UI thread
12307     * only when this View is attached to a window.</p>
12308     *
12309     * @param left The left coordinate of the rectangle to invalidate.
12310     * @param top The top coordinate of the rectangle to invalidate.
12311     * @param right The right coordinate of the rectangle to invalidate.
12312     * @param bottom The bottom coordinate of the rectangle to invalidate.
12313     *
12314     * @see #invalidate(int, int, int, int)
12315     * @see #invalidate(Rect)
12316     */
12317    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12318        // We try only with the AttachInfo because there's no point in invalidating
12319        // if we are not attached to our window
12320        final AttachInfo attachInfo = mAttachInfo;
12321        if (attachInfo != null) {
12322            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12323            info.target = this;
12324            info.left = left;
12325            info.top = top;
12326            info.right = right;
12327            info.bottom = bottom;
12328
12329            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12330        }
12331    }
12332
12333    /**
12334     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12335     * This event is sent at most once every
12336     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12337     */
12338    private void postSendViewScrolledAccessibilityEventCallback() {
12339        if (mSendViewScrolledAccessibilityEvent == null) {
12340            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12341        }
12342        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12343            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12344            postDelayed(mSendViewScrolledAccessibilityEvent,
12345                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12346        }
12347    }
12348
12349    /**
12350     * Called by a parent to request that a child update its values for mScrollX
12351     * and mScrollY if necessary. This will typically be done if the child is
12352     * animating a scroll using a {@link android.widget.Scroller Scroller}
12353     * object.
12354     */
12355    public void computeScroll() {
12356    }
12357
12358    /**
12359     * <p>Indicate whether the horizontal edges are faded when the view is
12360     * scrolled horizontally.</p>
12361     *
12362     * @return true if the horizontal edges should are faded on scroll, false
12363     *         otherwise
12364     *
12365     * @see #setHorizontalFadingEdgeEnabled(boolean)
12366     *
12367     * @attr ref android.R.styleable#View_requiresFadingEdge
12368     */
12369    public boolean isHorizontalFadingEdgeEnabled() {
12370        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12371    }
12372
12373    /**
12374     * <p>Define whether the horizontal edges should be faded when this view
12375     * is scrolled horizontally.</p>
12376     *
12377     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12378     *                                    be faded when the view is scrolled
12379     *                                    horizontally
12380     *
12381     * @see #isHorizontalFadingEdgeEnabled()
12382     *
12383     * @attr ref android.R.styleable#View_requiresFadingEdge
12384     */
12385    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12386        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12387            if (horizontalFadingEdgeEnabled) {
12388                initScrollCache();
12389            }
12390
12391            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12392        }
12393    }
12394
12395    /**
12396     * <p>Indicate whether the vertical edges are faded when the view is
12397     * scrolled horizontally.</p>
12398     *
12399     * @return true if the vertical edges should are faded on scroll, false
12400     *         otherwise
12401     *
12402     * @see #setVerticalFadingEdgeEnabled(boolean)
12403     *
12404     * @attr ref android.R.styleable#View_requiresFadingEdge
12405     */
12406    public boolean isVerticalFadingEdgeEnabled() {
12407        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12408    }
12409
12410    /**
12411     * <p>Define whether the vertical edges should be faded when this view
12412     * is scrolled vertically.</p>
12413     *
12414     * @param verticalFadingEdgeEnabled true if the vertical edges should
12415     *                                  be faded when the view is scrolled
12416     *                                  vertically
12417     *
12418     * @see #isVerticalFadingEdgeEnabled()
12419     *
12420     * @attr ref android.R.styleable#View_requiresFadingEdge
12421     */
12422    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12423        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12424            if (verticalFadingEdgeEnabled) {
12425                initScrollCache();
12426            }
12427
12428            mViewFlags ^= FADING_EDGE_VERTICAL;
12429        }
12430    }
12431
12432    /**
12433     * Returns the strength, or intensity, of the top faded edge. The strength is
12434     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12435     * returns 0.0 or 1.0 but no value in between.
12436     *
12437     * Subclasses should override this method to provide a smoother fade transition
12438     * when scrolling occurs.
12439     *
12440     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12441     */
12442    protected float getTopFadingEdgeStrength() {
12443        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12444    }
12445
12446    /**
12447     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12448     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12449     * returns 0.0 or 1.0 but no value in between.
12450     *
12451     * Subclasses should override this method to provide a smoother fade transition
12452     * when scrolling occurs.
12453     *
12454     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12455     */
12456    protected float getBottomFadingEdgeStrength() {
12457        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12458                computeVerticalScrollRange() ? 1.0f : 0.0f;
12459    }
12460
12461    /**
12462     * Returns the strength, or intensity, of the left faded edge. The strength is
12463     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12464     * returns 0.0 or 1.0 but no value in between.
12465     *
12466     * Subclasses should override this method to provide a smoother fade transition
12467     * when scrolling occurs.
12468     *
12469     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12470     */
12471    protected float getLeftFadingEdgeStrength() {
12472        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12473    }
12474
12475    /**
12476     * Returns the strength, or intensity, of the right faded edge. The strength is
12477     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12478     * returns 0.0 or 1.0 but no value in between.
12479     *
12480     * Subclasses should override this method to provide a smoother fade transition
12481     * when scrolling occurs.
12482     *
12483     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12484     */
12485    protected float getRightFadingEdgeStrength() {
12486        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12487                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12488    }
12489
12490    /**
12491     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12492     * scrollbar is not drawn by default.</p>
12493     *
12494     * @return true if the horizontal scrollbar should be painted, false
12495     *         otherwise
12496     *
12497     * @see #setHorizontalScrollBarEnabled(boolean)
12498     */
12499    public boolean isHorizontalScrollBarEnabled() {
12500        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12501    }
12502
12503    /**
12504     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12505     * scrollbar is not drawn by default.</p>
12506     *
12507     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12508     *                                   be painted
12509     *
12510     * @see #isHorizontalScrollBarEnabled()
12511     */
12512    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12513        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12514            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12515            computeOpaqueFlags();
12516            resolvePadding();
12517        }
12518    }
12519
12520    /**
12521     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12522     * scrollbar is not drawn by default.</p>
12523     *
12524     * @return true if the vertical scrollbar should be painted, false
12525     *         otherwise
12526     *
12527     * @see #setVerticalScrollBarEnabled(boolean)
12528     */
12529    public boolean isVerticalScrollBarEnabled() {
12530        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12531    }
12532
12533    /**
12534     * <p>Define whether the vertical scrollbar should be drawn or not. The
12535     * scrollbar is not drawn by default.</p>
12536     *
12537     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12538     *                                 be painted
12539     *
12540     * @see #isVerticalScrollBarEnabled()
12541     */
12542    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12543        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12544            mViewFlags ^= SCROLLBARS_VERTICAL;
12545            computeOpaqueFlags();
12546            resolvePadding();
12547        }
12548    }
12549
12550    /**
12551     * @hide
12552     */
12553    protected void recomputePadding() {
12554        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12555    }
12556
12557    /**
12558     * Define whether scrollbars will fade when the view is not scrolling.
12559     *
12560     * @param fadeScrollbars whether to enable fading
12561     *
12562     * @attr ref android.R.styleable#View_fadeScrollbars
12563     */
12564    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12565        initScrollCache();
12566        final ScrollabilityCache scrollabilityCache = mScrollCache;
12567        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12568        if (fadeScrollbars) {
12569            scrollabilityCache.state = ScrollabilityCache.OFF;
12570        } else {
12571            scrollabilityCache.state = ScrollabilityCache.ON;
12572        }
12573    }
12574
12575    /**
12576     *
12577     * Returns true if scrollbars will fade when this view is not scrolling
12578     *
12579     * @return true if scrollbar fading is enabled
12580     *
12581     * @attr ref android.R.styleable#View_fadeScrollbars
12582     */
12583    public boolean isScrollbarFadingEnabled() {
12584        return mScrollCache != null && mScrollCache.fadeScrollBars;
12585    }
12586
12587    /**
12588     *
12589     * Returns the delay before scrollbars fade.
12590     *
12591     * @return the delay before scrollbars fade
12592     *
12593     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12594     */
12595    public int getScrollBarDefaultDelayBeforeFade() {
12596        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12597                mScrollCache.scrollBarDefaultDelayBeforeFade;
12598    }
12599
12600    /**
12601     * Define the delay before scrollbars fade.
12602     *
12603     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12604     *
12605     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12606     */
12607    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12608        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12609    }
12610
12611    /**
12612     *
12613     * Returns the scrollbar fade duration.
12614     *
12615     * @return the scrollbar fade duration
12616     *
12617     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12618     */
12619    public int getScrollBarFadeDuration() {
12620        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12621                mScrollCache.scrollBarFadeDuration;
12622    }
12623
12624    /**
12625     * Define the scrollbar fade duration.
12626     *
12627     * @param scrollBarFadeDuration - the scrollbar fade duration
12628     *
12629     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12630     */
12631    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12632        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12633    }
12634
12635    /**
12636     *
12637     * Returns the scrollbar size.
12638     *
12639     * @return the scrollbar size
12640     *
12641     * @attr ref android.R.styleable#View_scrollbarSize
12642     */
12643    public int getScrollBarSize() {
12644        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12645                mScrollCache.scrollBarSize;
12646    }
12647
12648    /**
12649     * Define the scrollbar size.
12650     *
12651     * @param scrollBarSize - the scrollbar size
12652     *
12653     * @attr ref android.R.styleable#View_scrollbarSize
12654     */
12655    public void setScrollBarSize(int scrollBarSize) {
12656        getScrollCache().scrollBarSize = scrollBarSize;
12657    }
12658
12659    /**
12660     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12661     * inset. When inset, they add to the padding of the view. And the scrollbars
12662     * can be drawn inside the padding area or on the edge of the view. For example,
12663     * if a view has a background drawable and you want to draw the scrollbars
12664     * inside the padding specified by the drawable, you can use
12665     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12666     * appear at the edge of the view, ignoring the padding, then you can use
12667     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12668     * @param style the style of the scrollbars. Should be one of
12669     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12670     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12671     * @see #SCROLLBARS_INSIDE_OVERLAY
12672     * @see #SCROLLBARS_INSIDE_INSET
12673     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12674     * @see #SCROLLBARS_OUTSIDE_INSET
12675     *
12676     * @attr ref android.R.styleable#View_scrollbarStyle
12677     */
12678    public void setScrollBarStyle(@ScrollBarStyle int style) {
12679        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12680            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12681            computeOpaqueFlags();
12682            resolvePadding();
12683        }
12684    }
12685
12686    /**
12687     * <p>Returns the current scrollbar style.</p>
12688     * @return the current scrollbar style
12689     * @see #SCROLLBARS_INSIDE_OVERLAY
12690     * @see #SCROLLBARS_INSIDE_INSET
12691     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12692     * @see #SCROLLBARS_OUTSIDE_INSET
12693     *
12694     * @attr ref android.R.styleable#View_scrollbarStyle
12695     */
12696    @ViewDebug.ExportedProperty(mapping = {
12697            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12698            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12699            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12700            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12701    })
12702    @ScrollBarStyle
12703    public int getScrollBarStyle() {
12704        return mViewFlags & SCROLLBARS_STYLE_MASK;
12705    }
12706
12707    /**
12708     * <p>Compute the horizontal range that the horizontal scrollbar
12709     * represents.</p>
12710     *
12711     * <p>The range is expressed in arbitrary units that must be the same as the
12712     * units used by {@link #computeHorizontalScrollExtent()} and
12713     * {@link #computeHorizontalScrollOffset()}.</p>
12714     *
12715     * <p>The default range is the drawing width of this view.</p>
12716     *
12717     * @return the total horizontal range represented by the horizontal
12718     *         scrollbar
12719     *
12720     * @see #computeHorizontalScrollExtent()
12721     * @see #computeHorizontalScrollOffset()
12722     * @see android.widget.ScrollBarDrawable
12723     */
12724    protected int computeHorizontalScrollRange() {
12725        return getWidth();
12726    }
12727
12728    /**
12729     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12730     * within the horizontal range. This value is used to compute the position
12731     * of the thumb within the scrollbar's track.</p>
12732     *
12733     * <p>The range is expressed in arbitrary units that must be the same as the
12734     * units used by {@link #computeHorizontalScrollRange()} and
12735     * {@link #computeHorizontalScrollExtent()}.</p>
12736     *
12737     * <p>The default offset is the scroll offset of this view.</p>
12738     *
12739     * @return the horizontal offset of the scrollbar's thumb
12740     *
12741     * @see #computeHorizontalScrollRange()
12742     * @see #computeHorizontalScrollExtent()
12743     * @see android.widget.ScrollBarDrawable
12744     */
12745    protected int computeHorizontalScrollOffset() {
12746        return mScrollX;
12747    }
12748
12749    /**
12750     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12751     * within the horizontal range. This value is used to compute the length
12752     * of the thumb within the scrollbar's track.</p>
12753     *
12754     * <p>The range is expressed in arbitrary units that must be the same as the
12755     * units used by {@link #computeHorizontalScrollRange()} and
12756     * {@link #computeHorizontalScrollOffset()}.</p>
12757     *
12758     * <p>The default extent is the drawing width of this view.</p>
12759     *
12760     * @return the horizontal extent of the scrollbar's thumb
12761     *
12762     * @see #computeHorizontalScrollRange()
12763     * @see #computeHorizontalScrollOffset()
12764     * @see android.widget.ScrollBarDrawable
12765     */
12766    protected int computeHorizontalScrollExtent() {
12767        return getWidth();
12768    }
12769
12770    /**
12771     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12772     *
12773     * <p>The range is expressed in arbitrary units that must be the same as the
12774     * units used by {@link #computeVerticalScrollExtent()} and
12775     * {@link #computeVerticalScrollOffset()}.</p>
12776     *
12777     * @return the total vertical range represented by the vertical scrollbar
12778     *
12779     * <p>The default range is the drawing height of this view.</p>
12780     *
12781     * @see #computeVerticalScrollExtent()
12782     * @see #computeVerticalScrollOffset()
12783     * @see android.widget.ScrollBarDrawable
12784     */
12785    protected int computeVerticalScrollRange() {
12786        return getHeight();
12787    }
12788
12789    /**
12790     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12791     * within the horizontal range. This value is used to compute the position
12792     * of the thumb within the scrollbar's track.</p>
12793     *
12794     * <p>The range is expressed in arbitrary units that must be the same as the
12795     * units used by {@link #computeVerticalScrollRange()} and
12796     * {@link #computeVerticalScrollExtent()}.</p>
12797     *
12798     * <p>The default offset is the scroll offset of this view.</p>
12799     *
12800     * @return the vertical offset of the scrollbar's thumb
12801     *
12802     * @see #computeVerticalScrollRange()
12803     * @see #computeVerticalScrollExtent()
12804     * @see android.widget.ScrollBarDrawable
12805     */
12806    protected int computeVerticalScrollOffset() {
12807        return mScrollY;
12808    }
12809
12810    /**
12811     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12812     * within the vertical range. This value is used to compute the length
12813     * of the thumb within the scrollbar's track.</p>
12814     *
12815     * <p>The range is expressed in arbitrary units that must be the same as the
12816     * units used by {@link #computeVerticalScrollRange()} and
12817     * {@link #computeVerticalScrollOffset()}.</p>
12818     *
12819     * <p>The default extent is the drawing height of this view.</p>
12820     *
12821     * @return the vertical extent of the scrollbar's thumb
12822     *
12823     * @see #computeVerticalScrollRange()
12824     * @see #computeVerticalScrollOffset()
12825     * @see android.widget.ScrollBarDrawable
12826     */
12827    protected int computeVerticalScrollExtent() {
12828        return getHeight();
12829    }
12830
12831    /**
12832     * Check if this view can be scrolled horizontally in a certain direction.
12833     *
12834     * @param direction Negative to check scrolling left, positive to check scrolling right.
12835     * @return true if this view can be scrolled in the specified direction, false otherwise.
12836     */
12837    public boolean canScrollHorizontally(int direction) {
12838        final int offset = computeHorizontalScrollOffset();
12839        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12840        if (range == 0) return false;
12841        if (direction < 0) {
12842            return offset > 0;
12843        } else {
12844            return offset < range - 1;
12845        }
12846    }
12847
12848    /**
12849     * Check if this view can be scrolled vertically in a certain direction.
12850     *
12851     * @param direction Negative to check scrolling up, positive to check scrolling down.
12852     * @return true if this view can be scrolled in the specified direction, false otherwise.
12853     */
12854    public boolean canScrollVertically(int direction) {
12855        final int offset = computeVerticalScrollOffset();
12856        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12857        if (range == 0) return false;
12858        if (direction < 0) {
12859            return offset > 0;
12860        } else {
12861            return offset < range - 1;
12862        }
12863    }
12864
12865    /**
12866     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12867     * scrollbars are painted only if they have been awakened first.</p>
12868     *
12869     * @param canvas the canvas on which to draw the scrollbars
12870     *
12871     * @see #awakenScrollBars(int)
12872     */
12873    protected final void onDrawScrollBars(Canvas canvas) {
12874        // scrollbars are drawn only when the animation is running
12875        final ScrollabilityCache cache = mScrollCache;
12876        if (cache != null) {
12877
12878            int state = cache.state;
12879
12880            if (state == ScrollabilityCache.OFF) {
12881                return;
12882            }
12883
12884            boolean invalidate = false;
12885
12886            if (state == ScrollabilityCache.FADING) {
12887                // We're fading -- get our fade interpolation
12888                if (cache.interpolatorValues == null) {
12889                    cache.interpolatorValues = new float[1];
12890                }
12891
12892                float[] values = cache.interpolatorValues;
12893
12894                // Stops the animation if we're done
12895                if (cache.scrollBarInterpolator.timeToValues(values) ==
12896                        Interpolator.Result.FREEZE_END) {
12897                    cache.state = ScrollabilityCache.OFF;
12898                } else {
12899                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
12900                }
12901
12902                // This will make the scroll bars inval themselves after
12903                // drawing. We only want this when we're fading so that
12904                // we prevent excessive redraws
12905                invalidate = true;
12906            } else {
12907                // We're just on -- but we may have been fading before so
12908                // reset alpha
12909                cache.scrollBar.mutate().setAlpha(255);
12910            }
12911
12912
12913            final int viewFlags = mViewFlags;
12914
12915            final boolean drawHorizontalScrollBar =
12916                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12917            final boolean drawVerticalScrollBar =
12918                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12919                && !isVerticalScrollBarHidden();
12920
12921            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12922                final int width = mRight - mLeft;
12923                final int height = mBottom - mTop;
12924
12925                final ScrollBarDrawable scrollBar = cache.scrollBar;
12926
12927                final int scrollX = mScrollX;
12928                final int scrollY = mScrollY;
12929                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12930
12931                int left;
12932                int top;
12933                int right;
12934                int bottom;
12935
12936                if (drawHorizontalScrollBar) {
12937                    int size = scrollBar.getSize(false);
12938                    if (size <= 0) {
12939                        size = cache.scrollBarSize;
12940                    }
12941
12942                    scrollBar.setParameters(computeHorizontalScrollRange(),
12943                                            computeHorizontalScrollOffset(),
12944                                            computeHorizontalScrollExtent(), false);
12945                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12946                            getVerticalScrollbarWidth() : 0;
12947                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12948                    left = scrollX + (mPaddingLeft & inside);
12949                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12950                    bottom = top + size;
12951                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12952                    if (invalidate) {
12953                        invalidate(left, top, right, bottom);
12954                    }
12955                }
12956
12957                if (drawVerticalScrollBar) {
12958                    int size = scrollBar.getSize(true);
12959                    if (size <= 0) {
12960                        size = cache.scrollBarSize;
12961                    }
12962
12963                    scrollBar.setParameters(computeVerticalScrollRange(),
12964                                            computeVerticalScrollOffset(),
12965                                            computeVerticalScrollExtent(), true);
12966                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12967                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12968                        verticalScrollbarPosition = isLayoutRtl() ?
12969                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12970                    }
12971                    switch (verticalScrollbarPosition) {
12972                        default:
12973                        case SCROLLBAR_POSITION_RIGHT:
12974                            left = scrollX + width - size - (mUserPaddingRight & inside);
12975                            break;
12976                        case SCROLLBAR_POSITION_LEFT:
12977                            left = scrollX + (mUserPaddingLeft & inside);
12978                            break;
12979                    }
12980                    top = scrollY + (mPaddingTop & inside);
12981                    right = left + size;
12982                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12983                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12984                    if (invalidate) {
12985                        invalidate(left, top, right, bottom);
12986                    }
12987                }
12988            }
12989        }
12990    }
12991
12992    /**
12993     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12994     * FastScroller is visible.
12995     * @return whether to temporarily hide the vertical scrollbar
12996     * @hide
12997     */
12998    protected boolean isVerticalScrollBarHidden() {
12999        return false;
13000    }
13001
13002    /**
13003     * <p>Draw the horizontal scrollbar if
13004     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13005     *
13006     * @param canvas the canvas on which to draw the scrollbar
13007     * @param scrollBar the scrollbar's drawable
13008     *
13009     * @see #isHorizontalScrollBarEnabled()
13010     * @see #computeHorizontalScrollRange()
13011     * @see #computeHorizontalScrollExtent()
13012     * @see #computeHorizontalScrollOffset()
13013     * @see android.widget.ScrollBarDrawable
13014     * @hide
13015     */
13016    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13017            int l, int t, int r, int b) {
13018        scrollBar.setBounds(l, t, r, b);
13019        scrollBar.draw(canvas);
13020    }
13021
13022    /**
13023     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13024     * returns true.</p>
13025     *
13026     * @param canvas the canvas on which to draw the scrollbar
13027     * @param scrollBar the scrollbar's drawable
13028     *
13029     * @see #isVerticalScrollBarEnabled()
13030     * @see #computeVerticalScrollRange()
13031     * @see #computeVerticalScrollExtent()
13032     * @see #computeVerticalScrollOffset()
13033     * @see android.widget.ScrollBarDrawable
13034     * @hide
13035     */
13036    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13037            int l, int t, int r, int b) {
13038        scrollBar.setBounds(l, t, r, b);
13039        scrollBar.draw(canvas);
13040    }
13041
13042    /**
13043     * Implement this to do your drawing.
13044     *
13045     * @param canvas the canvas on which the background will be drawn
13046     */
13047    protected void onDraw(Canvas canvas) {
13048    }
13049
13050    /*
13051     * Caller is responsible for calling requestLayout if necessary.
13052     * (This allows addViewInLayout to not request a new layout.)
13053     */
13054    void assignParent(ViewParent parent) {
13055        if (mParent == null) {
13056            mParent = parent;
13057        } else if (parent == null) {
13058            mParent = null;
13059        } else {
13060            throw new RuntimeException("view " + this + " being added, but"
13061                    + " it already has a parent");
13062        }
13063    }
13064
13065    /**
13066     * This is called when the view is attached to a window.  At this point it
13067     * has a Surface and will start drawing.  Note that this function is
13068     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13069     * however it may be called any time before the first onDraw -- including
13070     * before or after {@link #onMeasure(int, int)}.
13071     *
13072     * @see #onDetachedFromWindow()
13073     */
13074    protected void onAttachedToWindow() {
13075        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13076            mParent.requestTransparentRegion(this);
13077        }
13078
13079        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13080            initialAwakenScrollBars();
13081            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13082        }
13083
13084        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13085
13086        jumpDrawablesToCurrentState();
13087
13088        resetSubtreeAccessibilityStateChanged();
13089
13090        // rebuild, since Outline not maintained while View is detached
13091        rebuildOutline();
13092
13093        if (isFocused()) {
13094            InputMethodManager imm = InputMethodManager.peekInstance();
13095            imm.focusIn(this);
13096        }
13097    }
13098
13099    /**
13100     * Resolve all RTL related properties.
13101     *
13102     * @return true if resolution of RTL properties has been done
13103     *
13104     * @hide
13105     */
13106    public boolean resolveRtlPropertiesIfNeeded() {
13107        if (!needRtlPropertiesResolution()) return false;
13108
13109        // Order is important here: LayoutDirection MUST be resolved first
13110        if (!isLayoutDirectionResolved()) {
13111            resolveLayoutDirection();
13112            resolveLayoutParams();
13113        }
13114        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13115        if (!isTextDirectionResolved()) {
13116            resolveTextDirection();
13117        }
13118        if (!isTextAlignmentResolved()) {
13119            resolveTextAlignment();
13120        }
13121        // Should resolve Drawables before Padding because we need the layout direction of the
13122        // Drawable to correctly resolve Padding.
13123        if (!areDrawablesResolved()) {
13124            resolveDrawables();
13125        }
13126        if (!isPaddingResolved()) {
13127            resolvePadding();
13128        }
13129        onRtlPropertiesChanged(getLayoutDirection());
13130        return true;
13131    }
13132
13133    /**
13134     * Reset resolution of all RTL related properties.
13135     *
13136     * @hide
13137     */
13138    public void resetRtlProperties() {
13139        resetResolvedLayoutDirection();
13140        resetResolvedTextDirection();
13141        resetResolvedTextAlignment();
13142        resetResolvedPadding();
13143        resetResolvedDrawables();
13144    }
13145
13146    /**
13147     * @see #onScreenStateChanged(int)
13148     */
13149    void dispatchScreenStateChanged(int screenState) {
13150        onScreenStateChanged(screenState);
13151    }
13152
13153    /**
13154     * This method is called whenever the state of the screen this view is
13155     * attached to changes. A state change will usually occurs when the screen
13156     * turns on or off (whether it happens automatically or the user does it
13157     * manually.)
13158     *
13159     * @param screenState The new state of the screen. Can be either
13160     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13161     */
13162    public void onScreenStateChanged(int screenState) {
13163    }
13164
13165    /**
13166     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13167     */
13168    private boolean hasRtlSupport() {
13169        return mContext.getApplicationInfo().hasRtlSupport();
13170    }
13171
13172    /**
13173     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13174     * RTL not supported)
13175     */
13176    private boolean isRtlCompatibilityMode() {
13177        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13178        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13179    }
13180
13181    /**
13182     * @return true if RTL properties need resolution.
13183     *
13184     */
13185    private boolean needRtlPropertiesResolution() {
13186        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13187    }
13188
13189    /**
13190     * Called when any RTL property (layout direction or text direction or text alignment) has
13191     * been changed.
13192     *
13193     * Subclasses need to override this method to take care of cached information that depends on the
13194     * resolved layout direction, or to inform child views that inherit their layout direction.
13195     *
13196     * The default implementation does nothing.
13197     *
13198     * @param layoutDirection the direction of the layout
13199     *
13200     * @see #LAYOUT_DIRECTION_LTR
13201     * @see #LAYOUT_DIRECTION_RTL
13202     */
13203    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13204    }
13205
13206    /**
13207     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13208     * that the parent directionality can and will be resolved before its children.
13209     *
13210     * @return true if resolution has been done, false otherwise.
13211     *
13212     * @hide
13213     */
13214    public boolean resolveLayoutDirection() {
13215        // Clear any previous layout direction resolution
13216        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13217
13218        if (hasRtlSupport()) {
13219            // Set resolved depending on layout direction
13220            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13221                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13222                case LAYOUT_DIRECTION_INHERIT:
13223                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13224                    // later to get the correct resolved value
13225                    if (!canResolveLayoutDirection()) return false;
13226
13227                    // Parent has not yet resolved, LTR is still the default
13228                    try {
13229                        if (!mParent.isLayoutDirectionResolved()) return false;
13230
13231                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13232                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13233                        }
13234                    } catch (AbstractMethodError e) {
13235                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13236                                " does not fully implement ViewParent", e);
13237                    }
13238                    break;
13239                case LAYOUT_DIRECTION_RTL:
13240                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13241                    break;
13242                case LAYOUT_DIRECTION_LOCALE:
13243                    if((LAYOUT_DIRECTION_RTL ==
13244                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13245                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13246                    }
13247                    break;
13248                default:
13249                    // Nothing to do, LTR by default
13250            }
13251        }
13252
13253        // Set to resolved
13254        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13255        return true;
13256    }
13257
13258    /**
13259     * Check if layout direction resolution can be done.
13260     *
13261     * @return true if layout direction resolution can be done otherwise return false.
13262     */
13263    public boolean canResolveLayoutDirection() {
13264        switch (getRawLayoutDirection()) {
13265            case LAYOUT_DIRECTION_INHERIT:
13266                if (mParent != null) {
13267                    try {
13268                        return mParent.canResolveLayoutDirection();
13269                    } catch (AbstractMethodError e) {
13270                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13271                                " does not fully implement ViewParent", e);
13272                    }
13273                }
13274                return false;
13275
13276            default:
13277                return true;
13278        }
13279    }
13280
13281    /**
13282     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13283     * {@link #onMeasure(int, int)}.
13284     *
13285     * @hide
13286     */
13287    public void resetResolvedLayoutDirection() {
13288        // Reset the current resolved bits
13289        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13290    }
13291
13292    /**
13293     * @return true if the layout direction is inherited.
13294     *
13295     * @hide
13296     */
13297    public boolean isLayoutDirectionInherited() {
13298        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13299    }
13300
13301    /**
13302     * @return true if layout direction has been resolved.
13303     */
13304    public boolean isLayoutDirectionResolved() {
13305        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13306    }
13307
13308    /**
13309     * Return if padding has been resolved
13310     *
13311     * @hide
13312     */
13313    boolean isPaddingResolved() {
13314        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13315    }
13316
13317    /**
13318     * Resolves padding depending on layout direction, if applicable, and
13319     * recomputes internal padding values to adjust for scroll bars.
13320     *
13321     * @hide
13322     */
13323    public void resolvePadding() {
13324        final int resolvedLayoutDirection = getLayoutDirection();
13325
13326        if (!isRtlCompatibilityMode()) {
13327            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13328            // If start / end padding are defined, they will be resolved (hence overriding) to
13329            // left / right or right / left depending on the resolved layout direction.
13330            // If start / end padding are not defined, use the left / right ones.
13331            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13332                Rect padding = sThreadLocal.get();
13333                if (padding == null) {
13334                    padding = new Rect();
13335                    sThreadLocal.set(padding);
13336                }
13337                mBackground.getPadding(padding);
13338                if (!mLeftPaddingDefined) {
13339                    mUserPaddingLeftInitial = padding.left;
13340                }
13341                if (!mRightPaddingDefined) {
13342                    mUserPaddingRightInitial = padding.right;
13343                }
13344            }
13345            switch (resolvedLayoutDirection) {
13346                case LAYOUT_DIRECTION_RTL:
13347                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13348                        mUserPaddingRight = mUserPaddingStart;
13349                    } else {
13350                        mUserPaddingRight = mUserPaddingRightInitial;
13351                    }
13352                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13353                        mUserPaddingLeft = mUserPaddingEnd;
13354                    } else {
13355                        mUserPaddingLeft = mUserPaddingLeftInitial;
13356                    }
13357                    break;
13358                case LAYOUT_DIRECTION_LTR:
13359                default:
13360                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13361                        mUserPaddingLeft = mUserPaddingStart;
13362                    } else {
13363                        mUserPaddingLeft = mUserPaddingLeftInitial;
13364                    }
13365                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13366                        mUserPaddingRight = mUserPaddingEnd;
13367                    } else {
13368                        mUserPaddingRight = mUserPaddingRightInitial;
13369                    }
13370            }
13371
13372            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13373        }
13374
13375        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13376        onRtlPropertiesChanged(resolvedLayoutDirection);
13377
13378        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13379    }
13380
13381    /**
13382     * Reset the resolved layout direction.
13383     *
13384     * @hide
13385     */
13386    public void resetResolvedPadding() {
13387        resetResolvedPaddingInternal();
13388    }
13389
13390    /**
13391     * Used when we only want to reset *this* view's padding and not trigger overrides
13392     * in ViewGroup that reset children too.
13393     */
13394    void resetResolvedPaddingInternal() {
13395        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13396    }
13397
13398    /**
13399     * This is called when the view is detached from a window.  At this point it
13400     * no longer has a surface for drawing.
13401     *
13402     * @see #onAttachedToWindow()
13403     */
13404    protected void onDetachedFromWindow() {
13405    }
13406
13407    /**
13408     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13409     * after onDetachedFromWindow().
13410     *
13411     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13412     * The super method should be called at the end of the overridden method to ensure
13413     * subclasses are destroyed first
13414     *
13415     * @hide
13416     */
13417    protected void onDetachedFromWindowInternal() {
13418        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13419        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13420
13421        removeUnsetPressCallback();
13422        removeLongPressCallback();
13423        removePerformClickCallback();
13424        removeSendViewScrolledAccessibilityEventCallback();
13425        stopNestedScroll();
13426
13427        // Anything that started animating right before detach should already
13428        // be in its final state when re-attached.
13429        jumpDrawablesToCurrentState();
13430
13431        destroyDrawingCache();
13432
13433        cleanupDraw();
13434        mCurrentAnimation = null;
13435    }
13436
13437    private void cleanupDraw() {
13438        resetDisplayList();
13439        if (mAttachInfo != null) {
13440            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13441        }
13442    }
13443
13444    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13445    }
13446
13447    /**
13448     * @return The number of times this view has been attached to a window
13449     */
13450    protected int getWindowAttachCount() {
13451        return mWindowAttachCount;
13452    }
13453
13454    /**
13455     * Retrieve a unique token identifying the window this view is attached to.
13456     * @return Return the window's token for use in
13457     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13458     */
13459    public IBinder getWindowToken() {
13460        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13461    }
13462
13463    /**
13464     * Retrieve the {@link WindowId} for the window this view is
13465     * currently attached to.
13466     */
13467    public WindowId getWindowId() {
13468        if (mAttachInfo == null) {
13469            return null;
13470        }
13471        if (mAttachInfo.mWindowId == null) {
13472            try {
13473                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13474                        mAttachInfo.mWindowToken);
13475                mAttachInfo.mWindowId = new WindowId(
13476                        mAttachInfo.mIWindowId);
13477            } catch (RemoteException e) {
13478            }
13479        }
13480        return mAttachInfo.mWindowId;
13481    }
13482
13483    /**
13484     * Retrieve a unique token identifying the top-level "real" window of
13485     * the window that this view is attached to.  That is, this is like
13486     * {@link #getWindowToken}, except if the window this view in is a panel
13487     * window (attached to another containing window), then the token of
13488     * the containing window is returned instead.
13489     *
13490     * @return Returns the associated window token, either
13491     * {@link #getWindowToken()} or the containing window's token.
13492     */
13493    public IBinder getApplicationWindowToken() {
13494        AttachInfo ai = mAttachInfo;
13495        if (ai != null) {
13496            IBinder appWindowToken = ai.mPanelParentWindowToken;
13497            if (appWindowToken == null) {
13498                appWindowToken = ai.mWindowToken;
13499            }
13500            return appWindowToken;
13501        }
13502        return null;
13503    }
13504
13505    /**
13506     * Gets the logical display to which the view's window has been attached.
13507     *
13508     * @return The logical display, or null if the view is not currently attached to a window.
13509     */
13510    public Display getDisplay() {
13511        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13512    }
13513
13514    /**
13515     * Retrieve private session object this view hierarchy is using to
13516     * communicate with the window manager.
13517     * @return the session object to communicate with the window manager
13518     */
13519    /*package*/ IWindowSession getWindowSession() {
13520        return mAttachInfo != null ? mAttachInfo.mSession : null;
13521    }
13522
13523    /**
13524     * @param info the {@link android.view.View.AttachInfo} to associated with
13525     *        this view
13526     */
13527    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13528        //System.out.println("Attached! " + this);
13529        mAttachInfo = info;
13530        if (mOverlay != null) {
13531            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13532        }
13533        mWindowAttachCount++;
13534        // We will need to evaluate the drawable state at least once.
13535        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13536        if (mFloatingTreeObserver != null) {
13537            info.mTreeObserver.merge(mFloatingTreeObserver);
13538            mFloatingTreeObserver = null;
13539        }
13540        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13541            mAttachInfo.mScrollContainers.add(this);
13542            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13543        }
13544        performCollectViewAttributes(mAttachInfo, visibility);
13545        onAttachedToWindow();
13546
13547        ListenerInfo li = mListenerInfo;
13548        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13549                li != null ? li.mOnAttachStateChangeListeners : null;
13550        if (listeners != null && listeners.size() > 0) {
13551            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13552            // perform the dispatching. The iterator is a safe guard against listeners that
13553            // could mutate the list by calling the various add/remove methods. This prevents
13554            // the array from being modified while we iterate it.
13555            for (OnAttachStateChangeListener listener : listeners) {
13556                listener.onViewAttachedToWindow(this);
13557            }
13558        }
13559
13560        int vis = info.mWindowVisibility;
13561        if (vis != GONE) {
13562            onWindowVisibilityChanged(vis);
13563        }
13564        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13565            // If nobody has evaluated the drawable state yet, then do it now.
13566            refreshDrawableState();
13567        }
13568        needGlobalAttributesUpdate(false);
13569    }
13570
13571    void dispatchDetachedFromWindow() {
13572        AttachInfo info = mAttachInfo;
13573        if (info != null) {
13574            int vis = info.mWindowVisibility;
13575            if (vis != GONE) {
13576                onWindowVisibilityChanged(GONE);
13577            }
13578        }
13579
13580        onDetachedFromWindow();
13581        onDetachedFromWindowInternal();
13582
13583        ListenerInfo li = mListenerInfo;
13584        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13585                li != null ? li.mOnAttachStateChangeListeners : null;
13586        if (listeners != null && listeners.size() > 0) {
13587            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13588            // perform the dispatching. The iterator is a safe guard against listeners that
13589            // could mutate the list by calling the various add/remove methods. This prevents
13590            // the array from being modified while we iterate it.
13591            for (OnAttachStateChangeListener listener : listeners) {
13592                listener.onViewDetachedFromWindow(this);
13593            }
13594        }
13595
13596        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13597            mAttachInfo.mScrollContainers.remove(this);
13598            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13599        }
13600
13601        mAttachInfo = null;
13602        if (mOverlay != null) {
13603            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13604        }
13605    }
13606
13607    /**
13608     * Cancel any deferred high-level input events that were previously posted to the event queue.
13609     *
13610     * <p>Many views post high-level events such as click handlers to the event queue
13611     * to run deferred in order to preserve a desired user experience - clearing visible
13612     * pressed states before executing, etc. This method will abort any events of this nature
13613     * that are currently in flight.</p>
13614     *
13615     * <p>Custom views that generate their own high-level deferred input events should override
13616     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13617     *
13618     * <p>This will also cancel pending input events for any child views.</p>
13619     *
13620     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13621     * This will not impact newer events posted after this call that may occur as a result of
13622     * lower-level input events still waiting in the queue. If you are trying to prevent
13623     * double-submitted  events for the duration of some sort of asynchronous transaction
13624     * you should also take other steps to protect against unexpected double inputs e.g. calling
13625     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13626     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13627     */
13628    public final void cancelPendingInputEvents() {
13629        dispatchCancelPendingInputEvents();
13630    }
13631
13632    /**
13633     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13634     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13635     */
13636    void dispatchCancelPendingInputEvents() {
13637        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13638        onCancelPendingInputEvents();
13639        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13640            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13641                    " did not call through to super.onCancelPendingInputEvents()");
13642        }
13643    }
13644
13645    /**
13646     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13647     * a parent view.
13648     *
13649     * <p>This method is responsible for removing any pending high-level input events that were
13650     * posted to the event queue to run later. Custom view classes that post their own deferred
13651     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13652     * {@link android.os.Handler} should override this method, call
13653     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13654     * </p>
13655     */
13656    public void onCancelPendingInputEvents() {
13657        removePerformClickCallback();
13658        cancelLongPress();
13659        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13660    }
13661
13662    /**
13663     * Store this view hierarchy's frozen state into the given container.
13664     *
13665     * @param container The SparseArray in which to save the view's state.
13666     *
13667     * @see #restoreHierarchyState(android.util.SparseArray)
13668     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13669     * @see #onSaveInstanceState()
13670     */
13671    public void saveHierarchyState(SparseArray<Parcelable> container) {
13672        dispatchSaveInstanceState(container);
13673    }
13674
13675    /**
13676     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13677     * this view and its children. May be overridden to modify how freezing happens to a
13678     * view's children; for example, some views may want to not store state for their children.
13679     *
13680     * @param container The SparseArray in which to save the view's state.
13681     *
13682     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13683     * @see #saveHierarchyState(android.util.SparseArray)
13684     * @see #onSaveInstanceState()
13685     */
13686    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13687        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13688            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13689            Parcelable state = onSaveInstanceState();
13690            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13691                throw new IllegalStateException(
13692                        "Derived class did not call super.onSaveInstanceState()");
13693            }
13694            if (state != null) {
13695                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13696                // + ": " + state);
13697                container.put(mID, state);
13698            }
13699        }
13700    }
13701
13702    /**
13703     * Hook allowing a view to generate a representation of its internal state
13704     * that can later be used to create a new instance with that same state.
13705     * This state should only contain information that is not persistent or can
13706     * not be reconstructed later. For example, you will never store your
13707     * current position on screen because that will be computed again when a
13708     * new instance of the view is placed in its view hierarchy.
13709     * <p>
13710     * Some examples of things you may store here: the current cursor position
13711     * in a text view (but usually not the text itself since that is stored in a
13712     * content provider or other persistent storage), the currently selected
13713     * item in a list view.
13714     *
13715     * @return Returns a Parcelable object containing the view's current dynamic
13716     *         state, or null if there is nothing interesting to save. The
13717     *         default implementation returns null.
13718     * @see #onRestoreInstanceState(android.os.Parcelable)
13719     * @see #saveHierarchyState(android.util.SparseArray)
13720     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13721     * @see #setSaveEnabled(boolean)
13722     */
13723    protected Parcelable onSaveInstanceState() {
13724        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13725        return BaseSavedState.EMPTY_STATE;
13726    }
13727
13728    /**
13729     * Restore this view hierarchy's frozen state from the given container.
13730     *
13731     * @param container The SparseArray which holds previously frozen states.
13732     *
13733     * @see #saveHierarchyState(android.util.SparseArray)
13734     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13735     * @see #onRestoreInstanceState(android.os.Parcelable)
13736     */
13737    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13738        dispatchRestoreInstanceState(container);
13739    }
13740
13741    /**
13742     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13743     * state for this view and its children. May be overridden to modify how restoring
13744     * happens to a view's children; for example, some views may want to not store state
13745     * for their children.
13746     *
13747     * @param container The SparseArray which holds previously saved state.
13748     *
13749     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13750     * @see #restoreHierarchyState(android.util.SparseArray)
13751     * @see #onRestoreInstanceState(android.os.Parcelable)
13752     */
13753    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13754        if (mID != NO_ID) {
13755            Parcelable state = container.get(mID);
13756            if (state != null) {
13757                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13758                // + ": " + state);
13759                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13760                onRestoreInstanceState(state);
13761                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13762                    throw new IllegalStateException(
13763                            "Derived class did not call super.onRestoreInstanceState()");
13764                }
13765            }
13766        }
13767    }
13768
13769    /**
13770     * Hook allowing a view to re-apply a representation of its internal state that had previously
13771     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13772     * null state.
13773     *
13774     * @param state The frozen state that had previously been returned by
13775     *        {@link #onSaveInstanceState}.
13776     *
13777     * @see #onSaveInstanceState()
13778     * @see #restoreHierarchyState(android.util.SparseArray)
13779     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13780     */
13781    protected void onRestoreInstanceState(Parcelable state) {
13782        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13783        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13784            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13785                    + "received " + state.getClass().toString() + " instead. This usually happens "
13786                    + "when two views of different type have the same id in the same hierarchy. "
13787                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13788                    + "other views do not use the same id.");
13789        }
13790    }
13791
13792    /**
13793     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13794     *
13795     * @return the drawing start time in milliseconds
13796     */
13797    public long getDrawingTime() {
13798        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13799    }
13800
13801    /**
13802     * <p>Enables or disables the duplication of the parent's state into this view. When
13803     * duplication is enabled, this view gets its drawable state from its parent rather
13804     * than from its own internal properties.</p>
13805     *
13806     * <p>Note: in the current implementation, setting this property to true after the
13807     * view was added to a ViewGroup might have no effect at all. This property should
13808     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13809     *
13810     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13811     * property is enabled, an exception will be thrown.</p>
13812     *
13813     * <p>Note: if the child view uses and updates additional states which are unknown to the
13814     * parent, these states should not be affected by this method.</p>
13815     *
13816     * @param enabled True to enable duplication of the parent's drawable state, false
13817     *                to disable it.
13818     *
13819     * @see #getDrawableState()
13820     * @see #isDuplicateParentStateEnabled()
13821     */
13822    public void setDuplicateParentStateEnabled(boolean enabled) {
13823        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13824    }
13825
13826    /**
13827     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13828     *
13829     * @return True if this view's drawable state is duplicated from the parent,
13830     *         false otherwise
13831     *
13832     * @see #getDrawableState()
13833     * @see #setDuplicateParentStateEnabled(boolean)
13834     */
13835    public boolean isDuplicateParentStateEnabled() {
13836        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13837    }
13838
13839    /**
13840     * <p>Specifies the type of layer backing this view. The layer can be
13841     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13842     * {@link #LAYER_TYPE_HARDWARE}.</p>
13843     *
13844     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13845     * instance that controls how the layer is composed on screen. The following
13846     * properties of the paint are taken into account when composing the layer:</p>
13847     * <ul>
13848     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13849     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13850     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13851     * </ul>
13852     *
13853     * <p>If this view has an alpha value set to < 1.0 by calling
13854     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
13855     * by this view's alpha value.</p>
13856     *
13857     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13858     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13859     * for more information on when and how to use layers.</p>
13860     *
13861     * @param layerType The type of layer to use with this view, must be one of
13862     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13863     *        {@link #LAYER_TYPE_HARDWARE}
13864     * @param paint The paint used to compose the layer. This argument is optional
13865     *        and can be null. It is ignored when the layer type is
13866     *        {@link #LAYER_TYPE_NONE}
13867     *
13868     * @see #getLayerType()
13869     * @see #LAYER_TYPE_NONE
13870     * @see #LAYER_TYPE_SOFTWARE
13871     * @see #LAYER_TYPE_HARDWARE
13872     * @see #setAlpha(float)
13873     *
13874     * @attr ref android.R.styleable#View_layerType
13875     */
13876    public void setLayerType(int layerType, Paint paint) {
13877        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13878            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13879                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13880        }
13881
13882        boolean typeChanged = mRenderNode.setLayerType(layerType);
13883
13884        if (!typeChanged) {
13885            setLayerPaint(paint);
13886            return;
13887        }
13888
13889        // Destroy any previous software drawing cache if needed
13890        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13891            destroyDrawingCache();
13892        }
13893
13894        mLayerType = layerType;
13895        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13896        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13897        mRenderNode.setLayerPaint(mLayerPaint);
13898
13899        // draw() behaves differently if we are on a layer, so we need to
13900        // invalidate() here
13901        invalidateParentCaches();
13902        invalidate(true);
13903    }
13904
13905    /**
13906     * Updates the {@link Paint} object used with the current layer (used only if the current
13907     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13908     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13909     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13910     * ensure that the view gets redrawn immediately.
13911     *
13912     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13913     * instance that controls how the layer is composed on screen. The following
13914     * properties of the paint are taken into account when composing the layer:</p>
13915     * <ul>
13916     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13917     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13918     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13919     * </ul>
13920     *
13921     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13922     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
13923     *
13924     * @param paint The paint used to compose the layer. This argument is optional
13925     *        and can be null. It is ignored when the layer type is
13926     *        {@link #LAYER_TYPE_NONE}
13927     *
13928     * @see #setLayerType(int, android.graphics.Paint)
13929     */
13930    public void setLayerPaint(Paint paint) {
13931        int layerType = getLayerType();
13932        if (layerType != LAYER_TYPE_NONE) {
13933            mLayerPaint = paint == null ? new Paint() : paint;
13934            if (layerType == LAYER_TYPE_HARDWARE) {
13935                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13936                    invalidateViewProperty(false, false);
13937                }
13938            } else {
13939                invalidate();
13940            }
13941        }
13942    }
13943
13944    /**
13945     * Indicates whether this view has a static layer. A view with layer type
13946     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13947     * dynamic.
13948     */
13949    boolean hasStaticLayer() {
13950        return true;
13951    }
13952
13953    /**
13954     * Indicates what type of layer is currently associated with this view. By default
13955     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13956     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13957     * for more information on the different types of layers.
13958     *
13959     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13960     *         {@link #LAYER_TYPE_HARDWARE}
13961     *
13962     * @see #setLayerType(int, android.graphics.Paint)
13963     * @see #buildLayer()
13964     * @see #LAYER_TYPE_NONE
13965     * @see #LAYER_TYPE_SOFTWARE
13966     * @see #LAYER_TYPE_HARDWARE
13967     */
13968    public int getLayerType() {
13969        return mLayerType;
13970    }
13971
13972    /**
13973     * Forces this view's layer to be created and this view to be rendered
13974     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13975     * invoking this method will have no effect.
13976     *
13977     * This method can for instance be used to render a view into its layer before
13978     * starting an animation. If this view is complex, rendering into the layer
13979     * before starting the animation will avoid skipping frames.
13980     *
13981     * @throws IllegalStateException If this view is not attached to a window
13982     *
13983     * @see #setLayerType(int, android.graphics.Paint)
13984     */
13985    public void buildLayer() {
13986        if (mLayerType == LAYER_TYPE_NONE) return;
13987
13988        final AttachInfo attachInfo = mAttachInfo;
13989        if (attachInfo == null) {
13990            throw new IllegalStateException("This view must be attached to a window first");
13991        }
13992
13993        if (getWidth() == 0 || getHeight() == 0) {
13994            return;
13995        }
13996
13997        switch (mLayerType) {
13998            case LAYER_TYPE_HARDWARE:
13999                updateDisplayListIfDirty();
14000                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14001                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14002                }
14003                break;
14004            case LAYER_TYPE_SOFTWARE:
14005                buildDrawingCache(true);
14006                break;
14007        }
14008    }
14009
14010    /**
14011     * If this View draws with a HardwareLayer, returns it.
14012     * Otherwise returns null
14013     *
14014     * TODO: Only TextureView uses this, can we eliminate it?
14015     */
14016    HardwareLayer getHardwareLayer() {
14017        return null;
14018    }
14019
14020    /**
14021     * Destroys all hardware rendering resources. This method is invoked
14022     * when the system needs to reclaim resources. Upon execution of this
14023     * method, you should free any OpenGL resources created by the view.
14024     *
14025     * Note: you <strong>must</strong> call
14026     * <code>super.destroyHardwareResources()</code> when overriding
14027     * this method.
14028     *
14029     * @hide
14030     */
14031    protected void destroyHardwareResources() {
14032        // Although the Layer will be destroyed by RenderNode, we want to release
14033        // the staging display list, which is also a signal to RenderNode that it's
14034        // safe to free its copy of the display list as it knows that we will
14035        // push an updated DisplayList if we try to draw again
14036        resetDisplayList();
14037    }
14038
14039    /**
14040     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14041     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14042     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14043     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14044     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14045     * null.</p>
14046     *
14047     * <p>Enabling the drawing cache is similar to
14048     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14049     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14050     * drawing cache has no effect on rendering because the system uses a different mechanism
14051     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14052     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14053     * for information on how to enable software and hardware layers.</p>
14054     *
14055     * <p>This API can be used to manually generate
14056     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14057     * {@link #getDrawingCache()}.</p>
14058     *
14059     * @param enabled true to enable the drawing cache, false otherwise
14060     *
14061     * @see #isDrawingCacheEnabled()
14062     * @see #getDrawingCache()
14063     * @see #buildDrawingCache()
14064     * @see #setLayerType(int, android.graphics.Paint)
14065     */
14066    public void setDrawingCacheEnabled(boolean enabled) {
14067        mCachingFailed = false;
14068        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14069    }
14070
14071    /**
14072     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14073     *
14074     * @return true if the drawing cache is enabled
14075     *
14076     * @see #setDrawingCacheEnabled(boolean)
14077     * @see #getDrawingCache()
14078     */
14079    @ViewDebug.ExportedProperty(category = "drawing")
14080    public boolean isDrawingCacheEnabled() {
14081        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14082    }
14083
14084    /**
14085     * Debugging utility which recursively outputs the dirty state of a view and its
14086     * descendants.
14087     *
14088     * @hide
14089     */
14090    @SuppressWarnings({"UnusedDeclaration"})
14091    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14092        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14093                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14094                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14095                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14096        if (clear) {
14097            mPrivateFlags &= clearMask;
14098        }
14099        if (this instanceof ViewGroup) {
14100            ViewGroup parent = (ViewGroup) this;
14101            final int count = parent.getChildCount();
14102            for (int i = 0; i < count; i++) {
14103                final View child = parent.getChildAt(i);
14104                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14105            }
14106        }
14107    }
14108
14109    /**
14110     * This method is used by ViewGroup to cause its children to restore or recreate their
14111     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14112     * to recreate its own display list, which would happen if it went through the normal
14113     * draw/dispatchDraw mechanisms.
14114     *
14115     * @hide
14116     */
14117    protected void dispatchGetDisplayList() {}
14118
14119    /**
14120     * A view that is not attached or hardware accelerated cannot create a display list.
14121     * This method checks these conditions and returns the appropriate result.
14122     *
14123     * @return true if view has the ability to create a display list, false otherwise.
14124     *
14125     * @hide
14126     */
14127    public boolean canHaveDisplayList() {
14128        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14129    }
14130
14131    private void updateDisplayListIfDirty() {
14132        final RenderNode renderNode = mRenderNode;
14133        if (!canHaveDisplayList()) {
14134            // can't populate RenderNode, don't try
14135            return;
14136        }
14137
14138        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14139                || !renderNode.isValid()
14140                || (mRecreateDisplayList)) {
14141            // Don't need to recreate the display list, just need to tell our
14142            // children to restore/recreate theirs
14143            if (renderNode.isValid()
14144                    && !mRecreateDisplayList) {
14145                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14146                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14147                dispatchGetDisplayList();
14148
14149                return; // no work needed
14150            }
14151
14152            // If we got here, we're recreating it. Mark it as such to ensure that
14153            // we copy in child display lists into ours in drawChild()
14154            mRecreateDisplayList = true;
14155
14156            int width = mRight - mLeft;
14157            int height = mBottom - mTop;
14158            int layerType = getLayerType();
14159
14160            final HardwareCanvas canvas = renderNode.start(width, height);
14161            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14162
14163            try {
14164                final HardwareLayer layer = getHardwareLayer();
14165                if (layer != null && layer.isValid()) {
14166                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14167                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14168                    buildDrawingCache(true);
14169                    Bitmap cache = getDrawingCache(true);
14170                    if (cache != null) {
14171                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14172                    }
14173                } else {
14174                    computeScroll();
14175
14176                    canvas.translate(-mScrollX, -mScrollY);
14177                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14178                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14179
14180                    // Fast path for layouts with no backgrounds
14181                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14182                        dispatchDraw(canvas);
14183                        if (mOverlay != null && !mOverlay.isEmpty()) {
14184                            mOverlay.getOverlayView().draw(canvas);
14185                        }
14186                    } else {
14187                        draw(canvas);
14188                    }
14189                }
14190            } finally {
14191                renderNode.end(canvas);
14192                setDisplayListProperties(renderNode);
14193            }
14194        } else {
14195            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14196            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14197        }
14198    }
14199
14200    /**
14201     * Returns a RenderNode with View draw content recorded, which can be
14202     * used to draw this view again without executing its draw method.
14203     *
14204     * @return A RenderNode ready to replay, or null if caching is not enabled.
14205     *
14206     * @hide
14207     */
14208    public RenderNode getDisplayList() {
14209        updateDisplayListIfDirty();
14210        return mRenderNode;
14211    }
14212
14213    private void resetDisplayList() {
14214        if (mRenderNode.isValid()) {
14215            mRenderNode.destroyDisplayListData();
14216        }
14217
14218        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14219            mBackgroundRenderNode.destroyDisplayListData();
14220        }
14221    }
14222
14223    /**
14224     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14225     *
14226     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14227     *
14228     * @see #getDrawingCache(boolean)
14229     */
14230    public Bitmap getDrawingCache() {
14231        return getDrawingCache(false);
14232    }
14233
14234    /**
14235     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14236     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14237     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14238     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14239     * request the drawing cache by calling this method and draw it on screen if the
14240     * returned bitmap is not null.</p>
14241     *
14242     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14243     * this method will create a bitmap of the same size as this view. Because this bitmap
14244     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14245     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14246     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14247     * size than the view. This implies that your application must be able to handle this
14248     * size.</p>
14249     *
14250     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14251     *        the current density of the screen when the application is in compatibility
14252     *        mode.
14253     *
14254     * @return A bitmap representing this view or null if cache is disabled.
14255     *
14256     * @see #setDrawingCacheEnabled(boolean)
14257     * @see #isDrawingCacheEnabled()
14258     * @see #buildDrawingCache(boolean)
14259     * @see #destroyDrawingCache()
14260     */
14261    public Bitmap getDrawingCache(boolean autoScale) {
14262        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14263            return null;
14264        }
14265        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14266            buildDrawingCache(autoScale);
14267        }
14268        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14269    }
14270
14271    /**
14272     * <p>Frees the resources used by the drawing cache. If you call
14273     * {@link #buildDrawingCache()} manually without calling
14274     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14275     * should cleanup the cache with this method afterwards.</p>
14276     *
14277     * @see #setDrawingCacheEnabled(boolean)
14278     * @see #buildDrawingCache()
14279     * @see #getDrawingCache()
14280     */
14281    public void destroyDrawingCache() {
14282        if (mDrawingCache != null) {
14283            mDrawingCache.recycle();
14284            mDrawingCache = null;
14285        }
14286        if (mUnscaledDrawingCache != null) {
14287            mUnscaledDrawingCache.recycle();
14288            mUnscaledDrawingCache = null;
14289        }
14290    }
14291
14292    /**
14293     * Setting a solid background color for the drawing cache's bitmaps will improve
14294     * performance and memory usage. Note, though that this should only be used if this
14295     * view will always be drawn on top of a solid color.
14296     *
14297     * @param color The background color to use for the drawing cache's bitmap
14298     *
14299     * @see #setDrawingCacheEnabled(boolean)
14300     * @see #buildDrawingCache()
14301     * @see #getDrawingCache()
14302     */
14303    public void setDrawingCacheBackgroundColor(int color) {
14304        if (color != mDrawingCacheBackgroundColor) {
14305            mDrawingCacheBackgroundColor = color;
14306            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14307        }
14308    }
14309
14310    /**
14311     * @see #setDrawingCacheBackgroundColor(int)
14312     *
14313     * @return The background color to used for the drawing cache's bitmap
14314     */
14315    public int getDrawingCacheBackgroundColor() {
14316        return mDrawingCacheBackgroundColor;
14317    }
14318
14319    /**
14320     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14321     *
14322     * @see #buildDrawingCache(boolean)
14323     */
14324    public void buildDrawingCache() {
14325        buildDrawingCache(false);
14326    }
14327
14328    /**
14329     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14330     *
14331     * <p>If you call {@link #buildDrawingCache()} manually without calling
14332     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14333     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14334     *
14335     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14336     * this method will create a bitmap of the same size as this view. Because this bitmap
14337     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14338     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14339     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14340     * size than the view. This implies that your application must be able to handle this
14341     * size.</p>
14342     *
14343     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14344     * you do not need the drawing cache bitmap, calling this method will increase memory
14345     * usage and cause the view to be rendered in software once, thus negatively impacting
14346     * performance.</p>
14347     *
14348     * @see #getDrawingCache()
14349     * @see #destroyDrawingCache()
14350     */
14351    public void buildDrawingCache(boolean autoScale) {
14352        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14353                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14354            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14355                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14356                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14357            }
14358            try {
14359                buildDrawingCacheImpl(autoScale);
14360            } finally {
14361                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14362            }
14363        }
14364    }
14365
14366    /**
14367     * private, internal implementation of buildDrawingCache, used to enable tracing
14368     */
14369    private void buildDrawingCacheImpl(boolean autoScale) {
14370        mCachingFailed = false;
14371
14372        int width = mRight - mLeft;
14373        int height = mBottom - mTop;
14374
14375        final AttachInfo attachInfo = mAttachInfo;
14376        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14377
14378        if (autoScale && scalingRequired) {
14379            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14380            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14381        }
14382
14383        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14384        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14385        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14386
14387        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14388        final long drawingCacheSize =
14389                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14390        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14391            if (width > 0 && height > 0) {
14392                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14393                        + projectedBitmapSize + " bytes, only "
14394                        + drawingCacheSize + " available");
14395            }
14396            destroyDrawingCache();
14397            mCachingFailed = true;
14398            return;
14399        }
14400
14401        boolean clear = true;
14402        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14403
14404        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14405            Bitmap.Config quality;
14406            if (!opaque) {
14407                // Never pick ARGB_4444 because it looks awful
14408                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14409                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14410                    case DRAWING_CACHE_QUALITY_AUTO:
14411                    case DRAWING_CACHE_QUALITY_LOW:
14412                    case DRAWING_CACHE_QUALITY_HIGH:
14413                    default:
14414                        quality = Bitmap.Config.ARGB_8888;
14415                        break;
14416                }
14417            } else {
14418                // Optimization for translucent windows
14419                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14420                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14421            }
14422
14423            // Try to cleanup memory
14424            if (bitmap != null) bitmap.recycle();
14425
14426            try {
14427                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14428                        width, height, quality);
14429                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14430                if (autoScale) {
14431                    mDrawingCache = bitmap;
14432                } else {
14433                    mUnscaledDrawingCache = bitmap;
14434                }
14435                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14436            } catch (OutOfMemoryError e) {
14437                // If there is not enough memory to create the bitmap cache, just
14438                // ignore the issue as bitmap caches are not required to draw the
14439                // view hierarchy
14440                if (autoScale) {
14441                    mDrawingCache = null;
14442                } else {
14443                    mUnscaledDrawingCache = null;
14444                }
14445                mCachingFailed = true;
14446                return;
14447            }
14448
14449            clear = drawingCacheBackgroundColor != 0;
14450        }
14451
14452        Canvas canvas;
14453        if (attachInfo != null) {
14454            canvas = attachInfo.mCanvas;
14455            if (canvas == null) {
14456                canvas = new Canvas();
14457            }
14458            canvas.setBitmap(bitmap);
14459            // Temporarily clobber the cached Canvas in case one of our children
14460            // is also using a drawing cache. Without this, the children would
14461            // steal the canvas by attaching their own bitmap to it and bad, bad
14462            // thing would happen (invisible views, corrupted drawings, etc.)
14463            attachInfo.mCanvas = null;
14464        } else {
14465            // This case should hopefully never or seldom happen
14466            canvas = new Canvas(bitmap);
14467        }
14468
14469        if (clear) {
14470            bitmap.eraseColor(drawingCacheBackgroundColor);
14471        }
14472
14473        computeScroll();
14474        final int restoreCount = canvas.save();
14475
14476        if (autoScale && scalingRequired) {
14477            final float scale = attachInfo.mApplicationScale;
14478            canvas.scale(scale, scale);
14479        }
14480
14481        canvas.translate(-mScrollX, -mScrollY);
14482
14483        mPrivateFlags |= PFLAG_DRAWN;
14484        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14485                mLayerType != LAYER_TYPE_NONE) {
14486            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14487        }
14488
14489        // Fast path for layouts with no backgrounds
14490        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14491            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14492            dispatchDraw(canvas);
14493            if (mOverlay != null && !mOverlay.isEmpty()) {
14494                mOverlay.getOverlayView().draw(canvas);
14495            }
14496        } else {
14497            draw(canvas);
14498        }
14499
14500        canvas.restoreToCount(restoreCount);
14501        canvas.setBitmap(null);
14502
14503        if (attachInfo != null) {
14504            // Restore the cached Canvas for our siblings
14505            attachInfo.mCanvas = canvas;
14506        }
14507    }
14508
14509    /**
14510     * Create a snapshot of the view into a bitmap.  We should probably make
14511     * some form of this public, but should think about the API.
14512     */
14513    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14514        int width = mRight - mLeft;
14515        int height = mBottom - mTop;
14516
14517        final AttachInfo attachInfo = mAttachInfo;
14518        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14519        width = (int) ((width * scale) + 0.5f);
14520        height = (int) ((height * scale) + 0.5f);
14521
14522        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14523                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14524        if (bitmap == null) {
14525            throw new OutOfMemoryError();
14526        }
14527
14528        Resources resources = getResources();
14529        if (resources != null) {
14530            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14531        }
14532
14533        Canvas canvas;
14534        if (attachInfo != null) {
14535            canvas = attachInfo.mCanvas;
14536            if (canvas == null) {
14537                canvas = new Canvas();
14538            }
14539            canvas.setBitmap(bitmap);
14540            // Temporarily clobber the cached Canvas in case one of our children
14541            // is also using a drawing cache. Without this, the children would
14542            // steal the canvas by attaching their own bitmap to it and bad, bad
14543            // things would happen (invisible views, corrupted drawings, etc.)
14544            attachInfo.mCanvas = null;
14545        } else {
14546            // This case should hopefully never or seldom happen
14547            canvas = new Canvas(bitmap);
14548        }
14549
14550        if ((backgroundColor & 0xff000000) != 0) {
14551            bitmap.eraseColor(backgroundColor);
14552        }
14553
14554        computeScroll();
14555        final int restoreCount = canvas.save();
14556        canvas.scale(scale, scale);
14557        canvas.translate(-mScrollX, -mScrollY);
14558
14559        // Temporarily remove the dirty mask
14560        int flags = mPrivateFlags;
14561        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14562
14563        // Fast path for layouts with no backgrounds
14564        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14565            dispatchDraw(canvas);
14566            if (mOverlay != null && !mOverlay.isEmpty()) {
14567                mOverlay.getOverlayView().draw(canvas);
14568            }
14569        } else {
14570            draw(canvas);
14571        }
14572
14573        mPrivateFlags = flags;
14574
14575        canvas.restoreToCount(restoreCount);
14576        canvas.setBitmap(null);
14577
14578        if (attachInfo != null) {
14579            // Restore the cached Canvas for our siblings
14580            attachInfo.mCanvas = canvas;
14581        }
14582
14583        return bitmap;
14584    }
14585
14586    /**
14587     * Indicates whether this View is currently in edit mode. A View is usually
14588     * in edit mode when displayed within a developer tool. For instance, if
14589     * this View is being drawn by a visual user interface builder, this method
14590     * should return true.
14591     *
14592     * Subclasses should check the return value of this method to provide
14593     * different behaviors if their normal behavior might interfere with the
14594     * host environment. For instance: the class spawns a thread in its
14595     * constructor, the drawing code relies on device-specific features, etc.
14596     *
14597     * This method is usually checked in the drawing code of custom widgets.
14598     *
14599     * @return True if this View is in edit mode, false otherwise.
14600     */
14601    public boolean isInEditMode() {
14602        return false;
14603    }
14604
14605    /**
14606     * If the View draws content inside its padding and enables fading edges,
14607     * it needs to support padding offsets. Padding offsets are added to the
14608     * fading edges to extend the length of the fade so that it covers pixels
14609     * drawn inside the padding.
14610     *
14611     * Subclasses of this class should override this method if they need
14612     * to draw content inside the padding.
14613     *
14614     * @return True if padding offset must be applied, false otherwise.
14615     *
14616     * @see #getLeftPaddingOffset()
14617     * @see #getRightPaddingOffset()
14618     * @see #getTopPaddingOffset()
14619     * @see #getBottomPaddingOffset()
14620     *
14621     * @since CURRENT
14622     */
14623    protected boolean isPaddingOffsetRequired() {
14624        return false;
14625    }
14626
14627    /**
14628     * Amount by which to extend the left fading region. Called only when
14629     * {@link #isPaddingOffsetRequired()} returns true.
14630     *
14631     * @return The left padding offset in pixels.
14632     *
14633     * @see #isPaddingOffsetRequired()
14634     *
14635     * @since CURRENT
14636     */
14637    protected int getLeftPaddingOffset() {
14638        return 0;
14639    }
14640
14641    /**
14642     * Amount by which to extend the right fading region. Called only when
14643     * {@link #isPaddingOffsetRequired()} returns true.
14644     *
14645     * @return The right padding offset in pixels.
14646     *
14647     * @see #isPaddingOffsetRequired()
14648     *
14649     * @since CURRENT
14650     */
14651    protected int getRightPaddingOffset() {
14652        return 0;
14653    }
14654
14655    /**
14656     * Amount by which to extend the top fading region. Called only when
14657     * {@link #isPaddingOffsetRequired()} returns true.
14658     *
14659     * @return The top padding offset in pixels.
14660     *
14661     * @see #isPaddingOffsetRequired()
14662     *
14663     * @since CURRENT
14664     */
14665    protected int getTopPaddingOffset() {
14666        return 0;
14667    }
14668
14669    /**
14670     * Amount by which to extend the bottom fading region. Called only when
14671     * {@link #isPaddingOffsetRequired()} returns true.
14672     *
14673     * @return The bottom padding offset in pixels.
14674     *
14675     * @see #isPaddingOffsetRequired()
14676     *
14677     * @since CURRENT
14678     */
14679    protected int getBottomPaddingOffset() {
14680        return 0;
14681    }
14682
14683    /**
14684     * @hide
14685     * @param offsetRequired
14686     */
14687    protected int getFadeTop(boolean offsetRequired) {
14688        int top = mPaddingTop;
14689        if (offsetRequired) top += getTopPaddingOffset();
14690        return top;
14691    }
14692
14693    /**
14694     * @hide
14695     * @param offsetRequired
14696     */
14697    protected int getFadeHeight(boolean offsetRequired) {
14698        int padding = mPaddingTop;
14699        if (offsetRequired) padding += getTopPaddingOffset();
14700        return mBottom - mTop - mPaddingBottom - padding;
14701    }
14702
14703    /**
14704     * <p>Indicates whether this view is attached to a hardware accelerated
14705     * window or not.</p>
14706     *
14707     * <p>Even if this method returns true, it does not mean that every call
14708     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14709     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14710     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14711     * window is hardware accelerated,
14712     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14713     * return false, and this method will return true.</p>
14714     *
14715     * @return True if the view is attached to a window and the window is
14716     *         hardware accelerated; false in any other case.
14717     */
14718    @ViewDebug.ExportedProperty(category = "drawing")
14719    public boolean isHardwareAccelerated() {
14720        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14721    }
14722
14723    /**
14724     * Sets a rectangular area on this view to which the view will be clipped
14725     * when it is drawn. Setting the value to null will remove the clip bounds
14726     * and the view will draw normally, using its full bounds.
14727     *
14728     * @param clipBounds The rectangular area, in the local coordinates of
14729     * this view, to which future drawing operations will be clipped.
14730     */
14731    public void setClipBounds(Rect clipBounds) {
14732        if (clipBounds == mClipBounds
14733                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
14734            return;
14735        }
14736        if (clipBounds != null) {
14737            if (mClipBounds == null) {
14738                mClipBounds = new Rect(clipBounds);
14739            } else {
14740                mClipBounds.set(clipBounds);
14741            }
14742        } else {
14743            mClipBounds = null;
14744        }
14745        mRenderNode.setClipBounds(mClipBounds);
14746        invalidateViewProperty(false, false);
14747    }
14748
14749    /**
14750     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14751     *
14752     * @return A copy of the current clip bounds if clip bounds are set,
14753     * otherwise null.
14754     */
14755    public Rect getClipBounds() {
14756        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14757    }
14758
14759    /**
14760     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14761     * case of an active Animation being run on the view.
14762     */
14763    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14764            Animation a, boolean scalingRequired) {
14765        Transformation invalidationTransform;
14766        final int flags = parent.mGroupFlags;
14767        final boolean initialized = a.isInitialized();
14768        if (!initialized) {
14769            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14770            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14771            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14772            onAnimationStart();
14773        }
14774
14775        final Transformation t = parent.getChildTransformation();
14776        boolean more = a.getTransformation(drawingTime, t, 1f);
14777        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14778            if (parent.mInvalidationTransformation == null) {
14779                parent.mInvalidationTransformation = new Transformation();
14780            }
14781            invalidationTransform = parent.mInvalidationTransformation;
14782            a.getTransformation(drawingTime, invalidationTransform, 1f);
14783        } else {
14784            invalidationTransform = t;
14785        }
14786
14787        if (more) {
14788            if (!a.willChangeBounds()) {
14789                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14790                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14791                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14792                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14793                    // The child need to draw an animation, potentially offscreen, so
14794                    // make sure we do not cancel invalidate requests
14795                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14796                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14797                }
14798            } else {
14799                if (parent.mInvalidateRegion == null) {
14800                    parent.mInvalidateRegion = new RectF();
14801                }
14802                final RectF region = parent.mInvalidateRegion;
14803                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14804                        invalidationTransform);
14805
14806                // The child need to draw an animation, potentially offscreen, so
14807                // make sure we do not cancel invalidate requests
14808                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14809
14810                final int left = mLeft + (int) region.left;
14811                final int top = mTop + (int) region.top;
14812                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14813                        top + (int) (region.height() + .5f));
14814            }
14815        }
14816        return more;
14817    }
14818
14819    /**
14820     * This method is called by getDisplayList() when a display list is recorded for a View.
14821     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14822     */
14823    void setDisplayListProperties(RenderNode renderNode) {
14824        if (renderNode != null) {
14825            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14826            renderNode.setClipToBounds(mParent instanceof ViewGroup
14827                    && ((ViewGroup) mParent).getClipChildren());
14828
14829            float alpha = 1;
14830            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14831                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14832                ViewGroup parentVG = (ViewGroup) mParent;
14833                final Transformation t = parentVG.getChildTransformation();
14834                if (parentVG.getChildStaticTransformation(this, t)) {
14835                    final int transformType = t.getTransformationType();
14836                    if (transformType != Transformation.TYPE_IDENTITY) {
14837                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14838                            alpha = t.getAlpha();
14839                        }
14840                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14841                            renderNode.setStaticMatrix(t.getMatrix());
14842                        }
14843                    }
14844                }
14845            }
14846            if (mTransformationInfo != null) {
14847                alpha *= getFinalAlpha();
14848                if (alpha < 1) {
14849                    final int multipliedAlpha = (int) (255 * alpha);
14850                    if (onSetAlpha(multipliedAlpha)) {
14851                        alpha = 1;
14852                    }
14853                }
14854                renderNode.setAlpha(alpha);
14855            } else if (alpha < 1) {
14856                renderNode.setAlpha(alpha);
14857            }
14858        }
14859    }
14860
14861    /**
14862     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14863     * This draw() method is an implementation detail and is not intended to be overridden or
14864     * to be called from anywhere else other than ViewGroup.drawChild().
14865     */
14866    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14867        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14868        boolean more = false;
14869        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14870        final int flags = parent.mGroupFlags;
14871
14872        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14873            parent.getChildTransformation().clear();
14874            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14875        }
14876
14877        Transformation transformToApply = null;
14878        boolean concatMatrix = false;
14879
14880        boolean scalingRequired = false;
14881        boolean caching;
14882        int layerType = getLayerType();
14883
14884        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14885        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14886                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14887            caching = true;
14888            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14889            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14890        } else {
14891            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14892        }
14893
14894        final Animation a = getAnimation();
14895        if (a != null) {
14896            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14897            concatMatrix = a.willChangeTransformationMatrix();
14898            if (concatMatrix) {
14899                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14900            }
14901            transformToApply = parent.getChildTransformation();
14902        } else {
14903            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14904                // No longer animating: clear out old animation matrix
14905                mRenderNode.setAnimationMatrix(null);
14906                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14907            }
14908            if (!usingRenderNodeProperties &&
14909                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14910                final Transformation t = parent.getChildTransformation();
14911                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14912                if (hasTransform) {
14913                    final int transformType = t.getTransformationType();
14914                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14915                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14916                }
14917            }
14918        }
14919
14920        concatMatrix |= !childHasIdentityMatrix;
14921
14922        // Sets the flag as early as possible to allow draw() implementations
14923        // to call invalidate() successfully when doing animations
14924        mPrivateFlags |= PFLAG_DRAWN;
14925
14926        if (!concatMatrix &&
14927                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14928                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14929                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14930                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14931            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14932            return more;
14933        }
14934        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14935
14936        if (hardwareAccelerated) {
14937            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14938            // retain the flag's value temporarily in the mRecreateDisplayList flag
14939            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14940            mPrivateFlags &= ~PFLAG_INVALIDATED;
14941        }
14942
14943        RenderNode renderNode = null;
14944        Bitmap cache = null;
14945        boolean hasDisplayList = false;
14946        if (caching) {
14947            if (!hardwareAccelerated) {
14948                if (layerType != LAYER_TYPE_NONE) {
14949                    layerType = LAYER_TYPE_SOFTWARE;
14950                    buildDrawingCache(true);
14951                }
14952                cache = getDrawingCache(true);
14953            } else {
14954                switch (layerType) {
14955                    case LAYER_TYPE_SOFTWARE:
14956                        if (usingRenderNodeProperties) {
14957                            hasDisplayList = canHaveDisplayList();
14958                        } else {
14959                            buildDrawingCache(true);
14960                            cache = getDrawingCache(true);
14961                        }
14962                        break;
14963                    case LAYER_TYPE_HARDWARE:
14964                        if (usingRenderNodeProperties) {
14965                            hasDisplayList = canHaveDisplayList();
14966                        }
14967                        break;
14968                    case LAYER_TYPE_NONE:
14969                        // Delay getting the display list until animation-driven alpha values are
14970                        // set up and possibly passed on to the view
14971                        hasDisplayList = canHaveDisplayList();
14972                        break;
14973                }
14974            }
14975        }
14976        usingRenderNodeProperties &= hasDisplayList;
14977        if (usingRenderNodeProperties) {
14978            renderNode = getDisplayList();
14979            if (!renderNode.isValid()) {
14980                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14981                // to getDisplayList(), the display list will be marked invalid and we should not
14982                // try to use it again.
14983                renderNode = null;
14984                hasDisplayList = false;
14985                usingRenderNodeProperties = false;
14986            }
14987        }
14988
14989        int sx = 0;
14990        int sy = 0;
14991        if (!hasDisplayList) {
14992            computeScroll();
14993            sx = mScrollX;
14994            sy = mScrollY;
14995        }
14996
14997        final boolean hasNoCache = cache == null || hasDisplayList;
14998        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14999                layerType != LAYER_TYPE_HARDWARE;
15000
15001        int restoreTo = -1;
15002        if (!usingRenderNodeProperties || transformToApply != null) {
15003            restoreTo = canvas.save();
15004        }
15005        if (offsetForScroll) {
15006            canvas.translate(mLeft - sx, mTop - sy);
15007        } else {
15008            if (!usingRenderNodeProperties) {
15009                canvas.translate(mLeft, mTop);
15010            }
15011            if (scalingRequired) {
15012                if (usingRenderNodeProperties) {
15013                    // TODO: Might not need this if we put everything inside the DL
15014                    restoreTo = canvas.save();
15015                }
15016                // mAttachInfo cannot be null, otherwise scalingRequired == false
15017                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15018                canvas.scale(scale, scale);
15019            }
15020        }
15021
15022        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
15023        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
15024                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15025            if (transformToApply != null || !childHasIdentityMatrix) {
15026                int transX = 0;
15027                int transY = 0;
15028
15029                if (offsetForScroll) {
15030                    transX = -sx;
15031                    transY = -sy;
15032                }
15033
15034                if (transformToApply != null) {
15035                    if (concatMatrix) {
15036                        if (usingRenderNodeProperties) {
15037                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15038                        } else {
15039                            // Undo the scroll translation, apply the transformation matrix,
15040                            // then redo the scroll translate to get the correct result.
15041                            canvas.translate(-transX, -transY);
15042                            canvas.concat(transformToApply.getMatrix());
15043                            canvas.translate(transX, transY);
15044                        }
15045                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15046                    }
15047
15048                    float transformAlpha = transformToApply.getAlpha();
15049                    if (transformAlpha < 1) {
15050                        alpha *= transformAlpha;
15051                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15052                    }
15053                }
15054
15055                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
15056                    canvas.translate(-transX, -transY);
15057                    canvas.concat(getMatrix());
15058                    canvas.translate(transX, transY);
15059                }
15060            }
15061
15062            // Deal with alpha if it is or used to be <1
15063            if (alpha < 1 ||
15064                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15065                if (alpha < 1) {
15066                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15067                } else {
15068                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15069                }
15070                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15071                if (hasNoCache) {
15072                    final int multipliedAlpha = (int) (255 * alpha);
15073                    if (!onSetAlpha(multipliedAlpha)) {
15074                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15075                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
15076                                layerType != LAYER_TYPE_NONE) {
15077                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15078                        }
15079                        if (usingRenderNodeProperties) {
15080                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15081                        } else  if (layerType == LAYER_TYPE_NONE) {
15082                            final int scrollX = hasDisplayList ? 0 : sx;
15083                            final int scrollY = hasDisplayList ? 0 : sy;
15084                            canvas.saveLayerAlpha(scrollX, scrollY,
15085                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
15086                                    multipliedAlpha, layerFlags);
15087                        }
15088                    } else {
15089                        // Alpha is handled by the child directly, clobber the layer's alpha
15090                        mPrivateFlags |= PFLAG_ALPHA_SET;
15091                    }
15092                }
15093            }
15094        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15095            onSetAlpha(255);
15096            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15097        }
15098
15099        if (!usingRenderNodeProperties) {
15100            // apply clips directly, since RenderNode won't do it for this draw
15101            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
15102                    && cache == null) {
15103                if (offsetForScroll) {
15104                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
15105                } else {
15106                    if (!scalingRequired || cache == null) {
15107                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
15108                    } else {
15109                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15110                    }
15111                }
15112            }
15113
15114            if (mClipBounds != null) {
15115                // clip bounds ignore scroll
15116                canvas.clipRect(mClipBounds);
15117            }
15118        }
15119
15120
15121
15122        if (!usingRenderNodeProperties && hasDisplayList) {
15123            renderNode = getDisplayList();
15124            if (!renderNode.isValid()) {
15125                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15126                // to getDisplayList(), the display list will be marked invalid and we should not
15127                // try to use it again.
15128                renderNode = null;
15129                hasDisplayList = false;
15130            }
15131        }
15132
15133        if (hasNoCache) {
15134            boolean layerRendered = false;
15135            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
15136                final HardwareLayer layer = getHardwareLayer();
15137                if (layer != null && layer.isValid()) {
15138                    int restoreAlpha = mLayerPaint.getAlpha();
15139                    mLayerPaint.setAlpha((int) (alpha * 255));
15140                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15141                    mLayerPaint.setAlpha(restoreAlpha);
15142                    layerRendered = true;
15143                } else {
15144                    final int scrollX = hasDisplayList ? 0 : sx;
15145                    final int scrollY = hasDisplayList ? 0 : sy;
15146                    canvas.saveLayer(scrollX, scrollY,
15147                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
15148                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
15149                }
15150            }
15151
15152            if (!layerRendered) {
15153                if (!hasDisplayList) {
15154                    // Fast path for layouts with no backgrounds
15155                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15156                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15157                        dispatchDraw(canvas);
15158                    } else {
15159                        draw(canvas);
15160                    }
15161                } else {
15162                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15163                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, flags);
15164                }
15165            }
15166        } else if (cache != null) {
15167            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15168            Paint cachePaint;
15169            int restoreAlpha = 0;
15170
15171            if (layerType == LAYER_TYPE_NONE) {
15172                cachePaint = parent.mCachePaint;
15173                if (cachePaint == null) {
15174                    cachePaint = new Paint();
15175                    cachePaint.setDither(false);
15176                    parent.mCachePaint = cachePaint;
15177                }
15178            } else {
15179                cachePaint = mLayerPaint;
15180                restoreAlpha = mLayerPaint.getAlpha();
15181            }
15182            cachePaint.setAlpha((int) (alpha * 255));
15183            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15184            cachePaint.setAlpha(restoreAlpha);
15185        }
15186
15187        if (restoreTo >= 0) {
15188            canvas.restoreToCount(restoreTo);
15189        }
15190
15191        if (a != null && !more) {
15192            if (!hardwareAccelerated && !a.getFillAfter()) {
15193                onSetAlpha(255);
15194            }
15195            parent.finishAnimatingView(this, a);
15196        }
15197
15198        if (more && hardwareAccelerated) {
15199            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15200                // alpha animations should cause the child to recreate its display list
15201                invalidate(true);
15202            }
15203        }
15204
15205        mRecreateDisplayList = false;
15206
15207        return more;
15208    }
15209
15210    /**
15211     * Manually render this view (and all of its children) to the given Canvas.
15212     * The view must have already done a full layout before this function is
15213     * called.  When implementing a view, implement
15214     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15215     * If you do need to override this method, call the superclass version.
15216     *
15217     * @param canvas The Canvas to which the View is rendered.
15218     */
15219    public void draw(Canvas canvas) {
15220        final int privateFlags = mPrivateFlags;
15221        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15222                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15223        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15224
15225        /*
15226         * Draw traversal performs several drawing steps which must be executed
15227         * in the appropriate order:
15228         *
15229         *      1. Draw the background
15230         *      2. If necessary, save the canvas' layers to prepare for fading
15231         *      3. Draw view's content
15232         *      4. Draw children
15233         *      5. If necessary, draw the fading edges and restore layers
15234         *      6. Draw decorations (scrollbars for instance)
15235         */
15236
15237        // Step 1, draw the background, if needed
15238        int saveCount;
15239
15240        if (!dirtyOpaque) {
15241            drawBackground(canvas);
15242        }
15243
15244        // skip step 2 & 5 if possible (common case)
15245        final int viewFlags = mViewFlags;
15246        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15247        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15248        if (!verticalEdges && !horizontalEdges) {
15249            // Step 3, draw the content
15250            if (!dirtyOpaque) onDraw(canvas);
15251
15252            // Step 4, draw the children
15253            dispatchDraw(canvas);
15254
15255            // Step 6, draw decorations (scrollbars)
15256            onDrawScrollBars(canvas);
15257
15258            if (mOverlay != null && !mOverlay.isEmpty()) {
15259                mOverlay.getOverlayView().dispatchDraw(canvas);
15260            }
15261
15262            // we're done...
15263            return;
15264        }
15265
15266        /*
15267         * Here we do the full fledged routine...
15268         * (this is an uncommon case where speed matters less,
15269         * this is why we repeat some of the tests that have been
15270         * done above)
15271         */
15272
15273        boolean drawTop = false;
15274        boolean drawBottom = false;
15275        boolean drawLeft = false;
15276        boolean drawRight = false;
15277
15278        float topFadeStrength = 0.0f;
15279        float bottomFadeStrength = 0.0f;
15280        float leftFadeStrength = 0.0f;
15281        float rightFadeStrength = 0.0f;
15282
15283        // Step 2, save the canvas' layers
15284        int paddingLeft = mPaddingLeft;
15285
15286        final boolean offsetRequired = isPaddingOffsetRequired();
15287        if (offsetRequired) {
15288            paddingLeft += getLeftPaddingOffset();
15289        }
15290
15291        int left = mScrollX + paddingLeft;
15292        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15293        int top = mScrollY + getFadeTop(offsetRequired);
15294        int bottom = top + getFadeHeight(offsetRequired);
15295
15296        if (offsetRequired) {
15297            right += getRightPaddingOffset();
15298            bottom += getBottomPaddingOffset();
15299        }
15300
15301        final ScrollabilityCache scrollabilityCache = mScrollCache;
15302        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15303        int length = (int) fadeHeight;
15304
15305        // clip the fade length if top and bottom fades overlap
15306        // overlapping fades produce odd-looking artifacts
15307        if (verticalEdges && (top + length > bottom - length)) {
15308            length = (bottom - top) / 2;
15309        }
15310
15311        // also clip horizontal fades if necessary
15312        if (horizontalEdges && (left + length > right - length)) {
15313            length = (right - left) / 2;
15314        }
15315
15316        if (verticalEdges) {
15317            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15318            drawTop = topFadeStrength * fadeHeight > 1.0f;
15319            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15320            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15321        }
15322
15323        if (horizontalEdges) {
15324            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15325            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15326            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15327            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15328        }
15329
15330        saveCount = canvas.getSaveCount();
15331
15332        int solidColor = getSolidColor();
15333        if (solidColor == 0) {
15334            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15335
15336            if (drawTop) {
15337                canvas.saveLayer(left, top, right, top + length, null, flags);
15338            }
15339
15340            if (drawBottom) {
15341                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15342            }
15343
15344            if (drawLeft) {
15345                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15346            }
15347
15348            if (drawRight) {
15349                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15350            }
15351        } else {
15352            scrollabilityCache.setFadeColor(solidColor);
15353        }
15354
15355        // Step 3, draw the content
15356        if (!dirtyOpaque) onDraw(canvas);
15357
15358        // Step 4, draw the children
15359        dispatchDraw(canvas);
15360
15361        // Step 5, draw the fade effect and restore layers
15362        final Paint p = scrollabilityCache.paint;
15363        final Matrix matrix = scrollabilityCache.matrix;
15364        final Shader fade = scrollabilityCache.shader;
15365
15366        if (drawTop) {
15367            matrix.setScale(1, fadeHeight * topFadeStrength);
15368            matrix.postTranslate(left, top);
15369            fade.setLocalMatrix(matrix);
15370            p.setShader(fade);
15371            canvas.drawRect(left, top, right, top + length, p);
15372        }
15373
15374        if (drawBottom) {
15375            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15376            matrix.postRotate(180);
15377            matrix.postTranslate(left, bottom);
15378            fade.setLocalMatrix(matrix);
15379            p.setShader(fade);
15380            canvas.drawRect(left, bottom - length, right, bottom, p);
15381        }
15382
15383        if (drawLeft) {
15384            matrix.setScale(1, fadeHeight * leftFadeStrength);
15385            matrix.postRotate(-90);
15386            matrix.postTranslate(left, top);
15387            fade.setLocalMatrix(matrix);
15388            p.setShader(fade);
15389            canvas.drawRect(left, top, left + length, bottom, p);
15390        }
15391
15392        if (drawRight) {
15393            matrix.setScale(1, fadeHeight * rightFadeStrength);
15394            matrix.postRotate(90);
15395            matrix.postTranslate(right, top);
15396            fade.setLocalMatrix(matrix);
15397            p.setShader(fade);
15398            canvas.drawRect(right - length, top, right, bottom, p);
15399        }
15400
15401        canvas.restoreToCount(saveCount);
15402
15403        // Step 6, draw decorations (scrollbars)
15404        onDrawScrollBars(canvas);
15405
15406        if (mOverlay != null && !mOverlay.isEmpty()) {
15407            mOverlay.getOverlayView().dispatchDraw(canvas);
15408        }
15409    }
15410
15411    /**
15412     * Draws the background onto the specified canvas.
15413     *
15414     * @param canvas Canvas on which to draw the background
15415     */
15416    private void drawBackground(Canvas canvas) {
15417        final Drawable background = mBackground;
15418        if (background == null) {
15419            return;
15420        }
15421
15422        if (mBackgroundSizeChanged) {
15423            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15424            mBackgroundSizeChanged = false;
15425            rebuildOutline();
15426        }
15427
15428        // Attempt to use a display list if requested.
15429        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15430                && mAttachInfo.mHardwareRenderer != null) {
15431            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15432
15433            final RenderNode renderNode = mBackgroundRenderNode;
15434            if (renderNode != null && renderNode.isValid()) {
15435                setBackgroundRenderNodeProperties(renderNode);
15436                ((HardwareCanvas) canvas).drawRenderNode(renderNode);
15437                return;
15438            }
15439        }
15440
15441        final int scrollX = mScrollX;
15442        final int scrollY = mScrollY;
15443        if ((scrollX | scrollY) == 0) {
15444            background.draw(canvas);
15445        } else {
15446            canvas.translate(scrollX, scrollY);
15447            background.draw(canvas);
15448            canvas.translate(-scrollX, -scrollY);
15449        }
15450    }
15451
15452    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15453        renderNode.setTranslationX(mScrollX);
15454        renderNode.setTranslationY(mScrollY);
15455    }
15456
15457    /**
15458     * Creates a new display list or updates the existing display list for the
15459     * specified Drawable.
15460     *
15461     * @param drawable Drawable for which to create a display list
15462     * @param renderNode Existing RenderNode, or {@code null}
15463     * @return A valid display list for the specified drawable
15464     */
15465    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15466        if (renderNode == null) {
15467            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15468        }
15469
15470        final Rect bounds = drawable.getBounds();
15471        final int width = bounds.width();
15472        final int height = bounds.height();
15473        final HardwareCanvas canvas = renderNode.start(width, height);
15474
15475        // Reverse left/top translation done by drawable canvas, which will
15476        // instead be applied by rendernode's LTRB bounds below. This way, the
15477        // drawable's bounds match with its rendernode bounds and its content
15478        // will lie within those bounds in the rendernode tree.
15479        canvas.translate(-bounds.left, -bounds.top);
15480
15481        try {
15482            drawable.draw(canvas);
15483        } finally {
15484            renderNode.end(canvas);
15485        }
15486
15487        // Set up drawable properties that are view-independent.
15488        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15489        renderNode.setProjectBackwards(drawable.isProjected());
15490        renderNode.setProjectionReceiver(true);
15491        renderNode.setClipToBounds(false);
15492        return renderNode;
15493    }
15494
15495    /**
15496     * Returns the overlay for this view, creating it if it does not yet exist.
15497     * Adding drawables to the overlay will cause them to be displayed whenever
15498     * the view itself is redrawn. Objects in the overlay should be actively
15499     * managed: remove them when they should not be displayed anymore. The
15500     * overlay will always have the same size as its host view.
15501     *
15502     * <p>Note: Overlays do not currently work correctly with {@link
15503     * SurfaceView} or {@link TextureView}; contents in overlays for these
15504     * types of views may not display correctly.</p>
15505     *
15506     * @return The ViewOverlay object for this view.
15507     * @see ViewOverlay
15508     */
15509    public ViewOverlay getOverlay() {
15510        if (mOverlay == null) {
15511            mOverlay = new ViewOverlay(mContext, this);
15512        }
15513        return mOverlay;
15514    }
15515
15516    /**
15517     * Override this if your view is known to always be drawn on top of a solid color background,
15518     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15519     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15520     * should be set to 0xFF.
15521     *
15522     * @see #setVerticalFadingEdgeEnabled(boolean)
15523     * @see #setHorizontalFadingEdgeEnabled(boolean)
15524     *
15525     * @return The known solid color background for this view, or 0 if the color may vary
15526     */
15527    @ViewDebug.ExportedProperty(category = "drawing")
15528    public int getSolidColor() {
15529        return 0;
15530    }
15531
15532    /**
15533     * Build a human readable string representation of the specified view flags.
15534     *
15535     * @param flags the view flags to convert to a string
15536     * @return a String representing the supplied flags
15537     */
15538    private static String printFlags(int flags) {
15539        String output = "";
15540        int numFlags = 0;
15541        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15542            output += "TAKES_FOCUS";
15543            numFlags++;
15544        }
15545
15546        switch (flags & VISIBILITY_MASK) {
15547        case INVISIBLE:
15548            if (numFlags > 0) {
15549                output += " ";
15550            }
15551            output += "INVISIBLE";
15552            // USELESS HERE numFlags++;
15553            break;
15554        case GONE:
15555            if (numFlags > 0) {
15556                output += " ";
15557            }
15558            output += "GONE";
15559            // USELESS HERE numFlags++;
15560            break;
15561        default:
15562            break;
15563        }
15564        return output;
15565    }
15566
15567    /**
15568     * Build a human readable string representation of the specified private
15569     * view flags.
15570     *
15571     * @param privateFlags the private view flags to convert to a string
15572     * @return a String representing the supplied flags
15573     */
15574    private static String printPrivateFlags(int privateFlags) {
15575        String output = "";
15576        int numFlags = 0;
15577
15578        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15579            output += "WANTS_FOCUS";
15580            numFlags++;
15581        }
15582
15583        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15584            if (numFlags > 0) {
15585                output += " ";
15586            }
15587            output += "FOCUSED";
15588            numFlags++;
15589        }
15590
15591        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15592            if (numFlags > 0) {
15593                output += " ";
15594            }
15595            output += "SELECTED";
15596            numFlags++;
15597        }
15598
15599        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15600            if (numFlags > 0) {
15601                output += " ";
15602            }
15603            output += "IS_ROOT_NAMESPACE";
15604            numFlags++;
15605        }
15606
15607        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15608            if (numFlags > 0) {
15609                output += " ";
15610            }
15611            output += "HAS_BOUNDS";
15612            numFlags++;
15613        }
15614
15615        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15616            if (numFlags > 0) {
15617                output += " ";
15618            }
15619            output += "DRAWN";
15620            // USELESS HERE numFlags++;
15621        }
15622        return output;
15623    }
15624
15625    /**
15626     * <p>Indicates whether or not this view's layout will be requested during
15627     * the next hierarchy layout pass.</p>
15628     *
15629     * @return true if the layout will be forced during next layout pass
15630     */
15631    public boolean isLayoutRequested() {
15632        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15633    }
15634
15635    /**
15636     * Return true if o is a ViewGroup that is laying out using optical bounds.
15637     * @hide
15638     */
15639    public static boolean isLayoutModeOptical(Object o) {
15640        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15641    }
15642
15643    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15644        Insets parentInsets = mParent instanceof View ?
15645                ((View) mParent).getOpticalInsets() : Insets.NONE;
15646        Insets childInsets = getOpticalInsets();
15647        return setFrame(
15648                left   + parentInsets.left - childInsets.left,
15649                top    + parentInsets.top  - childInsets.top,
15650                right  + parentInsets.left + childInsets.right,
15651                bottom + parentInsets.top  + childInsets.bottom);
15652    }
15653
15654    /**
15655     * Assign a size and position to a view and all of its
15656     * descendants
15657     *
15658     * <p>This is the second phase of the layout mechanism.
15659     * (The first is measuring). In this phase, each parent calls
15660     * layout on all of its children to position them.
15661     * This is typically done using the child measurements
15662     * that were stored in the measure pass().</p>
15663     *
15664     * <p>Derived classes should not override this method.
15665     * Derived classes with children should override
15666     * onLayout. In that method, they should
15667     * call layout on each of their children.</p>
15668     *
15669     * @param l Left position, relative to parent
15670     * @param t Top position, relative to parent
15671     * @param r Right position, relative to parent
15672     * @param b Bottom position, relative to parent
15673     */
15674    @SuppressWarnings({"unchecked"})
15675    public void layout(int l, int t, int r, int b) {
15676        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15677            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15678            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15679        }
15680
15681        int oldL = mLeft;
15682        int oldT = mTop;
15683        int oldB = mBottom;
15684        int oldR = mRight;
15685
15686        boolean changed = isLayoutModeOptical(mParent) ?
15687                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15688
15689        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15690            onLayout(changed, l, t, r, b);
15691            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15692
15693            ListenerInfo li = mListenerInfo;
15694            if (li != null && li.mOnLayoutChangeListeners != null) {
15695                ArrayList<OnLayoutChangeListener> listenersCopy =
15696                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15697                int numListeners = listenersCopy.size();
15698                for (int i = 0; i < numListeners; ++i) {
15699                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15700                }
15701            }
15702        }
15703
15704        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15705        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15706    }
15707
15708    /**
15709     * Called from layout when this view should
15710     * assign a size and position to each of its children.
15711     *
15712     * Derived classes with children should override
15713     * this method and call layout on each of
15714     * their children.
15715     * @param changed This is a new size or position for this view
15716     * @param left Left position, relative to parent
15717     * @param top Top position, relative to parent
15718     * @param right Right position, relative to parent
15719     * @param bottom Bottom position, relative to parent
15720     */
15721    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15722    }
15723
15724    /**
15725     * Assign a size and position to this view.
15726     *
15727     * This is called from layout.
15728     *
15729     * @param left Left position, relative to parent
15730     * @param top Top position, relative to parent
15731     * @param right Right position, relative to parent
15732     * @param bottom Bottom position, relative to parent
15733     * @return true if the new size and position are different than the
15734     *         previous ones
15735     * {@hide}
15736     */
15737    protected boolean setFrame(int left, int top, int right, int bottom) {
15738        boolean changed = false;
15739
15740        if (DBG) {
15741            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15742                    + right + "," + bottom + ")");
15743        }
15744
15745        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15746            changed = true;
15747
15748            // Remember our drawn bit
15749            int drawn = mPrivateFlags & PFLAG_DRAWN;
15750
15751            int oldWidth = mRight - mLeft;
15752            int oldHeight = mBottom - mTop;
15753            int newWidth = right - left;
15754            int newHeight = bottom - top;
15755            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15756
15757            // Invalidate our old position
15758            invalidate(sizeChanged);
15759
15760            mLeft = left;
15761            mTop = top;
15762            mRight = right;
15763            mBottom = bottom;
15764            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15765
15766            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15767
15768
15769            if (sizeChanged) {
15770                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15771            }
15772
15773            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
15774                // If we are visible, force the DRAWN bit to on so that
15775                // this invalidate will go through (at least to our parent).
15776                // This is because someone may have invalidated this view
15777                // before this call to setFrame came in, thereby clearing
15778                // the DRAWN bit.
15779                mPrivateFlags |= PFLAG_DRAWN;
15780                invalidate(sizeChanged);
15781                // parent display list may need to be recreated based on a change in the bounds
15782                // of any child
15783                invalidateParentCaches();
15784            }
15785
15786            // Reset drawn bit to original value (invalidate turns it off)
15787            mPrivateFlags |= drawn;
15788
15789            mBackgroundSizeChanged = true;
15790
15791            notifySubtreeAccessibilityStateChangedIfNeeded();
15792        }
15793        return changed;
15794    }
15795
15796    /**
15797     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
15798     * @hide
15799     */
15800    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
15801        setFrame(left, top, right, bottom);
15802    }
15803
15804    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15805        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15806        if (mOverlay != null) {
15807            mOverlay.getOverlayView().setRight(newWidth);
15808            mOverlay.getOverlayView().setBottom(newHeight);
15809        }
15810        rebuildOutline();
15811    }
15812
15813    /**
15814     * Finalize inflating a view from XML.  This is called as the last phase
15815     * of inflation, after all child views have been added.
15816     *
15817     * <p>Even if the subclass overrides onFinishInflate, they should always be
15818     * sure to call the super method, so that we get called.
15819     */
15820    protected void onFinishInflate() {
15821    }
15822
15823    /**
15824     * Returns the resources associated with this view.
15825     *
15826     * @return Resources object.
15827     */
15828    public Resources getResources() {
15829        return mResources;
15830    }
15831
15832    /**
15833     * Invalidates the specified Drawable.
15834     *
15835     * @param drawable the drawable to invalidate
15836     */
15837    @Override
15838    public void invalidateDrawable(@NonNull Drawable drawable) {
15839        if (verifyDrawable(drawable)) {
15840            final Rect dirty = drawable.getDirtyBounds();
15841            final int scrollX = mScrollX;
15842            final int scrollY = mScrollY;
15843
15844            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15845                    dirty.right + scrollX, dirty.bottom + scrollY);
15846            rebuildOutline();
15847        }
15848    }
15849
15850    /**
15851     * Schedules an action on a drawable to occur at a specified time.
15852     *
15853     * @param who the recipient of the action
15854     * @param what the action to run on the drawable
15855     * @param when the time at which the action must occur. Uses the
15856     *        {@link SystemClock#uptimeMillis} timebase.
15857     */
15858    @Override
15859    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15860        if (verifyDrawable(who) && what != null) {
15861            final long delay = when - SystemClock.uptimeMillis();
15862            if (mAttachInfo != null) {
15863                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15864                        Choreographer.CALLBACK_ANIMATION, what, who,
15865                        Choreographer.subtractFrameDelay(delay));
15866            } else {
15867                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15868            }
15869        }
15870    }
15871
15872    /**
15873     * Cancels a scheduled action on a drawable.
15874     *
15875     * @param who the recipient of the action
15876     * @param what the action to cancel
15877     */
15878    @Override
15879    public void unscheduleDrawable(Drawable who, Runnable what) {
15880        if (verifyDrawable(who) && what != null) {
15881            if (mAttachInfo != null) {
15882                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15883                        Choreographer.CALLBACK_ANIMATION, what, who);
15884            }
15885            ViewRootImpl.getRunQueue().removeCallbacks(what);
15886        }
15887    }
15888
15889    /**
15890     * Unschedule any events associated with the given Drawable.  This can be
15891     * used when selecting a new Drawable into a view, so that the previous
15892     * one is completely unscheduled.
15893     *
15894     * @param who The Drawable to unschedule.
15895     *
15896     * @see #drawableStateChanged
15897     */
15898    public void unscheduleDrawable(Drawable who) {
15899        if (mAttachInfo != null && who != null) {
15900            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15901                    Choreographer.CALLBACK_ANIMATION, null, who);
15902        }
15903    }
15904
15905    /**
15906     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15907     * that the View directionality can and will be resolved before its Drawables.
15908     *
15909     * Will call {@link View#onResolveDrawables} when resolution is done.
15910     *
15911     * @hide
15912     */
15913    protected void resolveDrawables() {
15914        // Drawables resolution may need to happen before resolving the layout direction (which is
15915        // done only during the measure() call).
15916        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15917        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15918        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15919        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15920        // direction to be resolved as its resolved value will be the same as its raw value.
15921        if (!isLayoutDirectionResolved() &&
15922                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15923            return;
15924        }
15925
15926        final int layoutDirection = isLayoutDirectionResolved() ?
15927                getLayoutDirection() : getRawLayoutDirection();
15928
15929        if (mBackground != null) {
15930            mBackground.setLayoutDirection(layoutDirection);
15931        }
15932        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15933        onResolveDrawables(layoutDirection);
15934    }
15935
15936    boolean areDrawablesResolved() {
15937        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15938    }
15939
15940    /**
15941     * Called when layout direction has been resolved.
15942     *
15943     * The default implementation does nothing.
15944     *
15945     * @param layoutDirection The resolved layout direction.
15946     *
15947     * @see #LAYOUT_DIRECTION_LTR
15948     * @see #LAYOUT_DIRECTION_RTL
15949     *
15950     * @hide
15951     */
15952    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15953    }
15954
15955    /**
15956     * @hide
15957     */
15958    protected void resetResolvedDrawables() {
15959        resetResolvedDrawablesInternal();
15960    }
15961
15962    void resetResolvedDrawablesInternal() {
15963        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15964    }
15965
15966    /**
15967     * If your view subclass is displaying its own Drawable objects, it should
15968     * override this function and return true for any Drawable it is
15969     * displaying.  This allows animations for those drawables to be
15970     * scheduled.
15971     *
15972     * <p>Be sure to call through to the super class when overriding this
15973     * function.
15974     *
15975     * @param who The Drawable to verify.  Return true if it is one you are
15976     *            displaying, else return the result of calling through to the
15977     *            super class.
15978     *
15979     * @return boolean If true than the Drawable is being displayed in the
15980     *         view; else false and it is not allowed to animate.
15981     *
15982     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15983     * @see #drawableStateChanged()
15984     */
15985    protected boolean verifyDrawable(Drawable who) {
15986        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who);
15987    }
15988
15989    /**
15990     * This function is called whenever the state of the view changes in such
15991     * a way that it impacts the state of drawables being shown.
15992     * <p>
15993     * If the View has a StateListAnimator, it will also be called to run necessary state
15994     * change animations.
15995     * <p>
15996     * Be sure to call through to the superclass when overriding this function.
15997     *
15998     * @see Drawable#setState(int[])
15999     */
16000    protected void drawableStateChanged() {
16001        final int[] state = getDrawableState();
16002
16003        final Drawable d = mBackground;
16004        if (d != null && d.isStateful()) {
16005            d.setState(state);
16006        }
16007
16008        if (mScrollCache != null) {
16009            final Drawable scrollBar = mScrollCache.scrollBar;
16010            if (scrollBar != null && scrollBar.isStateful()) {
16011                scrollBar.setState(state);
16012            }
16013        }
16014
16015        if (mStateListAnimator != null) {
16016            mStateListAnimator.setState(state);
16017        }
16018    }
16019
16020    /**
16021     * This function is called whenever the view hotspot changes and needs to
16022     * be propagated to drawables or child views managed by the view.
16023     * <p>
16024     * Dispatching to child views is handled by
16025     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16026     * <p>
16027     * Be sure to call through to the superclass when overriding this function.
16028     *
16029     * @param x hotspot x coordinate
16030     * @param y hotspot y coordinate
16031     */
16032    public void drawableHotspotChanged(float x, float y) {
16033        if (mBackground != null) {
16034            mBackground.setHotspot(x, y);
16035        }
16036
16037        dispatchDrawableHotspotChanged(x, y);
16038    }
16039
16040    /**
16041     * Dispatches drawableHotspotChanged to all of this View's children.
16042     *
16043     * @param x hotspot x coordinate
16044     * @param y hotspot y coordinate
16045     * @see #drawableHotspotChanged(float, float)
16046     */
16047    public void dispatchDrawableHotspotChanged(float x, float y) {
16048    }
16049
16050    /**
16051     * Call this to force a view to update its drawable state. This will cause
16052     * drawableStateChanged to be called on this view. Views that are interested
16053     * in the new state should call getDrawableState.
16054     *
16055     * @see #drawableStateChanged
16056     * @see #getDrawableState
16057     */
16058    public void refreshDrawableState() {
16059        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16060        drawableStateChanged();
16061
16062        ViewParent parent = mParent;
16063        if (parent != null) {
16064            parent.childDrawableStateChanged(this);
16065        }
16066    }
16067
16068    /**
16069     * Return an array of resource IDs of the drawable states representing the
16070     * current state of the view.
16071     *
16072     * @return The current drawable state
16073     *
16074     * @see Drawable#setState(int[])
16075     * @see #drawableStateChanged()
16076     * @see #onCreateDrawableState(int)
16077     */
16078    public final int[] getDrawableState() {
16079        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16080            return mDrawableState;
16081        } else {
16082            mDrawableState = onCreateDrawableState(0);
16083            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16084            return mDrawableState;
16085        }
16086    }
16087
16088    /**
16089     * Generate the new {@link android.graphics.drawable.Drawable} state for
16090     * this view. This is called by the view
16091     * system when the cached Drawable state is determined to be invalid.  To
16092     * retrieve the current state, you should use {@link #getDrawableState}.
16093     *
16094     * @param extraSpace if non-zero, this is the number of extra entries you
16095     * would like in the returned array in which you can place your own
16096     * states.
16097     *
16098     * @return Returns an array holding the current {@link Drawable} state of
16099     * the view.
16100     *
16101     * @see #mergeDrawableStates(int[], int[])
16102     */
16103    protected int[] onCreateDrawableState(int extraSpace) {
16104        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16105                mParent instanceof View) {
16106            return ((View) mParent).onCreateDrawableState(extraSpace);
16107        }
16108
16109        int[] drawableState;
16110
16111        int privateFlags = mPrivateFlags;
16112
16113        int viewStateIndex = 0;
16114        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16115        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16116        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16117        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16118        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16119        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16120        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16121                HardwareRenderer.isAvailable()) {
16122            // This is set if HW acceleration is requested, even if the current
16123            // process doesn't allow it.  This is just to allow app preview
16124            // windows to better match their app.
16125            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16126        }
16127        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16128
16129        final int privateFlags2 = mPrivateFlags2;
16130        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16131            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16132        }
16133        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16134            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16135        }
16136
16137        drawableState = StateSet.get(viewStateIndex);
16138
16139        //noinspection ConstantIfStatement
16140        if (false) {
16141            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16142            Log.i("View", toString()
16143                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16144                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16145                    + " fo=" + hasFocus()
16146                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16147                    + " wf=" + hasWindowFocus()
16148                    + ": " + Arrays.toString(drawableState));
16149        }
16150
16151        if (extraSpace == 0) {
16152            return drawableState;
16153        }
16154
16155        final int[] fullState;
16156        if (drawableState != null) {
16157            fullState = new int[drawableState.length + extraSpace];
16158            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16159        } else {
16160            fullState = new int[extraSpace];
16161        }
16162
16163        return fullState;
16164    }
16165
16166    /**
16167     * Merge your own state values in <var>additionalState</var> into the base
16168     * state values <var>baseState</var> that were returned by
16169     * {@link #onCreateDrawableState(int)}.
16170     *
16171     * @param baseState The base state values returned by
16172     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16173     * own additional state values.
16174     *
16175     * @param additionalState The additional state values you would like
16176     * added to <var>baseState</var>; this array is not modified.
16177     *
16178     * @return As a convenience, the <var>baseState</var> array you originally
16179     * passed into the function is returned.
16180     *
16181     * @see #onCreateDrawableState(int)
16182     */
16183    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16184        final int N = baseState.length;
16185        int i = N - 1;
16186        while (i >= 0 && baseState[i] == 0) {
16187            i--;
16188        }
16189        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16190        return baseState;
16191    }
16192
16193    /**
16194     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16195     * on all Drawable objects associated with this view.
16196     * <p>
16197     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16198     * attached to this view.
16199     */
16200    public void jumpDrawablesToCurrentState() {
16201        if (mBackground != null) {
16202            mBackground.jumpToCurrentState();
16203        }
16204        if (mStateListAnimator != null) {
16205            mStateListAnimator.jumpToCurrentState();
16206        }
16207    }
16208
16209    /**
16210     * Sets the background color for this view.
16211     * @param color the color of the background
16212     */
16213    @RemotableViewMethod
16214    public void setBackgroundColor(int color) {
16215        if (mBackground instanceof ColorDrawable) {
16216            ((ColorDrawable) mBackground.mutate()).setColor(color);
16217            computeOpaqueFlags();
16218            mBackgroundResource = 0;
16219        } else {
16220            setBackground(new ColorDrawable(color));
16221        }
16222    }
16223
16224    /**
16225     * If the view has a ColorDrawable background, returns the color of that
16226     * drawable.
16227     *
16228     * @return The color of the ColorDrawable background, if set, otherwise 0.
16229     */
16230    public int getBackgroundColor() {
16231        if (mBackground instanceof ColorDrawable) {
16232            return ((ColorDrawable) mBackground).getColor();
16233        }
16234        return 0;
16235    }
16236
16237    /**
16238     * Set the background to a given resource. The resource should refer to
16239     * a Drawable object or 0 to remove the background.
16240     * @param resid The identifier of the resource.
16241     *
16242     * @attr ref android.R.styleable#View_background
16243     */
16244    @RemotableViewMethod
16245    public void setBackgroundResource(int resid) {
16246        if (resid != 0 && resid == mBackgroundResource) {
16247            return;
16248        }
16249
16250        Drawable d = null;
16251        if (resid != 0) {
16252            d = mContext.getDrawable(resid);
16253        }
16254        setBackground(d);
16255
16256        mBackgroundResource = resid;
16257    }
16258
16259    /**
16260     * Set the background to a given Drawable, or remove the background. If the
16261     * background has padding, this View's padding is set to the background's
16262     * padding. However, when a background is removed, this View's padding isn't
16263     * touched. If setting the padding is desired, please use
16264     * {@link #setPadding(int, int, int, int)}.
16265     *
16266     * @param background The Drawable to use as the background, or null to remove the
16267     *        background
16268     */
16269    public void setBackground(Drawable background) {
16270        //noinspection deprecation
16271        setBackgroundDrawable(background);
16272    }
16273
16274    /**
16275     * @deprecated use {@link #setBackground(Drawable)} instead
16276     */
16277    @Deprecated
16278    public void setBackgroundDrawable(Drawable background) {
16279        computeOpaqueFlags();
16280
16281        if (background == mBackground) {
16282            return;
16283        }
16284
16285        boolean requestLayout = false;
16286
16287        mBackgroundResource = 0;
16288
16289        /*
16290         * Regardless of whether we're setting a new background or not, we want
16291         * to clear the previous drawable.
16292         */
16293        if (mBackground != null) {
16294            mBackground.setCallback(null);
16295            unscheduleDrawable(mBackground);
16296        }
16297
16298        if (background != null) {
16299            Rect padding = sThreadLocal.get();
16300            if (padding == null) {
16301                padding = new Rect();
16302                sThreadLocal.set(padding);
16303            }
16304            resetResolvedDrawablesInternal();
16305            background.setLayoutDirection(getLayoutDirection());
16306            if (background.getPadding(padding)) {
16307                resetResolvedPaddingInternal();
16308                switch (background.getLayoutDirection()) {
16309                    case LAYOUT_DIRECTION_RTL:
16310                        mUserPaddingLeftInitial = padding.right;
16311                        mUserPaddingRightInitial = padding.left;
16312                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16313                        break;
16314                    case LAYOUT_DIRECTION_LTR:
16315                    default:
16316                        mUserPaddingLeftInitial = padding.left;
16317                        mUserPaddingRightInitial = padding.right;
16318                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16319                }
16320                mLeftPaddingDefined = false;
16321                mRightPaddingDefined = false;
16322            }
16323
16324            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16325            // if it has a different minimum size, we should layout again
16326            if (mBackground == null
16327                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16328                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16329                requestLayout = true;
16330            }
16331
16332            background.setCallback(this);
16333            if (background.isStateful()) {
16334                background.setState(getDrawableState());
16335            }
16336            background.setVisible(getVisibility() == VISIBLE, false);
16337            mBackground = background;
16338
16339            applyBackgroundTint();
16340
16341            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16342                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16343                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16344                requestLayout = true;
16345            }
16346        } else {
16347            /* Remove the background */
16348            mBackground = null;
16349
16350            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16351                /*
16352                 * This view ONLY drew the background before and we're removing
16353                 * the background, so now it won't draw anything
16354                 * (hence we SKIP_DRAW)
16355                 */
16356                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16357                mPrivateFlags |= PFLAG_SKIP_DRAW;
16358            }
16359
16360            /*
16361             * When the background is set, we try to apply its padding to this
16362             * View. When the background is removed, we don't touch this View's
16363             * padding. This is noted in the Javadocs. Hence, we don't need to
16364             * requestLayout(), the invalidate() below is sufficient.
16365             */
16366
16367            // The old background's minimum size could have affected this
16368            // View's layout, so let's requestLayout
16369            requestLayout = true;
16370        }
16371
16372        computeOpaqueFlags();
16373
16374        if (requestLayout) {
16375            requestLayout();
16376        }
16377
16378        mBackgroundSizeChanged = true;
16379        invalidate(true);
16380    }
16381
16382    /**
16383     * Gets the background drawable
16384     *
16385     * @return The drawable used as the background for this view, if any.
16386     *
16387     * @see #setBackground(Drawable)
16388     *
16389     * @attr ref android.R.styleable#View_background
16390     */
16391    public Drawable getBackground() {
16392        return mBackground;
16393    }
16394
16395    /**
16396     * Applies a tint to the background drawable. Does not modify the current tint
16397     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16398     * <p>
16399     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16400     * mutate the drawable and apply the specified tint and tint mode using
16401     * {@link Drawable#setTintList(ColorStateList)}.
16402     *
16403     * @param tint the tint to apply, may be {@code null} to clear tint
16404     *
16405     * @attr ref android.R.styleable#View_backgroundTint
16406     * @see #getBackgroundTintList()
16407     * @see Drawable#setTintList(ColorStateList)
16408     */
16409    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16410        if (mBackgroundTint == null) {
16411            mBackgroundTint = new TintInfo();
16412        }
16413        mBackgroundTint.mTintList = tint;
16414        mBackgroundTint.mHasTintList = true;
16415
16416        applyBackgroundTint();
16417    }
16418
16419    /**
16420     * Return the tint applied to the background drawable, if specified.
16421     *
16422     * @return the tint applied to the background drawable
16423     * @attr ref android.R.styleable#View_backgroundTint
16424     * @see #setBackgroundTintList(ColorStateList)
16425     */
16426    @Nullable
16427    public ColorStateList getBackgroundTintList() {
16428        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16429    }
16430
16431    /**
16432     * Specifies the blending mode used to apply the tint specified by
16433     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16434     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16435     *
16436     * @param tintMode the blending mode used to apply the tint, may be
16437     *                 {@code null} to clear tint
16438     * @attr ref android.R.styleable#View_backgroundTintMode
16439     * @see #getBackgroundTintMode()
16440     * @see Drawable#setTintMode(PorterDuff.Mode)
16441     */
16442    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16443        if (mBackgroundTint == null) {
16444            mBackgroundTint = new TintInfo();
16445        }
16446        mBackgroundTint.mTintMode = tintMode;
16447        mBackgroundTint.mHasTintMode = true;
16448
16449        applyBackgroundTint();
16450    }
16451
16452    /**
16453     * Return the blending mode used to apply the tint to the background
16454     * drawable, if specified.
16455     *
16456     * @return the blending mode used to apply the tint to the background
16457     *         drawable
16458     * @attr ref android.R.styleable#View_backgroundTintMode
16459     * @see #setBackgroundTintMode(PorterDuff.Mode)
16460     */
16461    @Nullable
16462    public PorterDuff.Mode getBackgroundTintMode() {
16463        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16464    }
16465
16466    private void applyBackgroundTint() {
16467        if (mBackground != null && mBackgroundTint != null) {
16468            final TintInfo tintInfo = mBackgroundTint;
16469            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16470                mBackground = mBackground.mutate();
16471
16472                if (tintInfo.mHasTintList) {
16473                    mBackground.setTintList(tintInfo.mTintList);
16474                }
16475
16476                if (tintInfo.mHasTintMode) {
16477                    mBackground.setTintMode(tintInfo.mTintMode);
16478                }
16479
16480                // The drawable (or one of its children) may not have been
16481                // stateful before applying the tint, so let's try again.
16482                if (mBackground.isStateful()) {
16483                    mBackground.setState(getDrawableState());
16484                }
16485            }
16486        }
16487    }
16488
16489    /**
16490     * Sets the padding. The view may add on the space required to display
16491     * the scrollbars, depending on the style and visibility of the scrollbars.
16492     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16493     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16494     * from the values set in this call.
16495     *
16496     * @attr ref android.R.styleable#View_padding
16497     * @attr ref android.R.styleable#View_paddingBottom
16498     * @attr ref android.R.styleable#View_paddingLeft
16499     * @attr ref android.R.styleable#View_paddingRight
16500     * @attr ref android.R.styleable#View_paddingTop
16501     * @param left the left padding in pixels
16502     * @param top the top padding in pixels
16503     * @param right the right padding in pixels
16504     * @param bottom the bottom padding in pixels
16505     */
16506    public void setPadding(int left, int top, int right, int bottom) {
16507        resetResolvedPaddingInternal();
16508
16509        mUserPaddingStart = UNDEFINED_PADDING;
16510        mUserPaddingEnd = UNDEFINED_PADDING;
16511
16512        mUserPaddingLeftInitial = left;
16513        mUserPaddingRightInitial = right;
16514
16515        mLeftPaddingDefined = true;
16516        mRightPaddingDefined = true;
16517
16518        internalSetPadding(left, top, right, bottom);
16519    }
16520
16521    /**
16522     * @hide
16523     */
16524    protected void internalSetPadding(int left, int top, int right, int bottom) {
16525        mUserPaddingLeft = left;
16526        mUserPaddingRight = right;
16527        mUserPaddingBottom = bottom;
16528
16529        final int viewFlags = mViewFlags;
16530        boolean changed = false;
16531
16532        // Common case is there are no scroll bars.
16533        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16534            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16535                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16536                        ? 0 : getVerticalScrollbarWidth();
16537                switch (mVerticalScrollbarPosition) {
16538                    case SCROLLBAR_POSITION_DEFAULT:
16539                        if (isLayoutRtl()) {
16540                            left += offset;
16541                        } else {
16542                            right += offset;
16543                        }
16544                        break;
16545                    case SCROLLBAR_POSITION_RIGHT:
16546                        right += offset;
16547                        break;
16548                    case SCROLLBAR_POSITION_LEFT:
16549                        left += offset;
16550                        break;
16551                }
16552            }
16553            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16554                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16555                        ? 0 : getHorizontalScrollbarHeight();
16556            }
16557        }
16558
16559        if (mPaddingLeft != left) {
16560            changed = true;
16561            mPaddingLeft = left;
16562        }
16563        if (mPaddingTop != top) {
16564            changed = true;
16565            mPaddingTop = top;
16566        }
16567        if (mPaddingRight != right) {
16568            changed = true;
16569            mPaddingRight = right;
16570        }
16571        if (mPaddingBottom != bottom) {
16572            changed = true;
16573            mPaddingBottom = bottom;
16574        }
16575
16576        if (changed) {
16577            requestLayout();
16578            invalidateOutline();
16579        }
16580    }
16581
16582    /**
16583     * Sets the relative padding. The view may add on the space required to display
16584     * the scrollbars, depending on the style and visibility of the scrollbars.
16585     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16586     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16587     * from the values set in this call.
16588     *
16589     * @attr ref android.R.styleable#View_padding
16590     * @attr ref android.R.styleable#View_paddingBottom
16591     * @attr ref android.R.styleable#View_paddingStart
16592     * @attr ref android.R.styleable#View_paddingEnd
16593     * @attr ref android.R.styleable#View_paddingTop
16594     * @param start the start padding in pixels
16595     * @param top the top padding in pixels
16596     * @param end the end padding in pixels
16597     * @param bottom the bottom padding in pixels
16598     */
16599    public void setPaddingRelative(int start, int top, int end, int bottom) {
16600        resetResolvedPaddingInternal();
16601
16602        mUserPaddingStart = start;
16603        mUserPaddingEnd = end;
16604        mLeftPaddingDefined = true;
16605        mRightPaddingDefined = true;
16606
16607        switch(getLayoutDirection()) {
16608            case LAYOUT_DIRECTION_RTL:
16609                mUserPaddingLeftInitial = end;
16610                mUserPaddingRightInitial = start;
16611                internalSetPadding(end, top, start, bottom);
16612                break;
16613            case LAYOUT_DIRECTION_LTR:
16614            default:
16615                mUserPaddingLeftInitial = start;
16616                mUserPaddingRightInitial = end;
16617                internalSetPadding(start, top, end, bottom);
16618        }
16619    }
16620
16621    /**
16622     * Returns the top padding of this view.
16623     *
16624     * @return the top padding in pixels
16625     */
16626    public int getPaddingTop() {
16627        return mPaddingTop;
16628    }
16629
16630    /**
16631     * Returns the bottom padding of this view. If there are inset and enabled
16632     * scrollbars, this value may include the space required to display the
16633     * scrollbars as well.
16634     *
16635     * @return the bottom padding in pixels
16636     */
16637    public int getPaddingBottom() {
16638        return mPaddingBottom;
16639    }
16640
16641    /**
16642     * Returns the left padding of this view. If there are inset and enabled
16643     * scrollbars, this value may include the space required to display the
16644     * scrollbars as well.
16645     *
16646     * @return the left padding in pixels
16647     */
16648    public int getPaddingLeft() {
16649        if (!isPaddingResolved()) {
16650            resolvePadding();
16651        }
16652        return mPaddingLeft;
16653    }
16654
16655    /**
16656     * Returns the start padding of this view depending on its resolved layout direction.
16657     * If there are inset and enabled scrollbars, this value may include the space
16658     * required to display the scrollbars as well.
16659     *
16660     * @return the start padding in pixels
16661     */
16662    public int getPaddingStart() {
16663        if (!isPaddingResolved()) {
16664            resolvePadding();
16665        }
16666        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16667                mPaddingRight : mPaddingLeft;
16668    }
16669
16670    /**
16671     * Returns the right padding of this view. If there are inset and enabled
16672     * scrollbars, this value may include the space required to display the
16673     * scrollbars as well.
16674     *
16675     * @return the right padding in pixels
16676     */
16677    public int getPaddingRight() {
16678        if (!isPaddingResolved()) {
16679            resolvePadding();
16680        }
16681        return mPaddingRight;
16682    }
16683
16684    /**
16685     * Returns the end padding of this view depending on its resolved layout direction.
16686     * If there are inset and enabled scrollbars, this value may include the space
16687     * required to display the scrollbars as well.
16688     *
16689     * @return the end padding in pixels
16690     */
16691    public int getPaddingEnd() {
16692        if (!isPaddingResolved()) {
16693            resolvePadding();
16694        }
16695        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16696                mPaddingLeft : mPaddingRight;
16697    }
16698
16699    /**
16700     * Return if the padding has been set through relative values
16701     * {@link #setPaddingRelative(int, int, int, int)} or through
16702     * @attr ref android.R.styleable#View_paddingStart or
16703     * @attr ref android.R.styleable#View_paddingEnd
16704     *
16705     * @return true if the padding is relative or false if it is not.
16706     */
16707    public boolean isPaddingRelative() {
16708        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16709    }
16710
16711    Insets computeOpticalInsets() {
16712        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16713    }
16714
16715    /**
16716     * @hide
16717     */
16718    public void resetPaddingToInitialValues() {
16719        if (isRtlCompatibilityMode()) {
16720            mPaddingLeft = mUserPaddingLeftInitial;
16721            mPaddingRight = mUserPaddingRightInitial;
16722            return;
16723        }
16724        if (isLayoutRtl()) {
16725            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16726            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16727        } else {
16728            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16729            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16730        }
16731    }
16732
16733    /**
16734     * @hide
16735     */
16736    public Insets getOpticalInsets() {
16737        if (mLayoutInsets == null) {
16738            mLayoutInsets = computeOpticalInsets();
16739        }
16740        return mLayoutInsets;
16741    }
16742
16743    /**
16744     * Set this view's optical insets.
16745     *
16746     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16747     * property. Views that compute their own optical insets should call it as part of measurement.
16748     * This method does not request layout. If you are setting optical insets outside of
16749     * measure/layout itself you will want to call requestLayout() yourself.
16750     * </p>
16751     * @hide
16752     */
16753    public void setOpticalInsets(Insets insets) {
16754        mLayoutInsets = insets;
16755    }
16756
16757    /**
16758     * Changes the selection state of this view. A view can be selected or not.
16759     * Note that selection is not the same as focus. Views are typically
16760     * selected in the context of an AdapterView like ListView or GridView;
16761     * the selected view is the view that is highlighted.
16762     *
16763     * @param selected true if the view must be selected, false otherwise
16764     */
16765    public void setSelected(boolean selected) {
16766        //noinspection DoubleNegation
16767        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16768            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16769            if (!selected) resetPressedState();
16770            invalidate(true);
16771            refreshDrawableState();
16772            dispatchSetSelected(selected);
16773            if (selected) {
16774                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
16775            } else {
16776                notifyViewAccessibilityStateChangedIfNeeded(
16777                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16778            }
16779        }
16780    }
16781
16782    /**
16783     * Dispatch setSelected to all of this View's children.
16784     *
16785     * @see #setSelected(boolean)
16786     *
16787     * @param selected The new selected state
16788     */
16789    protected void dispatchSetSelected(boolean selected) {
16790    }
16791
16792    /**
16793     * Indicates the selection state of this view.
16794     *
16795     * @return true if the view is selected, false otherwise
16796     */
16797    @ViewDebug.ExportedProperty
16798    public boolean isSelected() {
16799        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16800    }
16801
16802    /**
16803     * Changes the activated state of this view. A view can be activated or not.
16804     * Note that activation is not the same as selection.  Selection is
16805     * a transient property, representing the view (hierarchy) the user is
16806     * currently interacting with.  Activation is a longer-term state that the
16807     * user can move views in and out of.  For example, in a list view with
16808     * single or multiple selection enabled, the views in the current selection
16809     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16810     * here.)  The activated state is propagated down to children of the view it
16811     * is set on.
16812     *
16813     * @param activated true if the view must be activated, false otherwise
16814     */
16815    public void setActivated(boolean activated) {
16816        //noinspection DoubleNegation
16817        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16818            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16819            invalidate(true);
16820            refreshDrawableState();
16821            dispatchSetActivated(activated);
16822        }
16823    }
16824
16825    /**
16826     * Dispatch setActivated to all of this View's children.
16827     *
16828     * @see #setActivated(boolean)
16829     *
16830     * @param activated The new activated state
16831     */
16832    protected void dispatchSetActivated(boolean activated) {
16833    }
16834
16835    /**
16836     * Indicates the activation state of this view.
16837     *
16838     * @return true if the view is activated, false otherwise
16839     */
16840    @ViewDebug.ExportedProperty
16841    public boolean isActivated() {
16842        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16843    }
16844
16845    /**
16846     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16847     * observer can be used to get notifications when global events, like
16848     * layout, happen.
16849     *
16850     * The returned ViewTreeObserver observer is not guaranteed to remain
16851     * valid for the lifetime of this View. If the caller of this method keeps
16852     * a long-lived reference to ViewTreeObserver, it should always check for
16853     * the return value of {@link ViewTreeObserver#isAlive()}.
16854     *
16855     * @return The ViewTreeObserver for this view's hierarchy.
16856     */
16857    public ViewTreeObserver getViewTreeObserver() {
16858        if (mAttachInfo != null) {
16859            return mAttachInfo.mTreeObserver;
16860        }
16861        if (mFloatingTreeObserver == null) {
16862            mFloatingTreeObserver = new ViewTreeObserver();
16863        }
16864        return mFloatingTreeObserver;
16865    }
16866
16867    /**
16868     * <p>Finds the topmost view in the current view hierarchy.</p>
16869     *
16870     * @return the topmost view containing this view
16871     */
16872    public View getRootView() {
16873        if (mAttachInfo != null) {
16874            final View v = mAttachInfo.mRootView;
16875            if (v != null) {
16876                return v;
16877            }
16878        }
16879
16880        View parent = this;
16881
16882        while (parent.mParent != null && parent.mParent instanceof View) {
16883            parent = (View) parent.mParent;
16884        }
16885
16886        return parent;
16887    }
16888
16889    /**
16890     * Transforms a motion event from view-local coordinates to on-screen
16891     * coordinates.
16892     *
16893     * @param ev the view-local motion event
16894     * @return false if the transformation could not be applied
16895     * @hide
16896     */
16897    public boolean toGlobalMotionEvent(MotionEvent ev) {
16898        final AttachInfo info = mAttachInfo;
16899        if (info == null) {
16900            return false;
16901        }
16902
16903        final Matrix m = info.mTmpMatrix;
16904        m.set(Matrix.IDENTITY_MATRIX);
16905        transformMatrixToGlobal(m);
16906        ev.transform(m);
16907        return true;
16908    }
16909
16910    /**
16911     * Transforms a motion event from on-screen coordinates to view-local
16912     * coordinates.
16913     *
16914     * @param ev the on-screen motion event
16915     * @return false if the transformation could not be applied
16916     * @hide
16917     */
16918    public boolean toLocalMotionEvent(MotionEvent ev) {
16919        final AttachInfo info = mAttachInfo;
16920        if (info == null) {
16921            return false;
16922        }
16923
16924        final Matrix m = info.mTmpMatrix;
16925        m.set(Matrix.IDENTITY_MATRIX);
16926        transformMatrixToLocal(m);
16927        ev.transform(m);
16928        return true;
16929    }
16930
16931    /**
16932     * Modifies the input matrix such that it maps view-local coordinates to
16933     * on-screen coordinates.
16934     *
16935     * @param m input matrix to modify
16936     * @hide
16937     */
16938    public void transformMatrixToGlobal(Matrix m) {
16939        final ViewParent parent = mParent;
16940        if (parent instanceof View) {
16941            final View vp = (View) parent;
16942            vp.transformMatrixToGlobal(m);
16943            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16944        } else if (parent instanceof ViewRootImpl) {
16945            final ViewRootImpl vr = (ViewRootImpl) parent;
16946            vr.transformMatrixToGlobal(m);
16947            m.preTranslate(0, -vr.mCurScrollY);
16948        }
16949
16950        m.preTranslate(mLeft, mTop);
16951
16952        if (!hasIdentityMatrix()) {
16953            m.preConcat(getMatrix());
16954        }
16955    }
16956
16957    /**
16958     * Modifies the input matrix such that it maps on-screen coordinates to
16959     * view-local coordinates.
16960     *
16961     * @param m input matrix to modify
16962     * @hide
16963     */
16964    public void transformMatrixToLocal(Matrix m) {
16965        final ViewParent parent = mParent;
16966        if (parent instanceof View) {
16967            final View vp = (View) parent;
16968            vp.transformMatrixToLocal(m);
16969            m.postTranslate(vp.mScrollX, vp.mScrollY);
16970        } else if (parent instanceof ViewRootImpl) {
16971            final ViewRootImpl vr = (ViewRootImpl) parent;
16972            vr.transformMatrixToLocal(m);
16973            m.postTranslate(0, vr.mCurScrollY);
16974        }
16975
16976        m.postTranslate(-mLeft, -mTop);
16977
16978        if (!hasIdentityMatrix()) {
16979            m.postConcat(getInverseMatrix());
16980        }
16981    }
16982
16983    /**
16984     * @hide
16985     */
16986    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16987            @ViewDebug.IntToString(from = 0, to = "x"),
16988            @ViewDebug.IntToString(from = 1, to = "y")
16989    })
16990    public int[] getLocationOnScreen() {
16991        int[] location = new int[2];
16992        getLocationOnScreen(location);
16993        return location;
16994    }
16995
16996    /**
16997     * <p>Computes the coordinates of this view on the screen. The argument
16998     * must be an array of two integers. After the method returns, the array
16999     * contains the x and y location in that order.</p>
17000     *
17001     * @param location an array of two integers in which to hold the coordinates
17002     */
17003    public void getLocationOnScreen(int[] location) {
17004        getLocationInWindow(location);
17005
17006        final AttachInfo info = mAttachInfo;
17007        if (info != null) {
17008            location[0] += info.mWindowLeft;
17009            location[1] += info.mWindowTop;
17010        }
17011    }
17012
17013    /**
17014     * <p>Computes the coordinates of this view in its window. The argument
17015     * must be an array of two integers. After the method returns, the array
17016     * contains the x and y location in that order.</p>
17017     *
17018     * @param location an array of two integers in which to hold the coordinates
17019     */
17020    public void getLocationInWindow(int[] location) {
17021        if (location == null || location.length < 2) {
17022            throw new IllegalArgumentException("location must be an array of two integers");
17023        }
17024
17025        if (mAttachInfo == null) {
17026            // When the view is not attached to a window, this method does not make sense
17027            location[0] = location[1] = 0;
17028            return;
17029        }
17030
17031        float[] position = mAttachInfo.mTmpTransformLocation;
17032        position[0] = position[1] = 0.0f;
17033
17034        if (!hasIdentityMatrix()) {
17035            getMatrix().mapPoints(position);
17036        }
17037
17038        position[0] += mLeft;
17039        position[1] += mTop;
17040
17041        ViewParent viewParent = mParent;
17042        while (viewParent instanceof View) {
17043            final View view = (View) viewParent;
17044
17045            position[0] -= view.mScrollX;
17046            position[1] -= view.mScrollY;
17047
17048            if (!view.hasIdentityMatrix()) {
17049                view.getMatrix().mapPoints(position);
17050            }
17051
17052            position[0] += view.mLeft;
17053            position[1] += view.mTop;
17054
17055            viewParent = view.mParent;
17056         }
17057
17058        if (viewParent instanceof ViewRootImpl) {
17059            // *cough*
17060            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17061            position[1] -= vr.mCurScrollY;
17062        }
17063
17064        location[0] = (int) (position[0] + 0.5f);
17065        location[1] = (int) (position[1] + 0.5f);
17066    }
17067
17068    /**
17069     * {@hide}
17070     * @param id the id of the view to be found
17071     * @return the view of the specified id, null if cannot be found
17072     */
17073    protected View findViewTraversal(int id) {
17074        if (id == mID) {
17075            return this;
17076        }
17077        return null;
17078    }
17079
17080    /**
17081     * {@hide}
17082     * @param tag the tag of the view to be found
17083     * @return the view of specified tag, null if cannot be found
17084     */
17085    protected View findViewWithTagTraversal(Object tag) {
17086        if (tag != null && tag.equals(mTag)) {
17087            return this;
17088        }
17089        return null;
17090    }
17091
17092    /**
17093     * {@hide}
17094     * @param predicate The predicate to evaluate.
17095     * @param childToSkip If not null, ignores this child during the recursive traversal.
17096     * @return The first view that matches the predicate or null.
17097     */
17098    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17099        if (predicate.apply(this)) {
17100            return this;
17101        }
17102        return null;
17103    }
17104
17105    /**
17106     * Look for a child view with the given id.  If this view has the given
17107     * id, return this view.
17108     *
17109     * @param id The id to search for.
17110     * @return The view that has the given id in the hierarchy or null
17111     */
17112    public final View findViewById(int id) {
17113        if (id < 0) {
17114            return null;
17115        }
17116        return findViewTraversal(id);
17117    }
17118
17119    /**
17120     * Finds a view by its unuque and stable accessibility id.
17121     *
17122     * @param accessibilityId The searched accessibility id.
17123     * @return The found view.
17124     */
17125    final View findViewByAccessibilityId(int accessibilityId) {
17126        if (accessibilityId < 0) {
17127            return null;
17128        }
17129        return findViewByAccessibilityIdTraversal(accessibilityId);
17130    }
17131
17132    /**
17133     * Performs the traversal to find a view by its unuque and stable accessibility id.
17134     *
17135     * <strong>Note:</strong>This method does not stop at the root namespace
17136     * boundary since the user can touch the screen at an arbitrary location
17137     * potentially crossing the root namespace bounday which will send an
17138     * accessibility event to accessibility services and they should be able
17139     * to obtain the event source. Also accessibility ids are guaranteed to be
17140     * unique in the window.
17141     *
17142     * @param accessibilityId The accessibility id.
17143     * @return The found view.
17144     *
17145     * @hide
17146     */
17147    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17148        if (getAccessibilityViewId() == accessibilityId) {
17149            return this;
17150        }
17151        return null;
17152    }
17153
17154    /**
17155     * Look for a child view with the given tag.  If this view has the given
17156     * tag, return this view.
17157     *
17158     * @param tag The tag to search for, using "tag.equals(getTag())".
17159     * @return The View that has the given tag in the hierarchy or null
17160     */
17161    public final View findViewWithTag(Object tag) {
17162        if (tag == null) {
17163            return null;
17164        }
17165        return findViewWithTagTraversal(tag);
17166    }
17167
17168    /**
17169     * {@hide}
17170     * Look for a child view that matches the specified predicate.
17171     * If this view matches the predicate, return this view.
17172     *
17173     * @param predicate The predicate to evaluate.
17174     * @return The first view that matches the predicate or null.
17175     */
17176    public final View findViewByPredicate(Predicate<View> predicate) {
17177        return findViewByPredicateTraversal(predicate, null);
17178    }
17179
17180    /**
17181     * {@hide}
17182     * Look for a child view that matches the specified predicate,
17183     * starting with the specified view and its descendents and then
17184     * recusively searching the ancestors and siblings of that view
17185     * until this view is reached.
17186     *
17187     * This method is useful in cases where the predicate does not match
17188     * a single unique view (perhaps multiple views use the same id)
17189     * and we are trying to find the view that is "closest" in scope to the
17190     * starting view.
17191     *
17192     * @param start The view to start from.
17193     * @param predicate The predicate to evaluate.
17194     * @return The first view that matches the predicate or null.
17195     */
17196    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17197        View childToSkip = null;
17198        for (;;) {
17199            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17200            if (view != null || start == this) {
17201                return view;
17202            }
17203
17204            ViewParent parent = start.getParent();
17205            if (parent == null || !(parent instanceof View)) {
17206                return null;
17207            }
17208
17209            childToSkip = start;
17210            start = (View) parent;
17211        }
17212    }
17213
17214    /**
17215     * Sets the identifier for this view. The identifier does not have to be
17216     * unique in this view's hierarchy. The identifier should be a positive
17217     * number.
17218     *
17219     * @see #NO_ID
17220     * @see #getId()
17221     * @see #findViewById(int)
17222     *
17223     * @param id a number used to identify the view
17224     *
17225     * @attr ref android.R.styleable#View_id
17226     */
17227    public void setId(int id) {
17228        mID = id;
17229        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17230            mID = generateViewId();
17231        }
17232    }
17233
17234    /**
17235     * {@hide}
17236     *
17237     * @param isRoot true if the view belongs to the root namespace, false
17238     *        otherwise
17239     */
17240    public void setIsRootNamespace(boolean isRoot) {
17241        if (isRoot) {
17242            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17243        } else {
17244            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17245        }
17246    }
17247
17248    /**
17249     * {@hide}
17250     *
17251     * @return true if the view belongs to the root namespace, false otherwise
17252     */
17253    public boolean isRootNamespace() {
17254        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17255    }
17256
17257    /**
17258     * Returns this view's identifier.
17259     *
17260     * @return a positive integer used to identify the view or {@link #NO_ID}
17261     *         if the view has no ID
17262     *
17263     * @see #setId(int)
17264     * @see #findViewById(int)
17265     * @attr ref android.R.styleable#View_id
17266     */
17267    @ViewDebug.CapturedViewProperty
17268    public int getId() {
17269        return mID;
17270    }
17271
17272    /**
17273     * Returns this view's tag.
17274     *
17275     * @return the Object stored in this view as a tag, or {@code null} if not
17276     *         set
17277     *
17278     * @see #setTag(Object)
17279     * @see #getTag(int)
17280     */
17281    @ViewDebug.ExportedProperty
17282    public Object getTag() {
17283        return mTag;
17284    }
17285
17286    /**
17287     * Sets the tag associated with this view. A tag can be used to mark
17288     * a view in its hierarchy and does not have to be unique within the
17289     * hierarchy. Tags can also be used to store data within a view without
17290     * resorting to another data structure.
17291     *
17292     * @param tag an Object to tag the view with
17293     *
17294     * @see #getTag()
17295     * @see #setTag(int, Object)
17296     */
17297    public void setTag(final Object tag) {
17298        mTag = tag;
17299    }
17300
17301    /**
17302     * Returns the tag associated with this view and the specified key.
17303     *
17304     * @param key The key identifying the tag
17305     *
17306     * @return the Object stored in this view as a tag, or {@code null} if not
17307     *         set
17308     *
17309     * @see #setTag(int, Object)
17310     * @see #getTag()
17311     */
17312    public Object getTag(int key) {
17313        if (mKeyedTags != null) return mKeyedTags.get(key);
17314        return null;
17315    }
17316
17317    /**
17318     * Sets a tag associated with this view and a key. A tag can be used
17319     * to mark a view in its hierarchy and does not have to be unique within
17320     * the hierarchy. Tags can also be used to store data within a view
17321     * without resorting to another data structure.
17322     *
17323     * The specified key should be an id declared in the resources of the
17324     * application to ensure it is unique (see the <a
17325     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17326     * Keys identified as belonging to
17327     * the Android framework or not associated with any package will cause
17328     * an {@link IllegalArgumentException} to be thrown.
17329     *
17330     * @param key The key identifying the tag
17331     * @param tag An Object to tag the view with
17332     *
17333     * @throws IllegalArgumentException If they specified key is not valid
17334     *
17335     * @see #setTag(Object)
17336     * @see #getTag(int)
17337     */
17338    public void setTag(int key, final Object tag) {
17339        // If the package id is 0x00 or 0x01, it's either an undefined package
17340        // or a framework id
17341        if ((key >>> 24) < 2) {
17342            throw new IllegalArgumentException("The key must be an application-specific "
17343                    + "resource id.");
17344        }
17345
17346        setKeyedTag(key, tag);
17347    }
17348
17349    /**
17350     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17351     * framework id.
17352     *
17353     * @hide
17354     */
17355    public void setTagInternal(int key, Object tag) {
17356        if ((key >>> 24) != 0x1) {
17357            throw new IllegalArgumentException("The key must be a framework-specific "
17358                    + "resource id.");
17359        }
17360
17361        setKeyedTag(key, tag);
17362    }
17363
17364    private void setKeyedTag(int key, Object tag) {
17365        if (mKeyedTags == null) {
17366            mKeyedTags = new SparseArray<Object>(2);
17367        }
17368
17369        mKeyedTags.put(key, tag);
17370    }
17371
17372    /**
17373     * Prints information about this view in the log output, with the tag
17374     * {@link #VIEW_LOG_TAG}.
17375     *
17376     * @hide
17377     */
17378    public void debug() {
17379        debug(0);
17380    }
17381
17382    /**
17383     * Prints information about this view in the log output, with the tag
17384     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17385     * indentation defined by the <code>depth</code>.
17386     *
17387     * @param depth the indentation level
17388     *
17389     * @hide
17390     */
17391    protected void debug(int depth) {
17392        String output = debugIndent(depth - 1);
17393
17394        output += "+ " + this;
17395        int id = getId();
17396        if (id != -1) {
17397            output += " (id=" + id + ")";
17398        }
17399        Object tag = getTag();
17400        if (tag != null) {
17401            output += " (tag=" + tag + ")";
17402        }
17403        Log.d(VIEW_LOG_TAG, output);
17404
17405        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17406            output = debugIndent(depth) + " FOCUSED";
17407            Log.d(VIEW_LOG_TAG, output);
17408        }
17409
17410        output = debugIndent(depth);
17411        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17412                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17413                + "} ";
17414        Log.d(VIEW_LOG_TAG, output);
17415
17416        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17417                || mPaddingBottom != 0) {
17418            output = debugIndent(depth);
17419            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17420                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17421            Log.d(VIEW_LOG_TAG, output);
17422        }
17423
17424        output = debugIndent(depth);
17425        output += "mMeasureWidth=" + mMeasuredWidth +
17426                " mMeasureHeight=" + mMeasuredHeight;
17427        Log.d(VIEW_LOG_TAG, output);
17428
17429        output = debugIndent(depth);
17430        if (mLayoutParams == null) {
17431            output += "BAD! no layout params";
17432        } else {
17433            output = mLayoutParams.debug(output);
17434        }
17435        Log.d(VIEW_LOG_TAG, output);
17436
17437        output = debugIndent(depth);
17438        output += "flags={";
17439        output += View.printFlags(mViewFlags);
17440        output += "}";
17441        Log.d(VIEW_LOG_TAG, output);
17442
17443        output = debugIndent(depth);
17444        output += "privateFlags={";
17445        output += View.printPrivateFlags(mPrivateFlags);
17446        output += "}";
17447        Log.d(VIEW_LOG_TAG, output);
17448    }
17449
17450    /**
17451     * Creates a string of whitespaces used for indentation.
17452     *
17453     * @param depth the indentation level
17454     * @return a String containing (depth * 2 + 3) * 2 white spaces
17455     *
17456     * @hide
17457     */
17458    protected static String debugIndent(int depth) {
17459        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17460        for (int i = 0; i < (depth * 2) + 3; i++) {
17461            spaces.append(' ').append(' ');
17462        }
17463        return spaces.toString();
17464    }
17465
17466    /**
17467     * <p>Return the offset of the widget's text baseline from the widget's top
17468     * boundary. If this widget does not support baseline alignment, this
17469     * method returns -1. </p>
17470     *
17471     * @return the offset of the baseline within the widget's bounds or -1
17472     *         if baseline alignment is not supported
17473     */
17474    @ViewDebug.ExportedProperty(category = "layout")
17475    public int getBaseline() {
17476        return -1;
17477    }
17478
17479    /**
17480     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17481     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17482     * a layout pass.
17483     *
17484     * @return whether the view hierarchy is currently undergoing a layout pass
17485     */
17486    public boolean isInLayout() {
17487        ViewRootImpl viewRoot = getViewRootImpl();
17488        return (viewRoot != null && viewRoot.isInLayout());
17489    }
17490
17491    /**
17492     * Call this when something has changed which has invalidated the
17493     * layout of this view. This will schedule a layout pass of the view
17494     * tree. This should not be called while the view hierarchy is currently in a layout
17495     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17496     * end of the current layout pass (and then layout will run again) or after the current
17497     * frame is drawn and the next layout occurs.
17498     *
17499     * <p>Subclasses which override this method should call the superclass method to
17500     * handle possible request-during-layout errors correctly.</p>
17501     */
17502    public void requestLayout() {
17503        if (mMeasureCache != null) mMeasureCache.clear();
17504
17505        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17506            // Only trigger request-during-layout logic if this is the view requesting it,
17507            // not the views in its parent hierarchy
17508            ViewRootImpl viewRoot = getViewRootImpl();
17509            if (viewRoot != null && viewRoot.isInLayout()) {
17510                if (!viewRoot.requestLayoutDuringLayout(this)) {
17511                    return;
17512                }
17513            }
17514            mAttachInfo.mViewRequestingLayout = this;
17515        }
17516
17517        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17518        mPrivateFlags |= PFLAG_INVALIDATED;
17519
17520        if (mParent != null && !mParent.isLayoutRequested()) {
17521            mParent.requestLayout();
17522        }
17523        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17524            mAttachInfo.mViewRequestingLayout = null;
17525        }
17526    }
17527
17528    /**
17529     * Forces this view to be laid out during the next layout pass.
17530     * This method does not call requestLayout() or forceLayout()
17531     * on the parent.
17532     */
17533    public void forceLayout() {
17534        if (mMeasureCache != null) mMeasureCache.clear();
17535
17536        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17537        mPrivateFlags |= PFLAG_INVALIDATED;
17538    }
17539
17540    /**
17541     * <p>
17542     * This is called to find out how big a view should be. The parent
17543     * supplies constraint information in the width and height parameters.
17544     * </p>
17545     *
17546     * <p>
17547     * The actual measurement work of a view is performed in
17548     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17549     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17550     * </p>
17551     *
17552     *
17553     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17554     *        parent
17555     * @param heightMeasureSpec Vertical space requirements as imposed by the
17556     *        parent
17557     *
17558     * @see #onMeasure(int, int)
17559     */
17560    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17561        boolean optical = isLayoutModeOptical(this);
17562        if (optical != isLayoutModeOptical(mParent)) {
17563            Insets insets = getOpticalInsets();
17564            int oWidth  = insets.left + insets.right;
17565            int oHeight = insets.top  + insets.bottom;
17566            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17567            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17568        }
17569
17570        // Suppress sign extension for the low bytes
17571        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17572        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17573
17574        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17575        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
17576                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
17577        final boolean matchingSize = isExactly &&
17578                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
17579                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
17580        if (forceLayout || !matchingSize &&
17581                (widthMeasureSpec != mOldWidthMeasureSpec ||
17582                        heightMeasureSpec != mOldHeightMeasureSpec)) {
17583
17584            // first clears the measured dimension flag
17585            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17586
17587            resolveRtlPropertiesIfNeeded();
17588
17589            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
17590            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17591                // measure ourselves, this should set the measured dimension flag back
17592                onMeasure(widthMeasureSpec, heightMeasureSpec);
17593                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17594            } else {
17595                long value = mMeasureCache.valueAt(cacheIndex);
17596                // Casting a long to int drops the high 32 bits, no mask needed
17597                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17598                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17599            }
17600
17601            // flag not set, setMeasuredDimension() was not invoked, we raise
17602            // an exception to warn the developer
17603            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17604                throw new IllegalStateException("onMeasure() did not set the"
17605                        + " measured dimension by calling"
17606                        + " setMeasuredDimension()");
17607            }
17608
17609            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17610        }
17611
17612        mOldWidthMeasureSpec = widthMeasureSpec;
17613        mOldHeightMeasureSpec = heightMeasureSpec;
17614
17615        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17616                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17617    }
17618
17619    /**
17620     * <p>
17621     * Measure the view and its content to determine the measured width and the
17622     * measured height. This method is invoked by {@link #measure(int, int)} and
17623     * should be overridden by subclasses to provide accurate and efficient
17624     * measurement of their contents.
17625     * </p>
17626     *
17627     * <p>
17628     * <strong>CONTRACT:</strong> When overriding this method, you
17629     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17630     * measured width and height of this view. Failure to do so will trigger an
17631     * <code>IllegalStateException</code>, thrown by
17632     * {@link #measure(int, int)}. Calling the superclass'
17633     * {@link #onMeasure(int, int)} is a valid use.
17634     * </p>
17635     *
17636     * <p>
17637     * The base class implementation of measure defaults to the background size,
17638     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17639     * override {@link #onMeasure(int, int)} to provide better measurements of
17640     * their content.
17641     * </p>
17642     *
17643     * <p>
17644     * If this method is overridden, it is the subclass's responsibility to make
17645     * sure the measured height and width are at least the view's minimum height
17646     * and width ({@link #getSuggestedMinimumHeight()} and
17647     * {@link #getSuggestedMinimumWidth()}).
17648     * </p>
17649     *
17650     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17651     *                         The requirements are encoded with
17652     *                         {@link android.view.View.MeasureSpec}.
17653     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17654     *                         The requirements are encoded with
17655     *                         {@link android.view.View.MeasureSpec}.
17656     *
17657     * @see #getMeasuredWidth()
17658     * @see #getMeasuredHeight()
17659     * @see #setMeasuredDimension(int, int)
17660     * @see #getSuggestedMinimumHeight()
17661     * @see #getSuggestedMinimumWidth()
17662     * @see android.view.View.MeasureSpec#getMode(int)
17663     * @see android.view.View.MeasureSpec#getSize(int)
17664     */
17665    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17666        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17667                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17668    }
17669
17670    /**
17671     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17672     * measured width and measured height. Failing to do so will trigger an
17673     * exception at measurement time.</p>
17674     *
17675     * @param measuredWidth The measured width of this view.  May be a complex
17676     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17677     * {@link #MEASURED_STATE_TOO_SMALL}.
17678     * @param measuredHeight The measured height of this view.  May be a complex
17679     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17680     * {@link #MEASURED_STATE_TOO_SMALL}.
17681     */
17682    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17683        boolean optical = isLayoutModeOptical(this);
17684        if (optical != isLayoutModeOptical(mParent)) {
17685            Insets insets = getOpticalInsets();
17686            int opticalWidth  = insets.left + insets.right;
17687            int opticalHeight = insets.top  + insets.bottom;
17688
17689            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17690            measuredHeight += optical ? opticalHeight : -opticalHeight;
17691        }
17692        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17693    }
17694
17695    /**
17696     * Sets the measured dimension without extra processing for things like optical bounds.
17697     * Useful for reapplying consistent values that have already been cooked with adjustments
17698     * for optical bounds, etc. such as those from the measurement cache.
17699     *
17700     * @param measuredWidth The measured width of this view.  May be a complex
17701     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17702     * {@link #MEASURED_STATE_TOO_SMALL}.
17703     * @param measuredHeight The measured height of this view.  May be a complex
17704     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17705     * {@link #MEASURED_STATE_TOO_SMALL}.
17706     */
17707    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17708        mMeasuredWidth = measuredWidth;
17709        mMeasuredHeight = measuredHeight;
17710
17711        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17712    }
17713
17714    /**
17715     * Merge two states as returned by {@link #getMeasuredState()}.
17716     * @param curState The current state as returned from a view or the result
17717     * of combining multiple views.
17718     * @param newState The new view state to combine.
17719     * @return Returns a new integer reflecting the combination of the two
17720     * states.
17721     */
17722    public static int combineMeasuredStates(int curState, int newState) {
17723        return curState | newState;
17724    }
17725
17726    /**
17727     * Version of {@link #resolveSizeAndState(int, int, int)}
17728     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17729     */
17730    public static int resolveSize(int size, int measureSpec) {
17731        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17732    }
17733
17734    /**
17735     * Utility to reconcile a desired size and state, with constraints imposed
17736     * by a MeasureSpec. Will take the desired size, unless a different size
17737     * is imposed by the constraints. The returned value is a compound integer,
17738     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17739     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
17740     * resulting size is smaller than the size the view wants to be.
17741     *
17742     * @param size How big the view wants to be.
17743     * @param measureSpec Constraints imposed by the parent.
17744     * @param childMeasuredState Size information bit mask for the view's
17745     *                           children.
17746     * @return Size information bit mask as defined by
17747     *         {@link #MEASURED_SIZE_MASK} and
17748     *         {@link #MEASURED_STATE_TOO_SMALL}.
17749     */
17750    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17751        final int specMode = MeasureSpec.getMode(measureSpec);
17752        final int specSize = MeasureSpec.getSize(measureSpec);
17753        final int result;
17754        switch (specMode) {
17755            case MeasureSpec.AT_MOST:
17756                if (specSize < size) {
17757                    result = specSize | MEASURED_STATE_TOO_SMALL;
17758                } else {
17759                    result = size;
17760                }
17761                break;
17762            case MeasureSpec.EXACTLY:
17763                result = specSize;
17764                break;
17765            case MeasureSpec.UNSPECIFIED:
17766            default:
17767                result = size;
17768        }
17769        return result | (childMeasuredState & MEASURED_STATE_MASK);
17770    }
17771
17772    /**
17773     * Utility to return a default size. Uses the supplied size if the
17774     * MeasureSpec imposed no constraints. Will get larger if allowed
17775     * by the MeasureSpec.
17776     *
17777     * @param size Default size for this view
17778     * @param measureSpec Constraints imposed by the parent
17779     * @return The size this view should be.
17780     */
17781    public static int getDefaultSize(int size, int measureSpec) {
17782        int result = size;
17783        int specMode = MeasureSpec.getMode(measureSpec);
17784        int specSize = MeasureSpec.getSize(measureSpec);
17785
17786        switch (specMode) {
17787        case MeasureSpec.UNSPECIFIED:
17788            result = size;
17789            break;
17790        case MeasureSpec.AT_MOST:
17791        case MeasureSpec.EXACTLY:
17792            result = specSize;
17793            break;
17794        }
17795        return result;
17796    }
17797
17798    /**
17799     * Returns the suggested minimum height that the view should use. This
17800     * returns the maximum of the view's minimum height
17801     * and the background's minimum height
17802     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17803     * <p>
17804     * When being used in {@link #onMeasure(int, int)}, the caller should still
17805     * ensure the returned height is within the requirements of the parent.
17806     *
17807     * @return The suggested minimum height of the view.
17808     */
17809    protected int getSuggestedMinimumHeight() {
17810        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17811
17812    }
17813
17814    /**
17815     * Returns the suggested minimum width that the view should use. This
17816     * returns the maximum of the view's minimum width)
17817     * and the background's minimum width
17818     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17819     * <p>
17820     * When being used in {@link #onMeasure(int, int)}, the caller should still
17821     * ensure the returned width is within the requirements of the parent.
17822     *
17823     * @return The suggested minimum width of the view.
17824     */
17825    protected int getSuggestedMinimumWidth() {
17826        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17827    }
17828
17829    /**
17830     * Returns the minimum height of the view.
17831     *
17832     * @return the minimum height the view will try to be.
17833     *
17834     * @see #setMinimumHeight(int)
17835     *
17836     * @attr ref android.R.styleable#View_minHeight
17837     */
17838    public int getMinimumHeight() {
17839        return mMinHeight;
17840    }
17841
17842    /**
17843     * Sets the minimum height of the view. It is not guaranteed the view will
17844     * be able to achieve this minimum height (for example, if its parent layout
17845     * constrains it with less available height).
17846     *
17847     * @param minHeight The minimum height the view will try to be.
17848     *
17849     * @see #getMinimumHeight()
17850     *
17851     * @attr ref android.R.styleable#View_minHeight
17852     */
17853    public void setMinimumHeight(int minHeight) {
17854        mMinHeight = minHeight;
17855        requestLayout();
17856    }
17857
17858    /**
17859     * Returns the minimum width of the view.
17860     *
17861     * @return the minimum width the view will try to be.
17862     *
17863     * @see #setMinimumWidth(int)
17864     *
17865     * @attr ref android.R.styleable#View_minWidth
17866     */
17867    public int getMinimumWidth() {
17868        return mMinWidth;
17869    }
17870
17871    /**
17872     * Sets the minimum width of the view. It is not guaranteed the view will
17873     * be able to achieve this minimum width (for example, if its parent layout
17874     * constrains it with less available width).
17875     *
17876     * @param minWidth The minimum width the view will try to be.
17877     *
17878     * @see #getMinimumWidth()
17879     *
17880     * @attr ref android.R.styleable#View_minWidth
17881     */
17882    public void setMinimumWidth(int minWidth) {
17883        mMinWidth = minWidth;
17884        requestLayout();
17885
17886    }
17887
17888    /**
17889     * Get the animation currently associated with this view.
17890     *
17891     * @return The animation that is currently playing or
17892     *         scheduled to play for this view.
17893     */
17894    public Animation getAnimation() {
17895        return mCurrentAnimation;
17896    }
17897
17898    /**
17899     * Start the specified animation now.
17900     *
17901     * @param animation the animation to start now
17902     */
17903    public void startAnimation(Animation animation) {
17904        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17905        setAnimation(animation);
17906        invalidateParentCaches();
17907        invalidate(true);
17908    }
17909
17910    /**
17911     * Cancels any animations for this view.
17912     */
17913    public void clearAnimation() {
17914        if (mCurrentAnimation != null) {
17915            mCurrentAnimation.detach();
17916        }
17917        mCurrentAnimation = null;
17918        invalidateParentIfNeeded();
17919    }
17920
17921    /**
17922     * Sets the next animation to play for this view.
17923     * If you want the animation to play immediately, use
17924     * {@link #startAnimation(android.view.animation.Animation)} instead.
17925     * This method provides allows fine-grained
17926     * control over the start time and invalidation, but you
17927     * must make sure that 1) the animation has a start time set, and
17928     * 2) the view's parent (which controls animations on its children)
17929     * will be invalidated when the animation is supposed to
17930     * start.
17931     *
17932     * @param animation The next animation, or null.
17933     */
17934    public void setAnimation(Animation animation) {
17935        mCurrentAnimation = animation;
17936
17937        if (animation != null) {
17938            // If the screen is off assume the animation start time is now instead of
17939            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17940            // would cause the animation to start when the screen turns back on
17941            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17942                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17943                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17944            }
17945            animation.reset();
17946        }
17947    }
17948
17949    /**
17950     * Invoked by a parent ViewGroup to notify the start of the animation
17951     * currently associated with this view. If you override this method,
17952     * always call super.onAnimationStart();
17953     *
17954     * @see #setAnimation(android.view.animation.Animation)
17955     * @see #getAnimation()
17956     */
17957    protected void onAnimationStart() {
17958        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17959    }
17960
17961    /**
17962     * Invoked by a parent ViewGroup to notify the end of the animation
17963     * currently associated with this view. If you override this method,
17964     * always call super.onAnimationEnd();
17965     *
17966     * @see #setAnimation(android.view.animation.Animation)
17967     * @see #getAnimation()
17968     */
17969    protected void onAnimationEnd() {
17970        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17971    }
17972
17973    /**
17974     * Invoked if there is a Transform that involves alpha. Subclass that can
17975     * draw themselves with the specified alpha should return true, and then
17976     * respect that alpha when their onDraw() is called. If this returns false
17977     * then the view may be redirected to draw into an offscreen buffer to
17978     * fulfill the request, which will look fine, but may be slower than if the
17979     * subclass handles it internally. The default implementation returns false.
17980     *
17981     * @param alpha The alpha (0..255) to apply to the view's drawing
17982     * @return true if the view can draw with the specified alpha.
17983     */
17984    protected boolean onSetAlpha(int alpha) {
17985        return false;
17986    }
17987
17988    /**
17989     * This is used by the RootView to perform an optimization when
17990     * the view hierarchy contains one or several SurfaceView.
17991     * SurfaceView is always considered transparent, but its children are not,
17992     * therefore all View objects remove themselves from the global transparent
17993     * region (passed as a parameter to this function).
17994     *
17995     * @param region The transparent region for this ViewAncestor (window).
17996     *
17997     * @return Returns true if the effective visibility of the view at this
17998     * point is opaque, regardless of the transparent region; returns false
17999     * if it is possible for underlying windows to be seen behind the view.
18000     *
18001     * {@hide}
18002     */
18003    public boolean gatherTransparentRegion(Region region) {
18004        final AttachInfo attachInfo = mAttachInfo;
18005        if (region != null && attachInfo != null) {
18006            final int pflags = mPrivateFlags;
18007            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18008                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18009                // remove it from the transparent region.
18010                final int[] location = attachInfo.mTransparentLocation;
18011                getLocationInWindow(location);
18012                region.op(location[0], location[1], location[0] + mRight - mLeft,
18013                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18014            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18015                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18016                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18017                // exists, so we remove the background drawable's non-transparent
18018                // parts from this transparent region.
18019                applyDrawableToTransparentRegion(mBackground, region);
18020            }
18021        }
18022        return true;
18023    }
18024
18025    /**
18026     * Play a sound effect for this view.
18027     *
18028     * <p>The framework will play sound effects for some built in actions, such as
18029     * clicking, but you may wish to play these effects in your widget,
18030     * for instance, for internal navigation.
18031     *
18032     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18033     * {@link #isSoundEffectsEnabled()} is true.
18034     *
18035     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18036     */
18037    public void playSoundEffect(int soundConstant) {
18038        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18039            return;
18040        }
18041        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18042    }
18043
18044    /**
18045     * BZZZTT!!1!
18046     *
18047     * <p>Provide haptic feedback to the user for this view.
18048     *
18049     * <p>The framework will provide haptic feedback for some built in actions,
18050     * such as long presses, but you may wish to provide feedback for your
18051     * own widget.
18052     *
18053     * <p>The feedback will only be performed if
18054     * {@link #isHapticFeedbackEnabled()} is true.
18055     *
18056     * @param feedbackConstant One of the constants defined in
18057     * {@link HapticFeedbackConstants}
18058     */
18059    public boolean performHapticFeedback(int feedbackConstant) {
18060        return performHapticFeedback(feedbackConstant, 0);
18061    }
18062
18063    /**
18064     * BZZZTT!!1!
18065     *
18066     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18067     *
18068     * @param feedbackConstant One of the constants defined in
18069     * {@link HapticFeedbackConstants}
18070     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18071     */
18072    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18073        if (mAttachInfo == null) {
18074            return false;
18075        }
18076        //noinspection SimplifiableIfStatement
18077        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18078                && !isHapticFeedbackEnabled()) {
18079            return false;
18080        }
18081        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18082                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18083    }
18084
18085    /**
18086     * Request that the visibility of the status bar or other screen/window
18087     * decorations be changed.
18088     *
18089     * <p>This method is used to put the over device UI into temporary modes
18090     * where the user's attention is focused more on the application content,
18091     * by dimming or hiding surrounding system affordances.  This is typically
18092     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18093     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18094     * to be placed behind the action bar (and with these flags other system
18095     * affordances) so that smooth transitions between hiding and showing them
18096     * can be done.
18097     *
18098     * <p>Two representative examples of the use of system UI visibility is
18099     * implementing a content browsing application (like a magazine reader)
18100     * and a video playing application.
18101     *
18102     * <p>The first code shows a typical implementation of a View in a content
18103     * browsing application.  In this implementation, the application goes
18104     * into a content-oriented mode by hiding the status bar and action bar,
18105     * and putting the navigation elements into lights out mode.  The user can
18106     * then interact with content while in this mode.  Such an application should
18107     * provide an easy way for the user to toggle out of the mode (such as to
18108     * check information in the status bar or access notifications).  In the
18109     * implementation here, this is done simply by tapping on the content.
18110     *
18111     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18112     *      content}
18113     *
18114     * <p>This second code sample shows a typical implementation of a View
18115     * in a video playing application.  In this situation, while the video is
18116     * playing the application would like to go into a complete full-screen mode,
18117     * to use as much of the display as possible for the video.  When in this state
18118     * the user can not interact with the application; the system intercepts
18119     * touching on the screen to pop the UI out of full screen mode.  See
18120     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18121     *
18122     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18123     *      content}
18124     *
18125     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18126     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18127     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18128     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18129     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18130     */
18131    public void setSystemUiVisibility(int visibility) {
18132        if (visibility != mSystemUiVisibility) {
18133            mSystemUiVisibility = visibility;
18134            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18135                mParent.recomputeViewAttributes(this);
18136            }
18137        }
18138    }
18139
18140    /**
18141     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18142     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18143     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18144     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18145     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18146     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18147     */
18148    public int getSystemUiVisibility() {
18149        return mSystemUiVisibility;
18150    }
18151
18152    /**
18153     * Returns the current system UI visibility that is currently set for
18154     * the entire window.  This is the combination of the
18155     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18156     * views in the window.
18157     */
18158    public int getWindowSystemUiVisibility() {
18159        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18160    }
18161
18162    /**
18163     * Override to find out when the window's requested system UI visibility
18164     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18165     * This is different from the callbacks received through
18166     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18167     * in that this is only telling you about the local request of the window,
18168     * not the actual values applied by the system.
18169     */
18170    public void onWindowSystemUiVisibilityChanged(int visible) {
18171    }
18172
18173    /**
18174     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18175     * the view hierarchy.
18176     */
18177    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18178        onWindowSystemUiVisibilityChanged(visible);
18179    }
18180
18181    /**
18182     * Set a listener to receive callbacks when the visibility of the system bar changes.
18183     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18184     */
18185    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18186        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18187        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18188            mParent.recomputeViewAttributes(this);
18189        }
18190    }
18191
18192    /**
18193     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18194     * the view hierarchy.
18195     */
18196    public void dispatchSystemUiVisibilityChanged(int visibility) {
18197        ListenerInfo li = mListenerInfo;
18198        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18199            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18200                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18201        }
18202    }
18203
18204    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18205        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18206        if (val != mSystemUiVisibility) {
18207            setSystemUiVisibility(val);
18208            return true;
18209        }
18210        return false;
18211    }
18212
18213    /** @hide */
18214    public void setDisabledSystemUiVisibility(int flags) {
18215        if (mAttachInfo != null) {
18216            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18217                mAttachInfo.mDisabledSystemUiVisibility = flags;
18218                if (mParent != null) {
18219                    mParent.recomputeViewAttributes(this);
18220                }
18221            }
18222        }
18223    }
18224
18225    /**
18226     * Creates an image that the system displays during the drag and drop
18227     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18228     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18229     * appearance as the given View. The default also positions the center of the drag shadow
18230     * directly under the touch point. If no View is provided (the constructor with no parameters
18231     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18232     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
18233     * default is an invisible drag shadow.
18234     * <p>
18235     * You are not required to use the View you provide to the constructor as the basis of the
18236     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18237     * anything you want as the drag shadow.
18238     * </p>
18239     * <p>
18240     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18241     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18242     *  size and position of the drag shadow. It uses this data to construct a
18243     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18244     *  so that your application can draw the shadow image in the Canvas.
18245     * </p>
18246     *
18247     * <div class="special reference">
18248     * <h3>Developer Guides</h3>
18249     * <p>For a guide to implementing drag and drop features, read the
18250     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18251     * </div>
18252     */
18253    public static class DragShadowBuilder {
18254        private final WeakReference<View> mView;
18255
18256        /**
18257         * Constructs a shadow image builder based on a View. By default, the resulting drag
18258         * shadow will have the same appearance and dimensions as the View, with the touch point
18259         * over the center of the View.
18260         * @param view A View. Any View in scope can be used.
18261         */
18262        public DragShadowBuilder(View view) {
18263            mView = new WeakReference<View>(view);
18264        }
18265
18266        /**
18267         * Construct a shadow builder object with no associated View.  This
18268         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18269         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18270         * to supply the drag shadow's dimensions and appearance without
18271         * reference to any View object. If they are not overridden, then the result is an
18272         * invisible drag shadow.
18273         */
18274        public DragShadowBuilder() {
18275            mView = new WeakReference<View>(null);
18276        }
18277
18278        /**
18279         * Returns the View object that had been passed to the
18280         * {@link #View.DragShadowBuilder(View)}
18281         * constructor.  If that View parameter was {@code null} or if the
18282         * {@link #View.DragShadowBuilder()}
18283         * constructor was used to instantiate the builder object, this method will return
18284         * null.
18285         *
18286         * @return The View object associate with this builder object.
18287         */
18288        @SuppressWarnings({"JavadocReference"})
18289        final public View getView() {
18290            return mView.get();
18291        }
18292
18293        /**
18294         * Provides the metrics for the shadow image. These include the dimensions of
18295         * the shadow image, and the point within that shadow that should
18296         * be centered under the touch location while dragging.
18297         * <p>
18298         * The default implementation sets the dimensions of the shadow to be the
18299         * same as the dimensions of the View itself and centers the shadow under
18300         * the touch point.
18301         * </p>
18302         *
18303         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18304         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18305         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18306         * image.
18307         *
18308         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18309         * shadow image that should be underneath the touch point during the drag and drop
18310         * operation. Your application must set {@link android.graphics.Point#x} to the
18311         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18312         */
18313        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18314            final View view = mView.get();
18315            if (view != null) {
18316                shadowSize.set(view.getWidth(), view.getHeight());
18317                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18318            } else {
18319                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18320            }
18321        }
18322
18323        /**
18324         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18325         * based on the dimensions it received from the
18326         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18327         *
18328         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18329         */
18330        public void onDrawShadow(Canvas canvas) {
18331            final View view = mView.get();
18332            if (view != null) {
18333                view.draw(canvas);
18334            } else {
18335                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18336            }
18337        }
18338    }
18339
18340    /**
18341     * Starts a drag and drop operation. When your application calls this method, it passes a
18342     * {@link android.view.View.DragShadowBuilder} object to the system. The
18343     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18344     * to get metrics for the drag shadow, and then calls the object's
18345     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18346     * <p>
18347     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18348     *  drag events to all the View objects in your application that are currently visible. It does
18349     *  this either by calling the View object's drag listener (an implementation of
18350     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18351     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18352     *  Both are passed a {@link android.view.DragEvent} object that has a
18353     *  {@link android.view.DragEvent#getAction()} value of
18354     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18355     * </p>
18356     * <p>
18357     * Your application can invoke startDrag() on any attached View object. The View object does not
18358     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18359     * be related to the View the user selected for dragging.
18360     * </p>
18361     * @param data A {@link android.content.ClipData} object pointing to the data to be
18362     * transferred by the drag and drop operation.
18363     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18364     * drag shadow.
18365     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18366     * drop operation. This Object is put into every DragEvent object sent by the system during the
18367     * current drag.
18368     * <p>
18369     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18370     * to the target Views. For example, it can contain flags that differentiate between a
18371     * a copy operation and a move operation.
18372     * </p>
18373     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18374     * so the parameter should be set to 0.
18375     * @return {@code true} if the method completes successfully, or
18376     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18377     * do a drag, and so no drag operation is in progress.
18378     */
18379    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18380            Object myLocalState, int flags) {
18381        if (ViewDebug.DEBUG_DRAG) {
18382            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18383        }
18384        boolean okay = false;
18385
18386        Point shadowSize = new Point();
18387        Point shadowTouchPoint = new Point();
18388        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18389
18390        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18391                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18392            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18393        }
18394
18395        if (ViewDebug.DEBUG_DRAG) {
18396            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18397                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18398        }
18399        Surface surface = new Surface();
18400        try {
18401            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18402                    flags, shadowSize.x, shadowSize.y, surface);
18403            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18404                    + " surface=" + surface);
18405            if (token != null) {
18406                Canvas canvas = surface.lockCanvas(null);
18407                try {
18408                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18409                    shadowBuilder.onDrawShadow(canvas);
18410                } finally {
18411                    surface.unlockCanvasAndPost(canvas);
18412                }
18413
18414                final ViewRootImpl root = getViewRootImpl();
18415
18416                // Cache the local state object for delivery with DragEvents
18417                root.setLocalDragState(myLocalState);
18418
18419                // repurpose 'shadowSize' for the last touch point
18420                root.getLastTouchPoint(shadowSize);
18421
18422                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18423                        shadowSize.x, shadowSize.y,
18424                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18425                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18426
18427                // Off and running!  Release our local surface instance; the drag
18428                // shadow surface is now managed by the system process.
18429                surface.release();
18430            }
18431        } catch (Exception e) {
18432            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18433            surface.destroy();
18434        }
18435
18436        return okay;
18437    }
18438
18439    /**
18440     * Handles drag events sent by the system following a call to
18441     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18442     *<p>
18443     * When the system calls this method, it passes a
18444     * {@link android.view.DragEvent} object. A call to
18445     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18446     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18447     * operation.
18448     * @param event The {@link android.view.DragEvent} sent by the system.
18449     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18450     * in DragEvent, indicating the type of drag event represented by this object.
18451     * @return {@code true} if the method was successful, otherwise {@code false}.
18452     * <p>
18453     *  The method should return {@code true} in response to an action type of
18454     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18455     *  operation.
18456     * </p>
18457     * <p>
18458     *  The method should also return {@code true} in response to an action type of
18459     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18460     *  {@code false} if it didn't.
18461     * </p>
18462     */
18463    public boolean onDragEvent(DragEvent event) {
18464        return false;
18465    }
18466
18467    /**
18468     * Detects if this View is enabled and has a drag event listener.
18469     * If both are true, then it calls the drag event listener with the
18470     * {@link android.view.DragEvent} it received. If the drag event listener returns
18471     * {@code true}, then dispatchDragEvent() returns {@code true}.
18472     * <p>
18473     * For all other cases, the method calls the
18474     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18475     * method and returns its result.
18476     * </p>
18477     * <p>
18478     * This ensures that a drag event is always consumed, even if the View does not have a drag
18479     * event listener. However, if the View has a listener and the listener returns true, then
18480     * onDragEvent() is not called.
18481     * </p>
18482     */
18483    public boolean dispatchDragEvent(DragEvent event) {
18484        ListenerInfo li = mListenerInfo;
18485        //noinspection SimplifiableIfStatement
18486        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18487                && li.mOnDragListener.onDrag(this, event)) {
18488            return true;
18489        }
18490        return onDragEvent(event);
18491    }
18492
18493    boolean canAcceptDrag() {
18494        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18495    }
18496
18497    /**
18498     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18499     * it is ever exposed at all.
18500     * @hide
18501     */
18502    public void onCloseSystemDialogs(String reason) {
18503    }
18504
18505    /**
18506     * Given a Drawable whose bounds have been set to draw into this view,
18507     * update a Region being computed for
18508     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18509     * that any non-transparent parts of the Drawable are removed from the
18510     * given transparent region.
18511     *
18512     * @param dr The Drawable whose transparency is to be applied to the region.
18513     * @param region A Region holding the current transparency information,
18514     * where any parts of the region that are set are considered to be
18515     * transparent.  On return, this region will be modified to have the
18516     * transparency information reduced by the corresponding parts of the
18517     * Drawable that are not transparent.
18518     * {@hide}
18519     */
18520    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18521        if (DBG) {
18522            Log.i("View", "Getting transparent region for: " + this);
18523        }
18524        final Region r = dr.getTransparentRegion();
18525        final Rect db = dr.getBounds();
18526        final AttachInfo attachInfo = mAttachInfo;
18527        if (r != null && attachInfo != null) {
18528            final int w = getRight()-getLeft();
18529            final int h = getBottom()-getTop();
18530            if (db.left > 0) {
18531                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18532                r.op(0, 0, db.left, h, Region.Op.UNION);
18533            }
18534            if (db.right < w) {
18535                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18536                r.op(db.right, 0, w, h, Region.Op.UNION);
18537            }
18538            if (db.top > 0) {
18539                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18540                r.op(0, 0, w, db.top, Region.Op.UNION);
18541            }
18542            if (db.bottom < h) {
18543                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18544                r.op(0, db.bottom, w, h, Region.Op.UNION);
18545            }
18546            final int[] location = attachInfo.mTransparentLocation;
18547            getLocationInWindow(location);
18548            r.translate(location[0], location[1]);
18549            region.op(r, Region.Op.INTERSECT);
18550        } else {
18551            region.op(db, Region.Op.DIFFERENCE);
18552        }
18553    }
18554
18555    private void checkForLongClick(int delayOffset) {
18556        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18557            mHasPerformedLongPress = false;
18558
18559            if (mPendingCheckForLongPress == null) {
18560                mPendingCheckForLongPress = new CheckForLongPress();
18561            }
18562            mPendingCheckForLongPress.rememberWindowAttachCount();
18563            postDelayed(mPendingCheckForLongPress,
18564                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18565        }
18566    }
18567
18568    /**
18569     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18570     * LayoutInflater} class, which provides a full range of options for view inflation.
18571     *
18572     * @param context The Context object for your activity or application.
18573     * @param resource The resource ID to inflate
18574     * @param root A view group that will be the parent.  Used to properly inflate the
18575     * layout_* parameters.
18576     * @see LayoutInflater
18577     */
18578    public static View inflate(Context context, int resource, ViewGroup root) {
18579        LayoutInflater factory = LayoutInflater.from(context);
18580        return factory.inflate(resource, root);
18581    }
18582
18583    /**
18584     * Scroll the view with standard behavior for scrolling beyond the normal
18585     * content boundaries. Views that call this method should override
18586     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18587     * results of an over-scroll operation.
18588     *
18589     * Views can use this method to handle any touch or fling-based scrolling.
18590     *
18591     * @param deltaX Change in X in pixels
18592     * @param deltaY Change in Y in pixels
18593     * @param scrollX Current X scroll value in pixels before applying deltaX
18594     * @param scrollY Current Y scroll value in pixels before applying deltaY
18595     * @param scrollRangeX Maximum content scroll range along the X axis
18596     * @param scrollRangeY Maximum content scroll range along the Y axis
18597     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18598     *          along the X axis.
18599     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18600     *          along the Y axis.
18601     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18602     * @return true if scrolling was clamped to an over-scroll boundary along either
18603     *          axis, false otherwise.
18604     */
18605    @SuppressWarnings({"UnusedParameters"})
18606    protected boolean overScrollBy(int deltaX, int deltaY,
18607            int scrollX, int scrollY,
18608            int scrollRangeX, int scrollRangeY,
18609            int maxOverScrollX, int maxOverScrollY,
18610            boolean isTouchEvent) {
18611        final int overScrollMode = mOverScrollMode;
18612        final boolean canScrollHorizontal =
18613                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18614        final boolean canScrollVertical =
18615                computeVerticalScrollRange() > computeVerticalScrollExtent();
18616        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18617                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18618        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18619                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18620
18621        int newScrollX = scrollX + deltaX;
18622        if (!overScrollHorizontal) {
18623            maxOverScrollX = 0;
18624        }
18625
18626        int newScrollY = scrollY + deltaY;
18627        if (!overScrollVertical) {
18628            maxOverScrollY = 0;
18629        }
18630
18631        // Clamp values if at the limits and record
18632        final int left = -maxOverScrollX;
18633        final int right = maxOverScrollX + scrollRangeX;
18634        final int top = -maxOverScrollY;
18635        final int bottom = maxOverScrollY + scrollRangeY;
18636
18637        boolean clampedX = false;
18638        if (newScrollX > right) {
18639            newScrollX = right;
18640            clampedX = true;
18641        } else if (newScrollX < left) {
18642            newScrollX = left;
18643            clampedX = true;
18644        }
18645
18646        boolean clampedY = false;
18647        if (newScrollY > bottom) {
18648            newScrollY = bottom;
18649            clampedY = true;
18650        } else if (newScrollY < top) {
18651            newScrollY = top;
18652            clampedY = true;
18653        }
18654
18655        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18656
18657        return clampedX || clampedY;
18658    }
18659
18660    /**
18661     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18662     * respond to the results of an over-scroll operation.
18663     *
18664     * @param scrollX New X scroll value in pixels
18665     * @param scrollY New Y scroll value in pixels
18666     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18667     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18668     */
18669    protected void onOverScrolled(int scrollX, int scrollY,
18670            boolean clampedX, boolean clampedY) {
18671        // Intentionally empty.
18672    }
18673
18674    /**
18675     * Returns the over-scroll mode for this view. The result will be
18676     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18677     * (allow over-scrolling only if the view content is larger than the container),
18678     * or {@link #OVER_SCROLL_NEVER}.
18679     *
18680     * @return This view's over-scroll mode.
18681     */
18682    public int getOverScrollMode() {
18683        return mOverScrollMode;
18684    }
18685
18686    /**
18687     * Set the over-scroll mode for this view. Valid over-scroll modes are
18688     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18689     * (allow over-scrolling only if the view content is larger than the container),
18690     * or {@link #OVER_SCROLL_NEVER}.
18691     *
18692     * Setting the over-scroll mode of a view will have an effect only if the
18693     * view is capable of scrolling.
18694     *
18695     * @param overScrollMode The new over-scroll mode for this view.
18696     */
18697    public void setOverScrollMode(int overScrollMode) {
18698        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18699                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18700                overScrollMode != OVER_SCROLL_NEVER) {
18701            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18702        }
18703        mOverScrollMode = overScrollMode;
18704    }
18705
18706    /**
18707     * Enable or disable nested scrolling for this view.
18708     *
18709     * <p>If this property is set to true the view will be permitted to initiate nested
18710     * scrolling operations with a compatible parent view in the current hierarchy. If this
18711     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18712     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18713     * the nested scroll.</p>
18714     *
18715     * @param enabled true to enable nested scrolling, false to disable
18716     *
18717     * @see #isNestedScrollingEnabled()
18718     */
18719    public void setNestedScrollingEnabled(boolean enabled) {
18720        if (enabled) {
18721            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18722        } else {
18723            stopNestedScroll();
18724            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18725        }
18726    }
18727
18728    /**
18729     * Returns true if nested scrolling is enabled for this view.
18730     *
18731     * <p>If nested scrolling is enabled and this View class implementation supports it,
18732     * this view will act as a nested scrolling child view when applicable, forwarding data
18733     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18734     * parent.</p>
18735     *
18736     * @return true if nested scrolling is enabled
18737     *
18738     * @see #setNestedScrollingEnabled(boolean)
18739     */
18740    public boolean isNestedScrollingEnabled() {
18741        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18742                PFLAG3_NESTED_SCROLLING_ENABLED;
18743    }
18744
18745    /**
18746     * Begin a nestable scroll operation along the given axes.
18747     *
18748     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18749     *
18750     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18751     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18752     * In the case of touch scrolling the nested scroll will be terminated automatically in
18753     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18754     * In the event of programmatic scrolling the caller must explicitly call
18755     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18756     *
18757     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18758     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18759     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18760     *
18761     * <p>At each incremental step of the scroll the caller should invoke
18762     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18763     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18764     * parent at least partially consumed the scroll and the caller should adjust the amount it
18765     * scrolls by.</p>
18766     *
18767     * <p>After applying the remainder of the scroll delta the caller should invoke
18768     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18769     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18770     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18771     * </p>
18772     *
18773     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18774     *             {@link #SCROLL_AXIS_VERTICAL}.
18775     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18776     *         the current gesture.
18777     *
18778     * @see #stopNestedScroll()
18779     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18780     * @see #dispatchNestedScroll(int, int, int, int, int[])
18781     */
18782    public boolean startNestedScroll(int axes) {
18783        if (hasNestedScrollingParent()) {
18784            // Already in progress
18785            return true;
18786        }
18787        if (isNestedScrollingEnabled()) {
18788            ViewParent p = getParent();
18789            View child = this;
18790            while (p != null) {
18791                try {
18792                    if (p.onStartNestedScroll(child, this, axes)) {
18793                        mNestedScrollingParent = p;
18794                        p.onNestedScrollAccepted(child, this, axes);
18795                        return true;
18796                    }
18797                } catch (AbstractMethodError e) {
18798                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18799                            "method onStartNestedScroll", e);
18800                    // Allow the search upward to continue
18801                }
18802                if (p instanceof View) {
18803                    child = (View) p;
18804                }
18805                p = p.getParent();
18806            }
18807        }
18808        return false;
18809    }
18810
18811    /**
18812     * Stop a nested scroll in progress.
18813     *
18814     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18815     *
18816     * @see #startNestedScroll(int)
18817     */
18818    public void stopNestedScroll() {
18819        if (mNestedScrollingParent != null) {
18820            mNestedScrollingParent.onStopNestedScroll(this);
18821            mNestedScrollingParent = null;
18822        }
18823    }
18824
18825    /**
18826     * Returns true if this view has a nested scrolling parent.
18827     *
18828     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18829     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18830     *
18831     * @return whether this view has a nested scrolling parent
18832     */
18833    public boolean hasNestedScrollingParent() {
18834        return mNestedScrollingParent != null;
18835    }
18836
18837    /**
18838     * Dispatch one step of a nested scroll in progress.
18839     *
18840     * <p>Implementations of views that support nested scrolling should call this to report
18841     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18842     * is not currently in progress or nested scrolling is not
18843     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18844     *
18845     * <p>Compatible View implementations should also call
18846     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18847     * consuming a component of the scroll event themselves.</p>
18848     *
18849     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18850     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18851     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18852     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18853     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18854     *                       in local view coordinates of this view from before this operation
18855     *                       to after it completes. View implementations may use this to adjust
18856     *                       expected input coordinate tracking.
18857     * @return true if the event was dispatched, false if it could not be dispatched.
18858     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18859     */
18860    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18861            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18862        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18863            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18864                int startX = 0;
18865                int startY = 0;
18866                if (offsetInWindow != null) {
18867                    getLocationInWindow(offsetInWindow);
18868                    startX = offsetInWindow[0];
18869                    startY = offsetInWindow[1];
18870                }
18871
18872                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18873                        dxUnconsumed, dyUnconsumed);
18874
18875                if (offsetInWindow != null) {
18876                    getLocationInWindow(offsetInWindow);
18877                    offsetInWindow[0] -= startX;
18878                    offsetInWindow[1] -= startY;
18879                }
18880                return true;
18881            } else if (offsetInWindow != null) {
18882                // No motion, no dispatch. Keep offsetInWindow up to date.
18883                offsetInWindow[0] = 0;
18884                offsetInWindow[1] = 0;
18885            }
18886        }
18887        return false;
18888    }
18889
18890    /**
18891     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18892     *
18893     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18894     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18895     * scrolling operation to consume some or all of the scroll operation before the child view
18896     * consumes it.</p>
18897     *
18898     * @param dx Horizontal scroll distance in pixels
18899     * @param dy Vertical scroll distance in pixels
18900     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18901     *                 and consumed[1] the consumed dy.
18902     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18903     *                       in local view coordinates of this view from before this operation
18904     *                       to after it completes. View implementations may use this to adjust
18905     *                       expected input coordinate tracking.
18906     * @return true if the parent consumed some or all of the scroll delta
18907     * @see #dispatchNestedScroll(int, int, int, int, int[])
18908     */
18909    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18910        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18911            if (dx != 0 || dy != 0) {
18912                int startX = 0;
18913                int startY = 0;
18914                if (offsetInWindow != null) {
18915                    getLocationInWindow(offsetInWindow);
18916                    startX = offsetInWindow[0];
18917                    startY = offsetInWindow[1];
18918                }
18919
18920                if (consumed == null) {
18921                    if (mTempNestedScrollConsumed == null) {
18922                        mTempNestedScrollConsumed = new int[2];
18923                    }
18924                    consumed = mTempNestedScrollConsumed;
18925                }
18926                consumed[0] = 0;
18927                consumed[1] = 0;
18928                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18929
18930                if (offsetInWindow != null) {
18931                    getLocationInWindow(offsetInWindow);
18932                    offsetInWindow[0] -= startX;
18933                    offsetInWindow[1] -= startY;
18934                }
18935                return consumed[0] != 0 || consumed[1] != 0;
18936            } else if (offsetInWindow != null) {
18937                offsetInWindow[0] = 0;
18938                offsetInWindow[1] = 0;
18939            }
18940        }
18941        return false;
18942    }
18943
18944    /**
18945     * Dispatch a fling to a nested scrolling parent.
18946     *
18947     * <p>This method should be used to indicate that a nested scrolling child has detected
18948     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18949     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18950     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18951     * along a scrollable axis.</p>
18952     *
18953     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18954     * its own content, it can use this method to delegate the fling to its nested scrolling
18955     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18956     *
18957     * @param velocityX Horizontal fling velocity in pixels per second
18958     * @param velocityY Vertical fling velocity in pixels per second
18959     * @param consumed true if the child consumed the fling, false otherwise
18960     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18961     */
18962    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18963        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18964            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18965        }
18966        return false;
18967    }
18968
18969    /**
18970     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18971     *
18972     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18973     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18974     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18975     * before the child view consumes it. If this method returns <code>true</code>, a nested
18976     * parent view consumed the fling and this view should not scroll as a result.</p>
18977     *
18978     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18979     * the fling at a time. If a parent view consumed the fling this method will return false.
18980     * Custom view implementations should account for this in two ways:</p>
18981     *
18982     * <ul>
18983     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18984     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18985     *     position regardless.</li>
18986     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18987     *     even to settle back to a valid idle position.</li>
18988     * </ul>
18989     *
18990     * <p>Views should also not offer fling velocities to nested parent views along an axis
18991     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18992     * should not offer a horizontal fling velocity to its parents since scrolling along that
18993     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18994     *
18995     * @param velocityX Horizontal fling velocity in pixels per second
18996     * @param velocityY Vertical fling velocity in pixels per second
18997     * @return true if a nested scrolling parent consumed the fling
18998     */
18999    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19000        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19001            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19002        }
19003        return false;
19004    }
19005
19006    /**
19007     * Gets a scale factor that determines the distance the view should scroll
19008     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19009     * @return The vertical scroll scale factor.
19010     * @hide
19011     */
19012    protected float getVerticalScrollFactor() {
19013        if (mVerticalScrollFactor == 0) {
19014            TypedValue outValue = new TypedValue();
19015            if (!mContext.getTheme().resolveAttribute(
19016                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19017                throw new IllegalStateException(
19018                        "Expected theme to define listPreferredItemHeight.");
19019            }
19020            mVerticalScrollFactor = outValue.getDimension(
19021                    mContext.getResources().getDisplayMetrics());
19022        }
19023        return mVerticalScrollFactor;
19024    }
19025
19026    /**
19027     * Gets a scale factor that determines the distance the view should scroll
19028     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19029     * @return The horizontal scroll scale factor.
19030     * @hide
19031     */
19032    protected float getHorizontalScrollFactor() {
19033        // TODO: Should use something else.
19034        return getVerticalScrollFactor();
19035    }
19036
19037    /**
19038     * Return the value specifying the text direction or policy that was set with
19039     * {@link #setTextDirection(int)}.
19040     *
19041     * @return the defined text direction. It can be one of:
19042     *
19043     * {@link #TEXT_DIRECTION_INHERIT},
19044     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19045     * {@link #TEXT_DIRECTION_ANY_RTL},
19046     * {@link #TEXT_DIRECTION_LTR},
19047     * {@link #TEXT_DIRECTION_RTL},
19048     * {@link #TEXT_DIRECTION_LOCALE}
19049     *
19050     * @attr ref android.R.styleable#View_textDirection
19051     *
19052     * @hide
19053     */
19054    @ViewDebug.ExportedProperty(category = "text", mapping = {
19055            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19056            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19057            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19058            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19059            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19060            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19061    })
19062    public int getRawTextDirection() {
19063        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19064    }
19065
19066    /**
19067     * Set the text direction.
19068     *
19069     * @param textDirection the direction to set. Should be one of:
19070     *
19071     * {@link #TEXT_DIRECTION_INHERIT},
19072     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19073     * {@link #TEXT_DIRECTION_ANY_RTL},
19074     * {@link #TEXT_DIRECTION_LTR},
19075     * {@link #TEXT_DIRECTION_RTL},
19076     * {@link #TEXT_DIRECTION_LOCALE}
19077     *
19078     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19079     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19080     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19081     *
19082     * @attr ref android.R.styleable#View_textDirection
19083     */
19084    public void setTextDirection(int textDirection) {
19085        if (getRawTextDirection() != textDirection) {
19086            // Reset the current text direction and the resolved one
19087            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19088            resetResolvedTextDirection();
19089            // Set the new text direction
19090            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19091            // Do resolution
19092            resolveTextDirection();
19093            // Notify change
19094            onRtlPropertiesChanged(getLayoutDirection());
19095            // Refresh
19096            requestLayout();
19097            invalidate(true);
19098        }
19099    }
19100
19101    /**
19102     * Return the resolved text direction.
19103     *
19104     * @return the resolved text direction. Returns one of:
19105     *
19106     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19107     * {@link #TEXT_DIRECTION_ANY_RTL},
19108     * {@link #TEXT_DIRECTION_LTR},
19109     * {@link #TEXT_DIRECTION_RTL},
19110     * {@link #TEXT_DIRECTION_LOCALE}
19111     *
19112     * @attr ref android.R.styleable#View_textDirection
19113     */
19114    @ViewDebug.ExportedProperty(category = "text", mapping = {
19115            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19116            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19117            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19118            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19119            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19120            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19121    })
19122    public int getTextDirection() {
19123        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19124    }
19125
19126    /**
19127     * Resolve the text direction.
19128     *
19129     * @return true if resolution has been done, false otherwise.
19130     *
19131     * @hide
19132     */
19133    public boolean resolveTextDirection() {
19134        // Reset any previous text direction resolution
19135        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19136
19137        if (hasRtlSupport()) {
19138            // Set resolved text direction flag depending on text direction flag
19139            final int textDirection = getRawTextDirection();
19140            switch(textDirection) {
19141                case TEXT_DIRECTION_INHERIT:
19142                    if (!canResolveTextDirection()) {
19143                        // We cannot do the resolution if there is no parent, so use the default one
19144                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19145                        // Resolution will need to happen again later
19146                        return false;
19147                    }
19148
19149                    // Parent has not yet resolved, so we still return the default
19150                    try {
19151                        if (!mParent.isTextDirectionResolved()) {
19152                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19153                            // Resolution will need to happen again later
19154                            return false;
19155                        }
19156                    } catch (AbstractMethodError e) {
19157                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19158                                " does not fully implement ViewParent", e);
19159                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19160                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19161                        return true;
19162                    }
19163
19164                    // Set current resolved direction to the same value as the parent's one
19165                    int parentResolvedDirection;
19166                    try {
19167                        parentResolvedDirection = mParent.getTextDirection();
19168                    } catch (AbstractMethodError e) {
19169                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19170                                " does not fully implement ViewParent", e);
19171                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19172                    }
19173                    switch (parentResolvedDirection) {
19174                        case TEXT_DIRECTION_FIRST_STRONG:
19175                        case TEXT_DIRECTION_ANY_RTL:
19176                        case TEXT_DIRECTION_LTR:
19177                        case TEXT_DIRECTION_RTL:
19178                        case TEXT_DIRECTION_LOCALE:
19179                            mPrivateFlags2 |=
19180                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19181                            break;
19182                        default:
19183                            // Default resolved direction is "first strong" heuristic
19184                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19185                    }
19186                    break;
19187                case TEXT_DIRECTION_FIRST_STRONG:
19188                case TEXT_DIRECTION_ANY_RTL:
19189                case TEXT_DIRECTION_LTR:
19190                case TEXT_DIRECTION_RTL:
19191                case TEXT_DIRECTION_LOCALE:
19192                    // Resolved direction is the same as text direction
19193                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19194                    break;
19195                default:
19196                    // Default resolved direction is "first strong" heuristic
19197                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19198            }
19199        } else {
19200            // Default resolved direction is "first strong" heuristic
19201            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19202        }
19203
19204        // Set to resolved
19205        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19206        return true;
19207    }
19208
19209    /**
19210     * Check if text direction resolution can be done.
19211     *
19212     * @return true if text direction resolution can be done otherwise return false.
19213     */
19214    public boolean canResolveTextDirection() {
19215        switch (getRawTextDirection()) {
19216            case TEXT_DIRECTION_INHERIT:
19217                if (mParent != null) {
19218                    try {
19219                        return mParent.canResolveTextDirection();
19220                    } catch (AbstractMethodError e) {
19221                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19222                                " does not fully implement ViewParent", e);
19223                    }
19224                }
19225                return false;
19226
19227            default:
19228                return true;
19229        }
19230    }
19231
19232    /**
19233     * Reset resolved text direction. Text direction will be resolved during a call to
19234     * {@link #onMeasure(int, int)}.
19235     *
19236     * @hide
19237     */
19238    public void resetResolvedTextDirection() {
19239        // Reset any previous text direction resolution
19240        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19241        // Set to default value
19242        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19243    }
19244
19245    /**
19246     * @return true if text direction is inherited.
19247     *
19248     * @hide
19249     */
19250    public boolean isTextDirectionInherited() {
19251        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19252    }
19253
19254    /**
19255     * @return true if text direction is resolved.
19256     */
19257    public boolean isTextDirectionResolved() {
19258        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19259    }
19260
19261    /**
19262     * Return the value specifying the text alignment or policy that was set with
19263     * {@link #setTextAlignment(int)}.
19264     *
19265     * @return the defined text alignment. It can be one of:
19266     *
19267     * {@link #TEXT_ALIGNMENT_INHERIT},
19268     * {@link #TEXT_ALIGNMENT_GRAVITY},
19269     * {@link #TEXT_ALIGNMENT_CENTER},
19270     * {@link #TEXT_ALIGNMENT_TEXT_START},
19271     * {@link #TEXT_ALIGNMENT_TEXT_END},
19272     * {@link #TEXT_ALIGNMENT_VIEW_START},
19273     * {@link #TEXT_ALIGNMENT_VIEW_END}
19274     *
19275     * @attr ref android.R.styleable#View_textAlignment
19276     *
19277     * @hide
19278     */
19279    @ViewDebug.ExportedProperty(category = "text", mapping = {
19280            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19281            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19282            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19283            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19284            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19285            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19286            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19287    })
19288    @TextAlignment
19289    public int getRawTextAlignment() {
19290        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19291    }
19292
19293    /**
19294     * Set the text alignment.
19295     *
19296     * @param textAlignment The text alignment to set. Should be one of
19297     *
19298     * {@link #TEXT_ALIGNMENT_INHERIT},
19299     * {@link #TEXT_ALIGNMENT_GRAVITY},
19300     * {@link #TEXT_ALIGNMENT_CENTER},
19301     * {@link #TEXT_ALIGNMENT_TEXT_START},
19302     * {@link #TEXT_ALIGNMENT_TEXT_END},
19303     * {@link #TEXT_ALIGNMENT_VIEW_START},
19304     * {@link #TEXT_ALIGNMENT_VIEW_END}
19305     *
19306     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19307     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19308     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19309     *
19310     * @attr ref android.R.styleable#View_textAlignment
19311     */
19312    public void setTextAlignment(@TextAlignment int textAlignment) {
19313        if (textAlignment != getRawTextAlignment()) {
19314            // Reset the current and resolved text alignment
19315            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19316            resetResolvedTextAlignment();
19317            // Set the new text alignment
19318            mPrivateFlags2 |=
19319                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19320            // Do resolution
19321            resolveTextAlignment();
19322            // Notify change
19323            onRtlPropertiesChanged(getLayoutDirection());
19324            // Refresh
19325            requestLayout();
19326            invalidate(true);
19327        }
19328    }
19329
19330    /**
19331     * Return the resolved text alignment.
19332     *
19333     * @return the resolved text alignment. Returns one of:
19334     *
19335     * {@link #TEXT_ALIGNMENT_GRAVITY},
19336     * {@link #TEXT_ALIGNMENT_CENTER},
19337     * {@link #TEXT_ALIGNMENT_TEXT_START},
19338     * {@link #TEXT_ALIGNMENT_TEXT_END},
19339     * {@link #TEXT_ALIGNMENT_VIEW_START},
19340     * {@link #TEXT_ALIGNMENT_VIEW_END}
19341     *
19342     * @attr ref android.R.styleable#View_textAlignment
19343     */
19344    @ViewDebug.ExportedProperty(category = "text", mapping = {
19345            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19346            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19347            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19348            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19349            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19350            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19351            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19352    })
19353    @TextAlignment
19354    public int getTextAlignment() {
19355        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19356                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19357    }
19358
19359    /**
19360     * Resolve the text alignment.
19361     *
19362     * @return true if resolution has been done, false otherwise.
19363     *
19364     * @hide
19365     */
19366    public boolean resolveTextAlignment() {
19367        // Reset any previous text alignment resolution
19368        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19369
19370        if (hasRtlSupport()) {
19371            // Set resolved text alignment flag depending on text alignment flag
19372            final int textAlignment = getRawTextAlignment();
19373            switch (textAlignment) {
19374                case TEXT_ALIGNMENT_INHERIT:
19375                    // Check if we can resolve the text alignment
19376                    if (!canResolveTextAlignment()) {
19377                        // We cannot do the resolution if there is no parent so use the default
19378                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19379                        // Resolution will need to happen again later
19380                        return false;
19381                    }
19382
19383                    // Parent has not yet resolved, so we still return the default
19384                    try {
19385                        if (!mParent.isTextAlignmentResolved()) {
19386                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19387                            // Resolution will need to happen again later
19388                            return false;
19389                        }
19390                    } catch (AbstractMethodError e) {
19391                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19392                                " does not fully implement ViewParent", e);
19393                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19394                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19395                        return true;
19396                    }
19397
19398                    int parentResolvedTextAlignment;
19399                    try {
19400                        parentResolvedTextAlignment = mParent.getTextAlignment();
19401                    } catch (AbstractMethodError e) {
19402                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19403                                " does not fully implement ViewParent", e);
19404                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19405                    }
19406                    switch (parentResolvedTextAlignment) {
19407                        case TEXT_ALIGNMENT_GRAVITY:
19408                        case TEXT_ALIGNMENT_TEXT_START:
19409                        case TEXT_ALIGNMENT_TEXT_END:
19410                        case TEXT_ALIGNMENT_CENTER:
19411                        case TEXT_ALIGNMENT_VIEW_START:
19412                        case TEXT_ALIGNMENT_VIEW_END:
19413                            // Resolved text alignment is the same as the parent resolved
19414                            // text alignment
19415                            mPrivateFlags2 |=
19416                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19417                            break;
19418                        default:
19419                            // Use default resolved text alignment
19420                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19421                    }
19422                    break;
19423                case TEXT_ALIGNMENT_GRAVITY:
19424                case TEXT_ALIGNMENT_TEXT_START:
19425                case TEXT_ALIGNMENT_TEXT_END:
19426                case TEXT_ALIGNMENT_CENTER:
19427                case TEXT_ALIGNMENT_VIEW_START:
19428                case TEXT_ALIGNMENT_VIEW_END:
19429                    // Resolved text alignment is the same as text alignment
19430                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19431                    break;
19432                default:
19433                    // Use default resolved text alignment
19434                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19435            }
19436        } else {
19437            // Use default resolved text alignment
19438            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19439        }
19440
19441        // Set the resolved
19442        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19443        return true;
19444    }
19445
19446    /**
19447     * Check if text alignment resolution can be done.
19448     *
19449     * @return true if text alignment resolution can be done otherwise return false.
19450     */
19451    public boolean canResolveTextAlignment() {
19452        switch (getRawTextAlignment()) {
19453            case TEXT_DIRECTION_INHERIT:
19454                if (mParent != null) {
19455                    try {
19456                        return mParent.canResolveTextAlignment();
19457                    } catch (AbstractMethodError e) {
19458                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19459                                " does not fully implement ViewParent", e);
19460                    }
19461                }
19462                return false;
19463
19464            default:
19465                return true;
19466        }
19467    }
19468
19469    /**
19470     * Reset resolved text alignment. Text alignment will be resolved during a call to
19471     * {@link #onMeasure(int, int)}.
19472     *
19473     * @hide
19474     */
19475    public void resetResolvedTextAlignment() {
19476        // Reset any previous text alignment resolution
19477        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19478        // Set to default
19479        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19480    }
19481
19482    /**
19483     * @return true if text alignment is inherited.
19484     *
19485     * @hide
19486     */
19487    public boolean isTextAlignmentInherited() {
19488        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19489    }
19490
19491    /**
19492     * @return true if text alignment is resolved.
19493     */
19494    public boolean isTextAlignmentResolved() {
19495        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19496    }
19497
19498    /**
19499     * Generate a value suitable for use in {@link #setId(int)}.
19500     * This value will not collide with ID values generated at build time by aapt for R.id.
19501     *
19502     * @return a generated ID value
19503     */
19504    public static int generateViewId() {
19505        for (;;) {
19506            final int result = sNextGeneratedId.get();
19507            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19508            int newValue = result + 1;
19509            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19510            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19511                return result;
19512            }
19513        }
19514    }
19515
19516    /**
19517     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19518     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19519     *                           a normal View or a ViewGroup with
19520     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19521     * @hide
19522     */
19523    public void captureTransitioningViews(List<View> transitioningViews) {
19524        if (getVisibility() == View.VISIBLE) {
19525            transitioningViews.add(this);
19526        }
19527    }
19528
19529    /**
19530     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19531     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19532     * @hide
19533     */
19534    public void findNamedViews(Map<String, View> namedElements) {
19535        if (getVisibility() == VISIBLE || mGhostView != null) {
19536            String transitionName = getTransitionName();
19537            if (transitionName != null) {
19538                namedElements.put(transitionName, this);
19539            }
19540        }
19541    }
19542
19543    //
19544    // Properties
19545    //
19546    /**
19547     * A Property wrapper around the <code>alpha</code> functionality handled by the
19548     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19549     */
19550    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19551        @Override
19552        public void setValue(View object, float value) {
19553            object.setAlpha(value);
19554        }
19555
19556        @Override
19557        public Float get(View object) {
19558            return object.getAlpha();
19559        }
19560    };
19561
19562    /**
19563     * A Property wrapper around the <code>translationX</code> functionality handled by the
19564     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19565     */
19566    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19567        @Override
19568        public void setValue(View object, float value) {
19569            object.setTranslationX(value);
19570        }
19571
19572                @Override
19573        public Float get(View object) {
19574            return object.getTranslationX();
19575        }
19576    };
19577
19578    /**
19579     * A Property wrapper around the <code>translationY</code> functionality handled by the
19580     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19581     */
19582    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19583        @Override
19584        public void setValue(View object, float value) {
19585            object.setTranslationY(value);
19586        }
19587
19588        @Override
19589        public Float get(View object) {
19590            return object.getTranslationY();
19591        }
19592    };
19593
19594    /**
19595     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19596     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19597     */
19598    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19599        @Override
19600        public void setValue(View object, float value) {
19601            object.setTranslationZ(value);
19602        }
19603
19604        @Override
19605        public Float get(View object) {
19606            return object.getTranslationZ();
19607        }
19608    };
19609
19610    /**
19611     * A Property wrapper around the <code>x</code> functionality handled by the
19612     * {@link View#setX(float)} and {@link View#getX()} methods.
19613     */
19614    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19615        @Override
19616        public void setValue(View object, float value) {
19617            object.setX(value);
19618        }
19619
19620        @Override
19621        public Float get(View object) {
19622            return object.getX();
19623        }
19624    };
19625
19626    /**
19627     * A Property wrapper around the <code>y</code> functionality handled by the
19628     * {@link View#setY(float)} and {@link View#getY()} methods.
19629     */
19630    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19631        @Override
19632        public void setValue(View object, float value) {
19633            object.setY(value);
19634        }
19635
19636        @Override
19637        public Float get(View object) {
19638            return object.getY();
19639        }
19640    };
19641
19642    /**
19643     * A Property wrapper around the <code>z</code> functionality handled by the
19644     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19645     */
19646    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19647        @Override
19648        public void setValue(View object, float value) {
19649            object.setZ(value);
19650        }
19651
19652        @Override
19653        public Float get(View object) {
19654            return object.getZ();
19655        }
19656    };
19657
19658    /**
19659     * A Property wrapper around the <code>rotation</code> functionality handled by the
19660     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19661     */
19662    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19663        @Override
19664        public void setValue(View object, float value) {
19665            object.setRotation(value);
19666        }
19667
19668        @Override
19669        public Float get(View object) {
19670            return object.getRotation();
19671        }
19672    };
19673
19674    /**
19675     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19676     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19677     */
19678    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19679        @Override
19680        public void setValue(View object, float value) {
19681            object.setRotationX(value);
19682        }
19683
19684        @Override
19685        public Float get(View object) {
19686            return object.getRotationX();
19687        }
19688    };
19689
19690    /**
19691     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19692     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19693     */
19694    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19695        @Override
19696        public void setValue(View object, float value) {
19697            object.setRotationY(value);
19698        }
19699
19700        @Override
19701        public Float get(View object) {
19702            return object.getRotationY();
19703        }
19704    };
19705
19706    /**
19707     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19708     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19709     */
19710    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19711        @Override
19712        public void setValue(View object, float value) {
19713            object.setScaleX(value);
19714        }
19715
19716        @Override
19717        public Float get(View object) {
19718            return object.getScaleX();
19719        }
19720    };
19721
19722    /**
19723     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19724     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19725     */
19726    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19727        @Override
19728        public void setValue(View object, float value) {
19729            object.setScaleY(value);
19730        }
19731
19732        @Override
19733        public Float get(View object) {
19734            return object.getScaleY();
19735        }
19736    };
19737
19738    /**
19739     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19740     * Each MeasureSpec represents a requirement for either the width or the height.
19741     * A MeasureSpec is comprised of a size and a mode. There are three possible
19742     * modes:
19743     * <dl>
19744     * <dt>UNSPECIFIED</dt>
19745     * <dd>
19746     * The parent has not imposed any constraint on the child. It can be whatever size
19747     * it wants.
19748     * </dd>
19749     *
19750     * <dt>EXACTLY</dt>
19751     * <dd>
19752     * The parent has determined an exact size for the child. The child is going to be
19753     * given those bounds regardless of how big it wants to be.
19754     * </dd>
19755     *
19756     * <dt>AT_MOST</dt>
19757     * <dd>
19758     * The child can be as large as it wants up to the specified size.
19759     * </dd>
19760     * </dl>
19761     *
19762     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19763     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19764     */
19765    public static class MeasureSpec {
19766        private static final int MODE_SHIFT = 30;
19767        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19768
19769        /**
19770         * Measure specification mode: The parent has not imposed any constraint
19771         * on the child. It can be whatever size it wants.
19772         */
19773        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19774
19775        /**
19776         * Measure specification mode: The parent has determined an exact size
19777         * for the child. The child is going to be given those bounds regardless
19778         * of how big it wants to be.
19779         */
19780        public static final int EXACTLY     = 1 << MODE_SHIFT;
19781
19782        /**
19783         * Measure specification mode: The child can be as large as it wants up
19784         * to the specified size.
19785         */
19786        public static final int AT_MOST     = 2 << MODE_SHIFT;
19787
19788        /**
19789         * Creates a measure specification based on the supplied size and mode.
19790         *
19791         * The mode must always be one of the following:
19792         * <ul>
19793         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19794         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19795         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19796         * </ul>
19797         *
19798         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19799         * implementation was such that the order of arguments did not matter
19800         * and overflow in either value could impact the resulting MeasureSpec.
19801         * {@link android.widget.RelativeLayout} was affected by this bug.
19802         * Apps targeting API levels greater than 17 will get the fixed, more strict
19803         * behavior.</p>
19804         *
19805         * @param size the size of the measure specification
19806         * @param mode the mode of the measure specification
19807         * @return the measure specification based on size and mode
19808         */
19809        public static int makeMeasureSpec(int size, int mode) {
19810            if (sUseBrokenMakeMeasureSpec) {
19811                return size + mode;
19812            } else {
19813                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19814            }
19815        }
19816
19817        /**
19818         * Extracts the mode from the supplied measure specification.
19819         *
19820         * @param measureSpec the measure specification to extract the mode from
19821         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19822         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19823         *         {@link android.view.View.MeasureSpec#EXACTLY}
19824         */
19825        public static int getMode(int measureSpec) {
19826            return (measureSpec & MODE_MASK);
19827        }
19828
19829        /**
19830         * Extracts the size from the supplied measure specification.
19831         *
19832         * @param measureSpec the measure specification to extract the size from
19833         * @return the size in pixels defined in the supplied measure specification
19834         */
19835        public static int getSize(int measureSpec) {
19836            return (measureSpec & ~MODE_MASK);
19837        }
19838
19839        static int adjust(int measureSpec, int delta) {
19840            final int mode = getMode(measureSpec);
19841            if (mode == UNSPECIFIED) {
19842                // No need to adjust size for UNSPECIFIED mode.
19843                return makeMeasureSpec(0, UNSPECIFIED);
19844            }
19845            int size = getSize(measureSpec) + delta;
19846            if (size < 0) {
19847                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19848                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19849                size = 0;
19850            }
19851            return makeMeasureSpec(size, mode);
19852        }
19853
19854        /**
19855         * Returns a String representation of the specified measure
19856         * specification.
19857         *
19858         * @param measureSpec the measure specification to convert to a String
19859         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19860         */
19861        public static String toString(int measureSpec) {
19862            int mode = getMode(measureSpec);
19863            int size = getSize(measureSpec);
19864
19865            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19866
19867            if (mode == UNSPECIFIED)
19868                sb.append("UNSPECIFIED ");
19869            else if (mode == EXACTLY)
19870                sb.append("EXACTLY ");
19871            else if (mode == AT_MOST)
19872                sb.append("AT_MOST ");
19873            else
19874                sb.append(mode).append(" ");
19875
19876            sb.append(size);
19877            return sb.toString();
19878        }
19879    }
19880
19881    private final class CheckForLongPress implements Runnable {
19882        private int mOriginalWindowAttachCount;
19883
19884        @Override
19885        public void run() {
19886            if (isPressed() && (mParent != null)
19887                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19888                if (performLongClick()) {
19889                    mHasPerformedLongPress = true;
19890                }
19891            }
19892        }
19893
19894        public void rememberWindowAttachCount() {
19895            mOriginalWindowAttachCount = mWindowAttachCount;
19896        }
19897    }
19898
19899    private final class CheckForTap implements Runnable {
19900        public float x;
19901        public float y;
19902
19903        @Override
19904        public void run() {
19905            mPrivateFlags &= ~PFLAG_PREPRESSED;
19906            setPressed(true, x, y);
19907            checkForLongClick(ViewConfiguration.getTapTimeout());
19908        }
19909    }
19910
19911    private final class PerformClick implements Runnable {
19912        @Override
19913        public void run() {
19914            performClick();
19915        }
19916    }
19917
19918    /** @hide */
19919    public void hackTurnOffWindowResizeAnim(boolean off) {
19920        mAttachInfo.mTurnOffWindowResizeAnim = off;
19921    }
19922
19923    /**
19924     * This method returns a ViewPropertyAnimator object, which can be used to animate
19925     * specific properties on this View.
19926     *
19927     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19928     */
19929    public ViewPropertyAnimator animate() {
19930        if (mAnimator == null) {
19931            mAnimator = new ViewPropertyAnimator(this);
19932        }
19933        return mAnimator;
19934    }
19935
19936    /**
19937     * Sets the name of the View to be used to identify Views in Transitions.
19938     * Names should be unique in the View hierarchy.
19939     *
19940     * @param transitionName The name of the View to uniquely identify it for Transitions.
19941     */
19942    public final void setTransitionName(String transitionName) {
19943        mTransitionName = transitionName;
19944    }
19945
19946    /**
19947     * Returns the name of the View to be used to identify Views in Transitions.
19948     * Names should be unique in the View hierarchy.
19949     *
19950     * <p>This returns null if the View has not been given a name.</p>
19951     *
19952     * @return The name used of the View to be used to identify Views in Transitions or null
19953     * if no name has been given.
19954     */
19955    @ViewDebug.ExportedProperty
19956    public String getTransitionName() {
19957        return mTransitionName;
19958    }
19959
19960    /**
19961     * Interface definition for a callback to be invoked when a hardware key event is
19962     * dispatched to this view. The callback will be invoked before the key event is
19963     * given to the view. This is only useful for hardware keyboards; a software input
19964     * method has no obligation to trigger this listener.
19965     */
19966    public interface OnKeyListener {
19967        /**
19968         * Called when a hardware key is dispatched to a view. This allows listeners to
19969         * get a chance to respond before the target view.
19970         * <p>Key presses in software keyboards will generally NOT trigger this method,
19971         * although some may elect to do so in some situations. Do not assume a
19972         * software input method has to be key-based; even if it is, it may use key presses
19973         * in a different way than you expect, so there is no way to reliably catch soft
19974         * input key presses.
19975         *
19976         * @param v The view the key has been dispatched to.
19977         * @param keyCode The code for the physical key that was pressed
19978         * @param event The KeyEvent object containing full information about
19979         *        the event.
19980         * @return True if the listener has consumed the event, false otherwise.
19981         */
19982        boolean onKey(View v, int keyCode, KeyEvent event);
19983    }
19984
19985    /**
19986     * Interface definition for a callback to be invoked when a touch event is
19987     * dispatched to this view. The callback will be invoked before the touch
19988     * event is given to the view.
19989     */
19990    public interface OnTouchListener {
19991        /**
19992         * Called when a touch event is dispatched to a view. This allows listeners to
19993         * get a chance to respond before the target view.
19994         *
19995         * @param v The view the touch event has been dispatched to.
19996         * @param event The MotionEvent object containing full information about
19997         *        the event.
19998         * @return True if the listener has consumed the event, false otherwise.
19999         */
20000        boolean onTouch(View v, MotionEvent event);
20001    }
20002
20003    /**
20004     * Interface definition for a callback to be invoked when a hover event is
20005     * dispatched to this view. The callback will be invoked before the hover
20006     * event is given to the view.
20007     */
20008    public interface OnHoverListener {
20009        /**
20010         * Called when a hover event is dispatched to a view. This allows listeners to
20011         * get a chance to respond before the target view.
20012         *
20013         * @param v The view the hover event has been dispatched to.
20014         * @param event The MotionEvent object containing full information about
20015         *        the event.
20016         * @return True if the listener has consumed the event, false otherwise.
20017         */
20018        boolean onHover(View v, MotionEvent event);
20019    }
20020
20021    /**
20022     * Interface definition for a callback to be invoked when a generic motion event is
20023     * dispatched to this view. The callback will be invoked before the generic motion
20024     * event is given to the view.
20025     */
20026    public interface OnGenericMotionListener {
20027        /**
20028         * Called when a generic motion event is dispatched to a view. This allows listeners to
20029         * get a chance to respond before the target view.
20030         *
20031         * @param v The view the generic motion event has been dispatched to.
20032         * @param event The MotionEvent object containing full information about
20033         *        the event.
20034         * @return True if the listener has consumed the event, false otherwise.
20035         */
20036        boolean onGenericMotion(View v, MotionEvent event);
20037    }
20038
20039    /**
20040     * Interface definition for a callback to be invoked when a view has been clicked and held.
20041     */
20042    public interface OnLongClickListener {
20043        /**
20044         * Called when a view has been clicked and held.
20045         *
20046         * @param v The view that was clicked and held.
20047         *
20048         * @return true if the callback consumed the long click, false otherwise.
20049         */
20050        boolean onLongClick(View v);
20051    }
20052
20053    /**
20054     * Interface definition for a callback to be invoked when a drag is being dispatched
20055     * to this view.  The callback will be invoked before the hosting view's own
20056     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20057     * onDrag(event) behavior, it should return 'false' from this callback.
20058     *
20059     * <div class="special reference">
20060     * <h3>Developer Guides</h3>
20061     * <p>For a guide to implementing drag and drop features, read the
20062     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20063     * </div>
20064     */
20065    public interface OnDragListener {
20066        /**
20067         * Called when a drag event is dispatched to a view. This allows listeners
20068         * to get a chance to override base View behavior.
20069         *
20070         * @param v The View that received the drag event.
20071         * @param event The {@link android.view.DragEvent} object for the drag event.
20072         * @return {@code true} if the drag event was handled successfully, or {@code false}
20073         * if the drag event was not handled. Note that {@code false} will trigger the View
20074         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20075         */
20076        boolean onDrag(View v, DragEvent event);
20077    }
20078
20079    /**
20080     * Interface definition for a callback to be invoked when the focus state of
20081     * a view changed.
20082     */
20083    public interface OnFocusChangeListener {
20084        /**
20085         * Called when the focus state of a view has changed.
20086         *
20087         * @param v The view whose state has changed.
20088         * @param hasFocus The new focus state of v.
20089         */
20090        void onFocusChange(View v, boolean hasFocus);
20091    }
20092
20093    /**
20094     * Interface definition for a callback to be invoked when a view is clicked.
20095     */
20096    public interface OnClickListener {
20097        /**
20098         * Called when a view has been clicked.
20099         *
20100         * @param v The view that was clicked.
20101         */
20102        void onClick(View v);
20103    }
20104
20105    /**
20106     * Interface definition for a callback to be invoked when the context menu
20107     * for this view is being built.
20108     */
20109    public interface OnCreateContextMenuListener {
20110        /**
20111         * Called when the context menu for this view is being built. It is not
20112         * safe to hold onto the menu after this method returns.
20113         *
20114         * @param menu The context menu that is being built
20115         * @param v The view for which the context menu is being built
20116         * @param menuInfo Extra information about the item for which the
20117         *            context menu should be shown. This information will vary
20118         *            depending on the class of v.
20119         */
20120        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20121    }
20122
20123    /**
20124     * Interface definition for a callback to be invoked when the status bar changes
20125     * visibility.  This reports <strong>global</strong> changes to the system UI
20126     * state, not what the application is requesting.
20127     *
20128     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20129     */
20130    public interface OnSystemUiVisibilityChangeListener {
20131        /**
20132         * Called when the status bar changes visibility because of a call to
20133         * {@link View#setSystemUiVisibility(int)}.
20134         *
20135         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20136         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20137         * This tells you the <strong>global</strong> state of these UI visibility
20138         * flags, not what your app is currently applying.
20139         */
20140        public void onSystemUiVisibilityChange(int visibility);
20141    }
20142
20143    /**
20144     * Interface definition for a callback to be invoked when this view is attached
20145     * or detached from its window.
20146     */
20147    public interface OnAttachStateChangeListener {
20148        /**
20149         * Called when the view is attached to a window.
20150         * @param v The view that was attached
20151         */
20152        public void onViewAttachedToWindow(View v);
20153        /**
20154         * Called when the view is detached from a window.
20155         * @param v The view that was detached
20156         */
20157        public void onViewDetachedFromWindow(View v);
20158    }
20159
20160    /**
20161     * Listener for applying window insets on a view in a custom way.
20162     *
20163     * <p>Apps may choose to implement this interface if they want to apply custom policy
20164     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20165     * is set, its
20166     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20167     * method will be called instead of the View's own
20168     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20169     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20170     * the View's normal behavior as part of its own.</p>
20171     */
20172    public interface OnApplyWindowInsetsListener {
20173        /**
20174         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20175         * on a View, this listener method will be called instead of the view's own
20176         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20177         *
20178         * @param v The view applying window insets
20179         * @param insets The insets to apply
20180         * @return The insets supplied, minus any insets that were consumed
20181         */
20182        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20183    }
20184
20185    private final class UnsetPressedState implements Runnable {
20186        @Override
20187        public void run() {
20188            setPressed(false);
20189        }
20190    }
20191
20192    /**
20193     * Base class for derived classes that want to save and restore their own
20194     * state in {@link android.view.View#onSaveInstanceState()}.
20195     */
20196    public static class BaseSavedState extends AbsSavedState {
20197        /**
20198         * Constructor used when reading from a parcel. Reads the state of the superclass.
20199         *
20200         * @param source
20201         */
20202        public BaseSavedState(Parcel source) {
20203            super(source);
20204        }
20205
20206        /**
20207         * Constructor called by derived classes when creating their SavedState objects
20208         *
20209         * @param superState The state of the superclass of this view
20210         */
20211        public BaseSavedState(Parcelable superState) {
20212            super(superState);
20213        }
20214
20215        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20216                new Parcelable.Creator<BaseSavedState>() {
20217            public BaseSavedState createFromParcel(Parcel in) {
20218                return new BaseSavedState(in);
20219            }
20220
20221            public BaseSavedState[] newArray(int size) {
20222                return new BaseSavedState[size];
20223            }
20224        };
20225    }
20226
20227    /**
20228     * A set of information given to a view when it is attached to its parent
20229     * window.
20230     */
20231    final static class AttachInfo {
20232        interface Callbacks {
20233            void playSoundEffect(int effectId);
20234            boolean performHapticFeedback(int effectId, boolean always);
20235        }
20236
20237        /**
20238         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20239         * to a Handler. This class contains the target (View) to invalidate and
20240         * the coordinates of the dirty rectangle.
20241         *
20242         * For performance purposes, this class also implements a pool of up to
20243         * POOL_LIMIT objects that get reused. This reduces memory allocations
20244         * whenever possible.
20245         */
20246        static class InvalidateInfo {
20247            private static final int POOL_LIMIT = 10;
20248
20249            private static final SynchronizedPool<InvalidateInfo> sPool =
20250                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20251
20252            View target;
20253
20254            int left;
20255            int top;
20256            int right;
20257            int bottom;
20258
20259            public static InvalidateInfo obtain() {
20260                InvalidateInfo instance = sPool.acquire();
20261                return (instance != null) ? instance : new InvalidateInfo();
20262            }
20263
20264            public void recycle() {
20265                target = null;
20266                sPool.release(this);
20267            }
20268        }
20269
20270        final IWindowSession mSession;
20271
20272        final IWindow mWindow;
20273
20274        final IBinder mWindowToken;
20275
20276        final Display mDisplay;
20277
20278        final Callbacks mRootCallbacks;
20279
20280        IWindowId mIWindowId;
20281        WindowId mWindowId;
20282
20283        /**
20284         * The top view of the hierarchy.
20285         */
20286        View mRootView;
20287
20288        IBinder mPanelParentWindowToken;
20289
20290        boolean mHardwareAccelerated;
20291        boolean mHardwareAccelerationRequested;
20292        HardwareRenderer mHardwareRenderer;
20293        List<RenderNode> mPendingAnimatingRenderNodes;
20294
20295        /**
20296         * The state of the display to which the window is attached, as reported
20297         * by {@link Display#getState()}.  Note that the display state constants
20298         * declared by {@link Display} do not exactly line up with the screen state
20299         * constants declared by {@link View} (there are more display states than
20300         * screen states).
20301         */
20302        int mDisplayState = Display.STATE_UNKNOWN;
20303
20304        /**
20305         * Scale factor used by the compatibility mode
20306         */
20307        float mApplicationScale;
20308
20309        /**
20310         * Indicates whether the application is in compatibility mode
20311         */
20312        boolean mScalingRequired;
20313
20314        /**
20315         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20316         */
20317        boolean mTurnOffWindowResizeAnim;
20318
20319        /**
20320         * Left position of this view's window
20321         */
20322        int mWindowLeft;
20323
20324        /**
20325         * Top position of this view's window
20326         */
20327        int mWindowTop;
20328
20329        /**
20330         * Indicates whether views need to use 32-bit drawing caches
20331         */
20332        boolean mUse32BitDrawingCache;
20333
20334        /**
20335         * For windows that are full-screen but using insets to layout inside
20336         * of the screen areas, these are the current insets to appear inside
20337         * the overscan area of the display.
20338         */
20339        final Rect mOverscanInsets = new Rect();
20340
20341        /**
20342         * For windows that are full-screen but using insets to layout inside
20343         * of the screen decorations, these are the current insets for the
20344         * content of the window.
20345         */
20346        final Rect mContentInsets = new Rect();
20347
20348        /**
20349         * For windows that are full-screen but using insets to layout inside
20350         * of the screen decorations, these are the current insets for the
20351         * actual visible parts of the window.
20352         */
20353        final Rect mVisibleInsets = new Rect();
20354
20355        /**
20356         * For windows that are full-screen but using insets to layout inside
20357         * of the screen decorations, these are the current insets for the
20358         * stable system windows.
20359         */
20360        final Rect mStableInsets = new Rect();
20361
20362        /**
20363         * The internal insets given by this window.  This value is
20364         * supplied by the client (through
20365         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20366         * be given to the window manager when changed to be used in laying
20367         * out windows behind it.
20368         */
20369        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20370                = new ViewTreeObserver.InternalInsetsInfo();
20371
20372        /**
20373         * Set to true when mGivenInternalInsets is non-empty.
20374         */
20375        boolean mHasNonEmptyGivenInternalInsets;
20376
20377        /**
20378         * All views in the window's hierarchy that serve as scroll containers,
20379         * used to determine if the window can be resized or must be panned
20380         * to adjust for a soft input area.
20381         */
20382        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20383
20384        final KeyEvent.DispatcherState mKeyDispatchState
20385                = new KeyEvent.DispatcherState();
20386
20387        /**
20388         * Indicates whether the view's window currently has the focus.
20389         */
20390        boolean mHasWindowFocus;
20391
20392        /**
20393         * The current visibility of the window.
20394         */
20395        int mWindowVisibility;
20396
20397        /**
20398         * Indicates the time at which drawing started to occur.
20399         */
20400        long mDrawingTime;
20401
20402        /**
20403         * Indicates whether or not ignoring the DIRTY_MASK flags.
20404         */
20405        boolean mIgnoreDirtyState;
20406
20407        /**
20408         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20409         * to avoid clearing that flag prematurely.
20410         */
20411        boolean mSetIgnoreDirtyState = false;
20412
20413        /**
20414         * Indicates whether the view's window is currently in touch mode.
20415         */
20416        boolean mInTouchMode;
20417
20418        /**
20419         * Indicates whether the view has requested unbuffered input dispatching for the current
20420         * event stream.
20421         */
20422        boolean mUnbufferedDispatchRequested;
20423
20424        /**
20425         * Indicates that ViewAncestor should trigger a global layout change
20426         * the next time it performs a traversal
20427         */
20428        boolean mRecomputeGlobalAttributes;
20429
20430        /**
20431         * Always report new attributes at next traversal.
20432         */
20433        boolean mForceReportNewAttributes;
20434
20435        /**
20436         * Set during a traveral if any views want to keep the screen on.
20437         */
20438        boolean mKeepScreenOn;
20439
20440        /**
20441         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20442         */
20443        int mSystemUiVisibility;
20444
20445        /**
20446         * Hack to force certain system UI visibility flags to be cleared.
20447         */
20448        int mDisabledSystemUiVisibility;
20449
20450        /**
20451         * Last global system UI visibility reported by the window manager.
20452         */
20453        int mGlobalSystemUiVisibility;
20454
20455        /**
20456         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20457         * attached.
20458         */
20459        boolean mHasSystemUiListeners;
20460
20461        /**
20462         * Set if the window has requested to extend into the overscan region
20463         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20464         */
20465        boolean mOverscanRequested;
20466
20467        /**
20468         * Set if the visibility of any views has changed.
20469         */
20470        boolean mViewVisibilityChanged;
20471
20472        /**
20473         * Set to true if a view has been scrolled.
20474         */
20475        boolean mViewScrollChanged;
20476
20477        /**
20478         * Set to true if high contrast mode enabled
20479         */
20480        boolean mHighContrastText;
20481
20482        /**
20483         * Global to the view hierarchy used as a temporary for dealing with
20484         * x/y points in the transparent region computations.
20485         */
20486        final int[] mTransparentLocation = new int[2];
20487
20488        /**
20489         * Global to the view hierarchy used as a temporary for dealing with
20490         * x/y points in the ViewGroup.invalidateChild implementation.
20491         */
20492        final int[] mInvalidateChildLocation = new int[2];
20493
20494        /**
20495         * Global to the view hierarchy used as a temporary for dealng with
20496         * computing absolute on-screen location.
20497         */
20498        final int[] mTmpLocation = new int[2];
20499
20500        /**
20501         * Global to the view hierarchy used as a temporary for dealing with
20502         * x/y location when view is transformed.
20503         */
20504        final float[] mTmpTransformLocation = new float[2];
20505
20506        /**
20507         * The view tree observer used to dispatch global events like
20508         * layout, pre-draw, touch mode change, etc.
20509         */
20510        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20511
20512        /**
20513         * A Canvas used by the view hierarchy to perform bitmap caching.
20514         */
20515        Canvas mCanvas;
20516
20517        /**
20518         * The view root impl.
20519         */
20520        final ViewRootImpl mViewRootImpl;
20521
20522        /**
20523         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20524         * handler can be used to pump events in the UI events queue.
20525         */
20526        final Handler mHandler;
20527
20528        /**
20529         * Temporary for use in computing invalidate rectangles while
20530         * calling up the hierarchy.
20531         */
20532        final Rect mTmpInvalRect = new Rect();
20533
20534        /**
20535         * Temporary for use in computing hit areas with transformed views
20536         */
20537        final RectF mTmpTransformRect = new RectF();
20538
20539        /**
20540         * Temporary for use in computing hit areas with transformed views
20541         */
20542        final RectF mTmpTransformRect1 = new RectF();
20543
20544        /**
20545         * Temporary list of rectanges.
20546         */
20547        final List<RectF> mTmpRectList = new ArrayList<>();
20548
20549        /**
20550         * Temporary for use in transforming invalidation rect
20551         */
20552        final Matrix mTmpMatrix = new Matrix();
20553
20554        /**
20555         * Temporary for use in transforming invalidation rect
20556         */
20557        final Transformation mTmpTransformation = new Transformation();
20558
20559        /**
20560         * Temporary for use in querying outlines from OutlineProviders
20561         */
20562        final Outline mTmpOutline = new Outline();
20563
20564        /**
20565         * Temporary list for use in collecting focusable descendents of a view.
20566         */
20567        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20568
20569        /**
20570         * The id of the window for accessibility purposes.
20571         */
20572        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20573
20574        /**
20575         * Flags related to accessibility processing.
20576         *
20577         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20578         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20579         */
20580        int mAccessibilityFetchFlags;
20581
20582        /**
20583         * The drawable for highlighting accessibility focus.
20584         */
20585        Drawable mAccessibilityFocusDrawable;
20586
20587        /**
20588         * Show where the margins, bounds and layout bounds are for each view.
20589         */
20590        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20591
20592        /**
20593         * Point used to compute visible regions.
20594         */
20595        final Point mPoint = new Point();
20596
20597        /**
20598         * Used to track which View originated a requestLayout() call, used when
20599         * requestLayout() is called during layout.
20600         */
20601        View mViewRequestingLayout;
20602
20603        /**
20604         * Creates a new set of attachment information with the specified
20605         * events handler and thread.
20606         *
20607         * @param handler the events handler the view must use
20608         */
20609        AttachInfo(IWindowSession session, IWindow window, Display display,
20610                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20611            mSession = session;
20612            mWindow = window;
20613            mWindowToken = window.asBinder();
20614            mDisplay = display;
20615            mViewRootImpl = viewRootImpl;
20616            mHandler = handler;
20617            mRootCallbacks = effectPlayer;
20618        }
20619    }
20620
20621    /**
20622     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20623     * is supported. This avoids keeping too many unused fields in most
20624     * instances of View.</p>
20625     */
20626    private static class ScrollabilityCache implements Runnable {
20627
20628        /**
20629         * Scrollbars are not visible
20630         */
20631        public static final int OFF = 0;
20632
20633        /**
20634         * Scrollbars are visible
20635         */
20636        public static final int ON = 1;
20637
20638        /**
20639         * Scrollbars are fading away
20640         */
20641        public static final int FADING = 2;
20642
20643        public boolean fadeScrollBars;
20644
20645        public int fadingEdgeLength;
20646        public int scrollBarDefaultDelayBeforeFade;
20647        public int scrollBarFadeDuration;
20648
20649        public int scrollBarSize;
20650        public ScrollBarDrawable scrollBar;
20651        public float[] interpolatorValues;
20652        public View host;
20653
20654        public final Paint paint;
20655        public final Matrix matrix;
20656        public Shader shader;
20657
20658        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20659
20660        private static final float[] OPAQUE = { 255 };
20661        private static final float[] TRANSPARENT = { 0.0f };
20662
20663        /**
20664         * When fading should start. This time moves into the future every time
20665         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20666         */
20667        public long fadeStartTime;
20668
20669
20670        /**
20671         * The current state of the scrollbars: ON, OFF, or FADING
20672         */
20673        public int state = OFF;
20674
20675        private int mLastColor;
20676
20677        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20678            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20679            scrollBarSize = configuration.getScaledScrollBarSize();
20680            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20681            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20682
20683            paint = new Paint();
20684            matrix = new Matrix();
20685            // use use a height of 1, and then wack the matrix each time we
20686            // actually use it.
20687            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20688            paint.setShader(shader);
20689            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20690
20691            this.host = host;
20692        }
20693
20694        public void setFadeColor(int color) {
20695            if (color != mLastColor) {
20696                mLastColor = color;
20697
20698                if (color != 0) {
20699                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20700                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20701                    paint.setShader(shader);
20702                    // Restore the default transfer mode (src_over)
20703                    paint.setXfermode(null);
20704                } else {
20705                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20706                    paint.setShader(shader);
20707                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20708                }
20709            }
20710        }
20711
20712        public void run() {
20713            long now = AnimationUtils.currentAnimationTimeMillis();
20714            if (now >= fadeStartTime) {
20715
20716                // the animation fades the scrollbars out by changing
20717                // the opacity (alpha) from fully opaque to fully
20718                // transparent
20719                int nextFrame = (int) now;
20720                int framesCount = 0;
20721
20722                Interpolator interpolator = scrollBarInterpolator;
20723
20724                // Start opaque
20725                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20726
20727                // End transparent
20728                nextFrame += scrollBarFadeDuration;
20729                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20730
20731                state = FADING;
20732
20733                // Kick off the fade animation
20734                host.invalidate(true);
20735            }
20736        }
20737    }
20738
20739    /**
20740     * Resuable callback for sending
20741     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20742     */
20743    private class SendViewScrolledAccessibilityEvent implements Runnable {
20744        public volatile boolean mIsPending;
20745
20746        public void run() {
20747            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20748            mIsPending = false;
20749        }
20750    }
20751
20752    /**
20753     * <p>
20754     * This class represents a delegate that can be registered in a {@link View}
20755     * to enhance accessibility support via composition rather via inheritance.
20756     * It is specifically targeted to widget developers that extend basic View
20757     * classes i.e. classes in package android.view, that would like their
20758     * applications to be backwards compatible.
20759     * </p>
20760     * <div class="special reference">
20761     * <h3>Developer Guides</h3>
20762     * <p>For more information about making applications accessible, read the
20763     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20764     * developer guide.</p>
20765     * </div>
20766     * <p>
20767     * A scenario in which a developer would like to use an accessibility delegate
20768     * is overriding a method introduced in a later API version then the minimal API
20769     * version supported by the application. For example, the method
20770     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20771     * in API version 4 when the accessibility APIs were first introduced. If a
20772     * developer would like his application to run on API version 4 devices (assuming
20773     * all other APIs used by the application are version 4 or lower) and take advantage
20774     * of this method, instead of overriding the method which would break the application's
20775     * backwards compatibility, he can override the corresponding method in this
20776     * delegate and register the delegate in the target View if the API version of
20777     * the system is high enough i.e. the API version is same or higher to the API
20778     * version that introduced
20779     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20780     * </p>
20781     * <p>
20782     * Here is an example implementation:
20783     * </p>
20784     * <code><pre><p>
20785     * if (Build.VERSION.SDK_INT >= 14) {
20786     *     // If the API version is equal of higher than the version in
20787     *     // which onInitializeAccessibilityNodeInfo was introduced we
20788     *     // register a delegate with a customized implementation.
20789     *     View view = findViewById(R.id.view_id);
20790     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20791     *         public void onInitializeAccessibilityNodeInfo(View host,
20792     *                 AccessibilityNodeInfo info) {
20793     *             // Let the default implementation populate the info.
20794     *             super.onInitializeAccessibilityNodeInfo(host, info);
20795     *             // Set some other information.
20796     *             info.setEnabled(host.isEnabled());
20797     *         }
20798     *     });
20799     * }
20800     * </code></pre></p>
20801     * <p>
20802     * This delegate contains methods that correspond to the accessibility methods
20803     * in View. If a delegate has been specified the implementation in View hands
20804     * off handling to the corresponding method in this delegate. The default
20805     * implementation the delegate methods behaves exactly as the corresponding
20806     * method in View for the case of no accessibility delegate been set. Hence,
20807     * to customize the behavior of a View method, clients can override only the
20808     * corresponding delegate method without altering the behavior of the rest
20809     * accessibility related methods of the host view.
20810     * </p>
20811     */
20812    public static class AccessibilityDelegate {
20813
20814        /**
20815         * Sends an accessibility event of the given type. If accessibility is not
20816         * enabled this method has no effect.
20817         * <p>
20818         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20819         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20820         * been set.
20821         * </p>
20822         *
20823         * @param host The View hosting the delegate.
20824         * @param eventType The type of the event to send.
20825         *
20826         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20827         */
20828        public void sendAccessibilityEvent(View host, int eventType) {
20829            host.sendAccessibilityEventInternal(eventType);
20830        }
20831
20832        /**
20833         * Performs the specified accessibility action on the view. For
20834         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20835         * <p>
20836         * The default implementation behaves as
20837         * {@link View#performAccessibilityAction(int, Bundle)
20838         *  View#performAccessibilityAction(int, Bundle)} for the case of
20839         *  no accessibility delegate been set.
20840         * </p>
20841         *
20842         * @param action The action to perform.
20843         * @return Whether the action was performed.
20844         *
20845         * @see View#performAccessibilityAction(int, Bundle)
20846         *      View#performAccessibilityAction(int, Bundle)
20847         */
20848        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20849            return host.performAccessibilityActionInternal(action, args);
20850        }
20851
20852        /**
20853         * Sends an accessibility event. This method behaves exactly as
20854         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20855         * empty {@link AccessibilityEvent} and does not perform a check whether
20856         * accessibility is enabled.
20857         * <p>
20858         * The default implementation behaves as
20859         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20860         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20861         * the case of no accessibility delegate been set.
20862         * </p>
20863         *
20864         * @param host The View hosting the delegate.
20865         * @param event The event to send.
20866         *
20867         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20868         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20869         */
20870        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20871            host.sendAccessibilityEventUncheckedInternal(event);
20872        }
20873
20874        /**
20875         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20876         * to its children for adding their text content to the event.
20877         * <p>
20878         * The default implementation behaves as
20879         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20880         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20881         * the case of no accessibility delegate been set.
20882         * </p>
20883         *
20884         * @param host The View hosting the delegate.
20885         * @param event The event.
20886         * @return True if the event population was completed.
20887         *
20888         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20889         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20890         */
20891        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20892            return host.dispatchPopulateAccessibilityEventInternal(event);
20893        }
20894
20895        /**
20896         * Gives a chance to the host View to populate the accessibility event with its
20897         * text content.
20898         * <p>
20899         * The default implementation behaves as
20900         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20901         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20902         * the case of no accessibility delegate been set.
20903         * </p>
20904         *
20905         * @param host The View hosting the delegate.
20906         * @param event The accessibility event which to populate.
20907         *
20908         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20909         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20910         */
20911        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20912            host.onPopulateAccessibilityEventInternal(event);
20913        }
20914
20915        /**
20916         * Initializes an {@link AccessibilityEvent} with information about the
20917         * the host View which is the event source.
20918         * <p>
20919         * The default implementation behaves as
20920         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20921         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20922         * the case of no accessibility delegate been set.
20923         * </p>
20924         *
20925         * @param host The View hosting the delegate.
20926         * @param event The event to initialize.
20927         *
20928         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20929         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20930         */
20931        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20932            host.onInitializeAccessibilityEventInternal(event);
20933        }
20934
20935        /**
20936         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20937         * <p>
20938         * The default implementation behaves as
20939         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20940         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20941         * the case of no accessibility delegate been set.
20942         * </p>
20943         *
20944         * @param host The View hosting the delegate.
20945         * @param info The instance to initialize.
20946         *
20947         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20948         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20949         */
20950        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20951            host.onInitializeAccessibilityNodeInfoInternal(info);
20952        }
20953
20954        /**
20955         * Called when a child of the host View has requested sending an
20956         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20957         * to augment the event.
20958         * <p>
20959         * The default implementation behaves as
20960         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20961         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20962         * the case of no accessibility delegate been set.
20963         * </p>
20964         *
20965         * @param host The View hosting the delegate.
20966         * @param child The child which requests sending the event.
20967         * @param event The event to be sent.
20968         * @return True if the event should be sent
20969         *
20970         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20971         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20972         */
20973        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20974                AccessibilityEvent event) {
20975            return host.onRequestSendAccessibilityEventInternal(child, event);
20976        }
20977
20978        /**
20979         * Gets the provider for managing a virtual view hierarchy rooted at this View
20980         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20981         * that explore the window content.
20982         * <p>
20983         * The default implementation behaves as
20984         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20985         * the case of no accessibility delegate been set.
20986         * </p>
20987         *
20988         * @return The provider.
20989         *
20990         * @see AccessibilityNodeProvider
20991         */
20992        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20993            return null;
20994        }
20995
20996        /**
20997         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20998         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20999         * This method is responsible for obtaining an accessibility node info from a
21000         * pool of reusable instances and calling
21001         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21002         * view to initialize the former.
21003         * <p>
21004         * <strong>Note:</strong> The client is responsible for recycling the obtained
21005         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21006         * creation.
21007         * </p>
21008         * <p>
21009         * The default implementation behaves as
21010         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21011         * the case of no accessibility delegate been set.
21012         * </p>
21013         * @return A populated {@link AccessibilityNodeInfo}.
21014         *
21015         * @see AccessibilityNodeInfo
21016         *
21017         * @hide
21018         */
21019        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21020            return host.createAccessibilityNodeInfoInternal();
21021        }
21022    }
21023
21024    private class MatchIdPredicate implements Predicate<View> {
21025        public int mId;
21026
21027        @Override
21028        public boolean apply(View view) {
21029            return (view.mID == mId);
21030        }
21031    }
21032
21033    private class MatchLabelForPredicate implements Predicate<View> {
21034        private int mLabeledId;
21035
21036        @Override
21037        public boolean apply(View view) {
21038            return (view.mLabelForId == mLabeledId);
21039        }
21040    }
21041
21042    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21043        private int mChangeTypes = 0;
21044        private boolean mPosted;
21045        private boolean mPostedWithDelay;
21046        private long mLastEventTimeMillis;
21047
21048        @Override
21049        public void run() {
21050            mPosted = false;
21051            mPostedWithDelay = false;
21052            mLastEventTimeMillis = SystemClock.uptimeMillis();
21053            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21054                final AccessibilityEvent event = AccessibilityEvent.obtain();
21055                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21056                event.setContentChangeTypes(mChangeTypes);
21057                sendAccessibilityEventUnchecked(event);
21058            }
21059            mChangeTypes = 0;
21060        }
21061
21062        public void runOrPost(int changeType) {
21063            mChangeTypes |= changeType;
21064
21065            // If this is a live region or the child of a live region, collect
21066            // all events from this frame and send them on the next frame.
21067            if (inLiveRegion()) {
21068                // If we're already posted with a delay, remove that.
21069                if (mPostedWithDelay) {
21070                    removeCallbacks(this);
21071                    mPostedWithDelay = false;
21072                }
21073                // Only post if we're not already posted.
21074                if (!mPosted) {
21075                    post(this);
21076                    mPosted = true;
21077                }
21078                return;
21079            }
21080
21081            if (mPosted) {
21082                return;
21083            }
21084
21085            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21086            final long minEventIntevalMillis =
21087                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21088            if (timeSinceLastMillis >= minEventIntevalMillis) {
21089                removeCallbacks(this);
21090                run();
21091            } else {
21092                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21093                mPostedWithDelay = true;
21094            }
21095        }
21096    }
21097
21098    private boolean inLiveRegion() {
21099        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21100            return true;
21101        }
21102
21103        ViewParent parent = getParent();
21104        while (parent instanceof View) {
21105            if (((View) parent).getAccessibilityLiveRegion()
21106                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21107                return true;
21108            }
21109            parent = parent.getParent();
21110        }
21111
21112        return false;
21113    }
21114
21115    /**
21116     * Dump all private flags in readable format, useful for documentation and
21117     * sanity checking.
21118     */
21119    private static void dumpFlags() {
21120        final HashMap<String, String> found = Maps.newHashMap();
21121        try {
21122            for (Field field : View.class.getDeclaredFields()) {
21123                final int modifiers = field.getModifiers();
21124                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21125                    if (field.getType().equals(int.class)) {
21126                        final int value = field.getInt(null);
21127                        dumpFlag(found, field.getName(), value);
21128                    } else if (field.getType().equals(int[].class)) {
21129                        final int[] values = (int[]) field.get(null);
21130                        for (int i = 0; i < values.length; i++) {
21131                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21132                        }
21133                    }
21134                }
21135            }
21136        } catch (IllegalAccessException e) {
21137            throw new RuntimeException(e);
21138        }
21139
21140        final ArrayList<String> keys = Lists.newArrayList();
21141        keys.addAll(found.keySet());
21142        Collections.sort(keys);
21143        for (String key : keys) {
21144            Log.d(VIEW_LOG_TAG, found.get(key));
21145        }
21146    }
21147
21148    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21149        // Sort flags by prefix, then by bits, always keeping unique keys
21150        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21151        final int prefix = name.indexOf('_');
21152        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21153        final String output = bits + " " + name;
21154        found.put(key, output);
21155    }
21156}
21157