View.java revision 80a2f50315e9b219de7e0dc92afad625cbb88f1a
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.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.LayoutRes;
28import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.Size;
31import android.annotation.UiThread;
32import android.content.ClipData;
33import android.content.Context;
34import android.content.ContextWrapper;
35import android.content.Intent;
36import android.content.res.ColorStateList;
37import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Insets;
43import android.graphics.Interpolator;
44import android.graphics.LinearGradient;
45import android.graphics.Matrix;
46import android.graphics.Outline;
47import android.graphics.Paint;
48import android.graphics.PixelFormat;
49import android.graphics.Point;
50import android.graphics.PorterDuff;
51import android.graphics.PorterDuffXfermode;
52import android.graphics.Rect;
53import android.graphics.RectF;
54import android.graphics.Region;
55import android.graphics.Shader;
56import android.graphics.drawable.ColorDrawable;
57import android.graphics.drawable.Drawable;
58import android.hardware.display.DisplayManagerGlobal;
59import android.os.Bundle;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Parcel;
63import android.os.Parcelable;
64import android.os.RemoteException;
65import android.os.SystemClock;
66import android.os.SystemProperties;
67import android.os.Trace;
68import android.text.TextUtils;
69import android.util.AttributeSet;
70import android.util.FloatProperty;
71import android.util.LayoutDirection;
72import android.util.Log;
73import android.util.LongSparseLongArray;
74import android.util.Pools.SynchronizedPool;
75import android.util.Property;
76import android.util.SparseArray;
77import android.util.StateSet;
78import android.util.SuperNotCalledException;
79import android.util.TypedValue;
80import android.view.ContextMenu.ContextMenuInfo;
81import android.view.AccessibilityIterators.TextSegmentIterator;
82import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
83import android.view.AccessibilityIterators.WordTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.accessibility.AccessibilityEvent;
86import android.view.accessibility.AccessibilityEventSource;
87import android.view.accessibility.AccessibilityManager;
88import android.view.accessibility.AccessibilityNodeInfo;
89import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
90import android.view.accessibility.AccessibilityNodeProvider;
91import android.view.animation.Animation;
92import android.view.animation.AnimationUtils;
93import android.view.animation.Transformation;
94import android.view.inputmethod.EditorInfo;
95import android.view.inputmethod.InputConnection;
96import android.view.inputmethod.InputMethodManager;
97import android.widget.Checkable;
98import android.widget.ScrollBarDrawable;
99
100import static android.os.Build.VERSION_CODES.*;
101import static java.lang.Math.max;
102
103import com.android.internal.R;
104import com.android.internal.util.Predicate;
105import com.android.internal.view.menu.MenuBuilder;
106import com.google.android.collect.Lists;
107import com.google.android.collect.Maps;
108
109import java.lang.annotation.Retention;
110import java.lang.annotation.RetentionPolicy;
111import java.lang.ref.WeakReference;
112import java.lang.reflect.Field;
113import java.lang.reflect.InvocationTargetException;
114import java.lang.reflect.Method;
115import java.lang.reflect.Modifier;
116import java.util.ArrayList;
117import java.util.Arrays;
118import java.util.Collections;
119import java.util.HashMap;
120import java.util.List;
121import java.util.Locale;
122import java.util.Map;
123import java.util.concurrent.CopyOnWriteArrayList;
124import java.util.concurrent.atomic.AtomicInteger;
125
126/**
127 * <p>
128 * This class represents the basic building block for user interface components. A View
129 * occupies a rectangular area on the screen and is responsible for drawing and
130 * event handling. View is the base class for <em>widgets</em>, which are
131 * used to create interactive UI components (buttons, text fields, etc.). The
132 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
133 * are invisible containers that hold other Views (or other ViewGroups) and define
134 * their layout properties.
135 * </p>
136 *
137 * <div class="special reference">
138 * <h3>Developer Guides</h3>
139 * <p>For information about using this class to develop your application's user interface,
140 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
141 * </div>
142 *
143 * <a name="Using"></a>
144 * <h3>Using Views</h3>
145 * <p>
146 * All of the views in a window are arranged in a single tree. You can add views
147 * either from code or by specifying a tree of views in one or more XML layout
148 * files. There are many specialized subclasses of views that act as controls or
149 * are capable of displaying text, images, or other content.
150 * </p>
151 * <p>
152 * Once you have created a tree of views, there are typically a few types of
153 * common operations you may wish to perform:
154 * <ul>
155 * <li><strong>Set properties:</strong> for example setting the text of a
156 * {@link android.widget.TextView}. The available properties and the methods
157 * that set them will vary among the different subclasses of views. Note that
158 * properties that are known at build time can be set in the XML layout
159 * files.</li>
160 * <li><strong>Set focus:</strong> The framework will handled moving focus in
161 * response to user input. To force focus to a specific view, call
162 * {@link #requestFocus}.</li>
163 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
164 * that will be notified when something interesting happens to the view. For
165 * example, all views will let you set a listener to be notified when the view
166 * gains or loses focus. You can register such a listener using
167 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
168 * Other view subclasses offer more specialized listeners. For example, a Button
169 * exposes a listener to notify clients when the button is clicked.</li>
170 * <li><strong>Set visibility:</strong> You can hide or show views using
171 * {@link #setVisibility(int)}.</li>
172 * </ul>
173 * </p>
174 * <p><em>
175 * Note: The Android framework is responsible for measuring, laying out and
176 * drawing views. You should not call methods that perform these actions on
177 * views yourself unless you are actually implementing a
178 * {@link android.view.ViewGroup}.
179 * </em></p>
180 *
181 * <a name="Lifecycle"></a>
182 * <h3>Implementing a Custom View</h3>
183 *
184 * <p>
185 * To implement a custom view, you will usually begin by providing overrides for
186 * some of the standard methods that the framework calls on all views. You do
187 * not need to override all of these methods. In fact, you can start by just
188 * overriding {@link #onDraw(android.graphics.Canvas)}.
189 * <table border="2" width="85%" align="center" cellpadding="5">
190 *     <thead>
191 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
192 *     </thead>
193 *
194 *     <tbody>
195 *     <tr>
196 *         <td rowspan="2">Creation</td>
197 *         <td>Constructors</td>
198 *         <td>There is a form of the constructor that are called when the view
199 *         is created from code and a form that is called when the view is
200 *         inflated from a layout file. The second form should parse and apply
201 *         any attributes defined in the layout file.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onFinishInflate()}</code></td>
206 *         <td>Called after a view and all of its children has been inflated
207 *         from XML.</td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td rowspan="3">Layout</td>
212 *         <td><code>{@link #onMeasure(int, int)}</code></td>
213 *         <td>Called to determine the size requirements for this view and all
214 *         of its children.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
219 *         <td>Called when this view should assign a size and position to all
220 *         of its children.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
225 *         <td>Called when the size of this view has changed.
226 *         </td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td>Drawing</td>
231 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
232 *         <td>Called when the view should render its content.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td rowspan="4">Event processing</td>
238 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
239 *         <td>Called when a new hardware key event occurs.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
244 *         <td>Called when a hardware key up event occurs.
245 *         </td>
246 *     </tr>
247 *     <tr>
248 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
249 *         <td>Called when a trackball motion event occurs.
250 *         </td>
251 *     </tr>
252 *     <tr>
253 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
254 *         <td>Called when a touch screen motion event occurs.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="2">Focus</td>
260 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
261 *         <td>Called when the view gains or loses focus.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
267 *         <td>Called when the window containing the view gains or loses focus.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td rowspan="3">Attaching</td>
273 *         <td><code>{@link #onAttachedToWindow()}</code></td>
274 *         <td>Called when the view is attached to a window.
275 *         </td>
276 *     </tr>
277 *
278 *     <tr>
279 *         <td><code>{@link #onDetachedFromWindow}</code></td>
280 *         <td>Called when the view is detached from its window.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
286 *         <td>Called when the visibility of the window containing the view
287 *         has changed.
288 *         </td>
289 *     </tr>
290 *     </tbody>
291 *
292 * </table>
293 * </p>
294 *
295 * <a name="IDs"></a>
296 * <h3>IDs</h3>
297 * Views may have an integer id associated with them. These ids are typically
298 * assigned in the layout XML files, and are used to find specific views within
299 * the view tree. A common pattern is to:
300 * <ul>
301 * <li>Define a Button in the layout file and assign it a unique ID.
302 * <pre>
303 * &lt;Button
304 *     android:id="@+id/my_button"
305 *     android:layout_width="wrap_content"
306 *     android:layout_height="wrap_content"
307 *     android:text="@string/my_button_text"/&gt;
308 * </pre></li>
309 * <li>From the onCreate method of an Activity, find the Button
310 * <pre class="prettyprint">
311 *      Button myButton = (Button) findViewById(R.id.my_button);
312 * </pre></li>
313 * </ul>
314 * <p>
315 * View IDs need not be unique throughout the tree, but it is good practice to
316 * ensure that they are at least unique within the part of the tree you are
317 * searching.
318 * </p>
319 *
320 * <a name="Position"></a>
321 * <h3>Position</h3>
322 * <p>
323 * The geometry of a view is that of a rectangle. A view has a location,
324 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
325 * two dimensions, expressed as a width and a height. The unit for location
326 * and dimensions is the pixel.
327 * </p>
328 *
329 * <p>
330 * It is possible to retrieve the location of a view by invoking the methods
331 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
332 * coordinate of the rectangle representing the view. The latter returns the
333 * top, or Y, coordinate of the rectangle representing the view. These methods
334 * both return the location of the view relative to its parent. For instance,
335 * when getLeft() returns 20, that means the view is located 20 pixels to the
336 * right of the left edge of its direct parent.
337 * </p>
338 *
339 * <p>
340 * In addition, several convenience methods are offered to avoid unnecessary
341 * computations, namely {@link #getRight()} and {@link #getBottom()}.
342 * These methods return the coordinates of the right and bottom edges of the
343 * rectangle representing the view. For instance, calling {@link #getRight()}
344 * is similar to the following computation: <code>getLeft() + getWidth()</code>
345 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
346 * </p>
347 *
348 * <a name="SizePaddingMargins"></a>
349 * <h3>Size, padding and margins</h3>
350 * <p>
351 * The size of a view is expressed with a width and a height. A view actually
352 * possess two pairs of width and height values.
353 * </p>
354 *
355 * <p>
356 * The first pair is known as <em>measured width</em> and
357 * <em>measured height</em>. These dimensions define how big a view wants to be
358 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
359 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
360 * and {@link #getMeasuredHeight()}.
361 * </p>
362 *
363 * <p>
364 * The second pair is simply known as <em>width</em> and <em>height</em>, or
365 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
366 * dimensions define the actual size of the view on screen, at drawing time and
367 * after layout. These values may, but do not have to, be different from the
368 * measured width and height. The width and height can be obtained by calling
369 * {@link #getWidth()} and {@link #getHeight()}.
370 * </p>
371 *
372 * <p>
373 * To measure its dimensions, a view takes into account its padding. The padding
374 * is expressed in pixels for the left, top, right and bottom parts of the view.
375 * Padding can be used to offset the content of the view by a specific amount of
376 * pixels. For instance, a left padding of 2 will push the view's content by
377 * 2 pixels to the right of the left edge. Padding can be set using the
378 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
379 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
380 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
381 * {@link #getPaddingEnd()}.
382 * </p>
383 *
384 * <p>
385 * Even though a view can define a padding, it does not provide any support for
386 * margins. However, view groups provide such a support. Refer to
387 * {@link android.view.ViewGroup} and
388 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
389 * </p>
390 *
391 * <a name="Layout"></a>
392 * <h3>Layout</h3>
393 * <p>
394 * Layout is a two pass process: a measure pass and a layout pass. The measuring
395 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
396 * of the view tree. Each view pushes dimension specifications down the tree
397 * during the recursion. At the end of the measure pass, every view has stored
398 * its measurements. The second pass happens in
399 * {@link #layout(int,int,int,int)} and is also top-down. During
400 * this pass each parent is responsible for positioning all of its children
401 * using the sizes computed in the measure pass.
402 * </p>
403 *
404 * <p>
405 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
406 * {@link #getMeasuredHeight()} values must be set, along with those for all of
407 * that view's descendants. A view's measured width and measured height values
408 * must respect the constraints imposed by the view's parents. This guarantees
409 * that at the end of the measure pass, all parents accept all of their
410 * children's measurements. A parent view may call measure() more than once on
411 * its children. For example, the parent may measure each child once with
412 * unspecified dimensions to find out how big they want to be, then call
413 * measure() on them again with actual numbers if the sum of all the children's
414 * unconstrained sizes is too big or too small.
415 * </p>
416 *
417 * <p>
418 * The measure pass uses two classes to communicate dimensions. The
419 * {@link MeasureSpec} class is used by views to tell their parents how they
420 * want to be measured and positioned. The base LayoutParams class just
421 * describes how big the view wants to be for both width and height. For each
422 * dimension, it can specify one of:
423 * <ul>
424 * <li> an exact number
425 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
426 * (minus padding)
427 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
428 * enclose its content (plus padding).
429 * </ul>
430 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
431 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
432 * an X and Y value.
433 * </p>
434 *
435 * <p>
436 * MeasureSpecs are used to push requirements down the tree from parent to
437 * child. A MeasureSpec can be in one of three modes:
438 * <ul>
439 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
440 * of a child view. For example, a LinearLayout may call measure() on its child
441 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
442 * tall the child view wants to be given a width of 240 pixels.
443 * <li>EXACTLY: This is used by the parent to impose an exact size on the
444 * child. The child must use this size, and guarantee that all of its
445 * descendants will fit within this size.
446 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
447 * child. The child must guarantee that it and all of its descendants will fit
448 * within this size.
449 * </ul>
450 * </p>
451 *
452 * <p>
453 * To initiate a layout, call {@link #requestLayout}. This method is typically
454 * called by a view on itself when it believes that is can no longer fit within
455 * its current bounds.
456 * </p>
457 *
458 * <a name="Drawing"></a>
459 * <h3>Drawing</h3>
460 * <p>
461 * Drawing is handled by walking the tree and recording the drawing commands of
462 * any View that needs to update. After this, the drawing commands of the
463 * entire tree are issued to screen, clipped to the newly damaged area.
464 * </p>
465 *
466 * <p>
467 * The tree is largely recorded and drawn in order, with parents drawn before
468 * (i.e., behind) their children, with siblings drawn in the order they appear
469 * in the tree. If you set a background drawable for a View, then the View will
470 * draw it before calling back to its <code>onDraw()</code> method. The child
471 * drawing order can be overridden with
472 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
473 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
474 * </p>
475 *
476 * <p>
477 * To force a view to draw, call {@link #invalidate()}.
478 * </p>
479 *
480 * <a name="EventHandlingThreading"></a>
481 * <h3>Event Handling and Threading</h3>
482 * <p>
483 * The basic cycle of a view is as follows:
484 * <ol>
485 * <li>An event comes in and is dispatched to the appropriate view. The view
486 * handles the event and notifies any listeners.</li>
487 * <li>If in the course of processing the event, the view's bounds may need
488 * to be changed, the view will call {@link #requestLayout()}.</li>
489 * <li>Similarly, if in the course of processing the event the view's appearance
490 * may need to be changed, the view will call {@link #invalidate()}.</li>
491 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
492 * the framework will take care of measuring, laying out, and drawing the tree
493 * as appropriate.</li>
494 * </ol>
495 * </p>
496 *
497 * <p><em>Note: The entire view tree is single threaded. You must always be on
498 * the UI thread when calling any method on any view.</em>
499 * If you are doing work on other threads and want to update the state of a view
500 * from that thread, you should use a {@link Handler}.
501 * </p>
502 *
503 * <a name="FocusHandling"></a>
504 * <h3>Focus Handling</h3>
505 * <p>
506 * The framework will handle routine focus movement in response to user input.
507 * This includes changing the focus as views are removed or hidden, or as new
508 * views become available. Views indicate their willingness to take focus
509 * through the {@link #isFocusable} method. To change whether a view can take
510 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
511 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
512 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
513 * </p>
514 * <p>
515 * Focus movement is based on an algorithm which finds the nearest neighbor in a
516 * given direction. In rare cases, the default algorithm may not match the
517 * intended behavior of the developer. In these situations, you can provide
518 * explicit overrides by using these XML attributes in the layout file:
519 * <pre>
520 * nextFocusDown
521 * nextFocusLeft
522 * nextFocusRight
523 * nextFocusUp
524 * </pre>
525 * </p>
526 *
527 *
528 * <p>
529 * To get a particular view to take focus, call {@link #requestFocus()}.
530 * </p>
531 *
532 * <a name="TouchMode"></a>
533 * <h3>Touch Mode</h3>
534 * <p>
535 * When a user is navigating a user interface via directional keys such as a D-pad, it is
536 * necessary to give focus to actionable items such as buttons so the user can see
537 * what will take input.  If the device has touch capabilities, however, and the user
538 * begins interacting with the interface by touching it, it is no longer necessary to
539 * always highlight, or give focus to, a particular view.  This motivates a mode
540 * for interaction named 'touch mode'.
541 * </p>
542 * <p>
543 * For a touch capable device, once the user touches the screen, the device
544 * will enter touch mode.  From this point onward, only views for which
545 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
546 * Other views that are touchable, like buttons, will not take focus when touched; they will
547 * only fire the on click listeners.
548 * </p>
549 * <p>
550 * Any time a user hits a directional key, such as a D-pad direction, the view device will
551 * exit touch mode, and find a view to take focus, so that the user may resume interacting
552 * with the user interface without touching the screen again.
553 * </p>
554 * <p>
555 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
556 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
557 * </p>
558 *
559 * <a name="Scrolling"></a>
560 * <h3>Scrolling</h3>
561 * <p>
562 * The framework provides basic support for views that wish to internally
563 * scroll their content. This includes keeping track of the X and Y scroll
564 * offset as well as mechanisms for drawing scrollbars. See
565 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
566 * {@link #awakenScrollBars()} for more details.
567 * </p>
568 *
569 * <a name="Tags"></a>
570 * <h3>Tags</h3>
571 * <p>
572 * Unlike IDs, tags are not used to identify views. Tags are essentially an
573 * extra piece of information that can be associated with a view. They are most
574 * often used as a convenience to store data related to views in the views
575 * themselves rather than by putting them in a separate structure.
576 * </p>
577 *
578 * <a name="Properties"></a>
579 * <h3>Properties</h3>
580 * <p>
581 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
582 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
583 * available both in the {@link Property} form as well as in similarly-named setter/getter
584 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
585 * be used to set persistent state associated with these rendering-related properties on the view.
586 * The properties and methods can also be used in conjunction with
587 * {@link android.animation.Animator Animator}-based animations, described more in the
588 * <a href="#Animation">Animation</a> section.
589 * </p>
590 *
591 * <a name="Animation"></a>
592 * <h3>Animation</h3>
593 * <p>
594 * Starting with Android 3.0, the preferred way of animating views is to use the
595 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
596 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
597 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
598 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
599 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
600 * makes animating these View properties particularly easy and efficient.
601 * </p>
602 * <p>
603 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
604 * You can attach an {@link Animation} object to a view using
605 * {@link #setAnimation(Animation)} or
606 * {@link #startAnimation(Animation)}. The animation can alter the scale,
607 * rotation, translation and alpha of a view over time. If the animation is
608 * attached to a view that has children, the animation will affect the entire
609 * subtree rooted by that node. When an animation is started, the framework will
610 * take care of redrawing the appropriate views until the animation completes.
611 * </p>
612 *
613 * <a name="Security"></a>
614 * <h3>Security</h3>
615 * <p>
616 * Sometimes it is essential that an application be able to verify that an action
617 * is being performed with the full knowledge and consent of the user, such as
618 * granting a permission request, making a purchase or clicking on an advertisement.
619 * Unfortunately, a malicious application could try to spoof the user into
620 * performing these actions, unaware, by concealing the intended purpose of the view.
621 * As a remedy, the framework offers a touch filtering mechanism that can be used to
622 * improve the security of views that provide access to sensitive functionality.
623 * </p><p>
624 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
625 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
626 * will discard touches that are received whenever the view's window is obscured by
627 * another visible window.  As a result, the view will not receive touches whenever a
628 * toast, dialog or other window appears above the view's window.
629 * </p><p>
630 * For more fine-grained control over security, consider overriding the
631 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
632 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
633 * </p>
634 *
635 * @attr ref android.R.styleable#View_alpha
636 * @attr ref android.R.styleable#View_assistBlocked
637 * @attr ref android.R.styleable#View_background
638 * @attr ref android.R.styleable#View_clickable
639 * @attr ref android.R.styleable#View_contentDescription
640 * @attr ref android.R.styleable#View_drawingCacheQuality
641 * @attr ref android.R.styleable#View_duplicateParentState
642 * @attr ref android.R.styleable#View_id
643 * @attr ref android.R.styleable#View_requiresFadingEdge
644 * @attr ref android.R.styleable#View_fadeScrollbars
645 * @attr ref android.R.styleable#View_fadingEdgeLength
646 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
647 * @attr ref android.R.styleable#View_fitsSystemWindows
648 * @attr ref android.R.styleable#View_isScrollContainer
649 * @attr ref android.R.styleable#View_focusable
650 * @attr ref android.R.styleable#View_focusableInTouchMode
651 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
652 * @attr ref android.R.styleable#View_keepScreenOn
653 * @attr ref android.R.styleable#View_layerType
654 * @attr ref android.R.styleable#View_layoutDirection
655 * @attr ref android.R.styleable#View_longClickable
656 * @attr ref android.R.styleable#View_minHeight
657 * @attr ref android.R.styleable#View_minWidth
658 * @attr ref android.R.styleable#View_nextFocusDown
659 * @attr ref android.R.styleable#View_nextFocusLeft
660 * @attr ref android.R.styleable#View_nextFocusRight
661 * @attr ref android.R.styleable#View_nextFocusUp
662 * @attr ref android.R.styleable#View_onClick
663 * @attr ref android.R.styleable#View_padding
664 * @attr ref android.R.styleable#View_paddingBottom
665 * @attr ref android.R.styleable#View_paddingLeft
666 * @attr ref android.R.styleable#View_paddingRight
667 * @attr ref android.R.styleable#View_paddingTop
668 * @attr ref android.R.styleable#View_paddingStart
669 * @attr ref android.R.styleable#View_paddingEnd
670 * @attr ref android.R.styleable#View_saveEnabled
671 * @attr ref android.R.styleable#View_rotation
672 * @attr ref android.R.styleable#View_rotationX
673 * @attr ref android.R.styleable#View_rotationY
674 * @attr ref android.R.styleable#View_scaleX
675 * @attr ref android.R.styleable#View_scaleY
676 * @attr ref android.R.styleable#View_scrollX
677 * @attr ref android.R.styleable#View_scrollY
678 * @attr ref android.R.styleable#View_scrollbarSize
679 * @attr ref android.R.styleable#View_scrollbarStyle
680 * @attr ref android.R.styleable#View_scrollbars
681 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
682 * @attr ref android.R.styleable#View_scrollbarFadeDuration
683 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
684 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
685 * @attr ref android.R.styleable#View_scrollbarThumbVertical
686 * @attr ref android.R.styleable#View_scrollbarTrackVertical
687 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
688 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
689 * @attr ref android.R.styleable#View_stateListAnimator
690 * @attr ref android.R.styleable#View_transitionName
691 * @attr ref android.R.styleable#View_soundEffectsEnabled
692 * @attr ref android.R.styleable#View_tag
693 * @attr ref android.R.styleable#View_textAlignment
694 * @attr ref android.R.styleable#View_textDirection
695 * @attr ref android.R.styleable#View_transformPivotX
696 * @attr ref android.R.styleable#View_transformPivotY
697 * @attr ref android.R.styleable#View_translationX
698 * @attr ref android.R.styleable#View_translationY
699 * @attr ref android.R.styleable#View_translationZ
700 * @attr ref android.R.styleable#View_visibility
701 *
702 * @see android.view.ViewGroup
703 */
704@UiThread
705public class View implements Drawable.Callback, KeyEvent.Callback,
706        AccessibilityEventSource {
707    private static final boolean DBG = false;
708
709    /**
710     * The logging tag used by this class with android.util.Log.
711     */
712    protected static final String VIEW_LOG_TAG = "View";
713
714    /**
715     * When set to true, apps will draw debugging information about their layouts.
716     *
717     * @hide
718     */
719    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
720
721    /**
722     * When set to true, this view will save its attribute data.
723     *
724     * @hide
725     */
726    public static boolean mDebugViewAttributes = false;
727
728    /**
729     * Used to mark a View that has no ID.
730     */
731    public static final int NO_ID = -1;
732
733    /**
734     * Signals that compatibility booleans have been initialized according to
735     * target SDK versions.
736     */
737    private static boolean sCompatibilityDone = false;
738
739    /**
740     * Use the old (broken) way of building MeasureSpecs.
741     */
742    private static boolean sUseBrokenMakeMeasureSpec = false;
743
744    /**
745     * Ignore any optimizations using the measure cache.
746     */
747    private static boolean sIgnoreMeasureCache = false;
748
749    /**
750     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
751     * calling setFlags.
752     */
753    private static final int NOT_FOCUSABLE = 0x00000000;
754
755    /**
756     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
757     * setFlags.
758     */
759    private static final int FOCUSABLE = 0x00000001;
760
761    /**
762     * Mask for use with setFlags indicating bits used for focus.
763     */
764    private static final int FOCUSABLE_MASK = 0x00000001;
765
766    /**
767     * This view will adjust its padding to fit sytem windows (e.g. status bar)
768     */
769    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
770
771    /** @hide */
772    @IntDef({VISIBLE, INVISIBLE, GONE})
773    @Retention(RetentionPolicy.SOURCE)
774    public @interface Visibility {}
775
776    /**
777     * This view is visible.
778     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
779     * android:visibility}.
780     */
781    public static final int VISIBLE = 0x00000000;
782
783    /**
784     * This view is invisible, but it still takes up space for layout purposes.
785     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
786     * android:visibility}.
787     */
788    public static final int INVISIBLE = 0x00000004;
789
790    /**
791     * This view is invisible, and it doesn't take any space for layout
792     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
793     * android:visibility}.
794     */
795    public static final int GONE = 0x00000008;
796
797    /**
798     * Mask for use with setFlags indicating bits used for visibility.
799     * {@hide}
800     */
801    static final int VISIBILITY_MASK = 0x0000000C;
802
803    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
804
805    /**
806     * This view is enabled. Interpretation varies by subclass.
807     * Use with ENABLED_MASK when calling setFlags.
808     * {@hide}
809     */
810    static final int ENABLED = 0x00000000;
811
812    /**
813     * This view is disabled. Interpretation varies by subclass.
814     * Use with ENABLED_MASK when calling setFlags.
815     * {@hide}
816     */
817    static final int DISABLED = 0x00000020;
818
819   /**
820    * Mask for use with setFlags indicating bits used for indicating whether
821    * this view is enabled
822    * {@hide}
823    */
824    static final int ENABLED_MASK = 0x00000020;
825
826    /**
827     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
828     * called and further optimizations will be performed. It is okay to have
829     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
830     * {@hide}
831     */
832    static final int WILL_NOT_DRAW = 0x00000080;
833
834    /**
835     * Mask for use with setFlags indicating bits used for indicating whether
836     * this view is will draw
837     * {@hide}
838     */
839    static final int DRAW_MASK = 0x00000080;
840
841    /**
842     * <p>This view doesn't show scrollbars.</p>
843     * {@hide}
844     */
845    static final int SCROLLBARS_NONE = 0x00000000;
846
847    /**
848     * <p>This view shows horizontal scrollbars.</p>
849     * {@hide}
850     */
851    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
852
853    /**
854     * <p>This view shows vertical scrollbars.</p>
855     * {@hide}
856     */
857    static final int SCROLLBARS_VERTICAL = 0x00000200;
858
859    /**
860     * <p>Mask for use with setFlags indicating bits used for indicating which
861     * scrollbars are enabled.</p>
862     * {@hide}
863     */
864    static final int SCROLLBARS_MASK = 0x00000300;
865
866    /**
867     * Indicates that the view should filter touches when its window is obscured.
868     * Refer to the class comments for more information about this security feature.
869     * {@hide}
870     */
871    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
872
873    /**
874     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
875     * that they are optional and should be skipped if the window has
876     * requested system UI flags that ignore those insets for layout.
877     */
878    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
879
880    /**
881     * <p>This view doesn't show fading edges.</p>
882     * {@hide}
883     */
884    static final int FADING_EDGE_NONE = 0x00000000;
885
886    /**
887     * <p>This view shows horizontal fading edges.</p>
888     * {@hide}
889     */
890    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
891
892    /**
893     * <p>This view shows vertical fading edges.</p>
894     * {@hide}
895     */
896    static final int FADING_EDGE_VERTICAL = 0x00002000;
897
898    /**
899     * <p>Mask for use with setFlags indicating bits used for indicating which
900     * fading edges are enabled.</p>
901     * {@hide}
902     */
903    static final int FADING_EDGE_MASK = 0x00003000;
904
905    /**
906     * <p>Indicates this view can be clicked. When clickable, a View reacts
907     * to clicks by notifying the OnClickListener.<p>
908     * {@hide}
909     */
910    static final int CLICKABLE = 0x00004000;
911
912    /**
913     * <p>Indicates this view is caching its drawing into a bitmap.</p>
914     * {@hide}
915     */
916    static final int DRAWING_CACHE_ENABLED = 0x00008000;
917
918    /**
919     * <p>Indicates that no icicle should be saved for this view.<p>
920     * {@hide}
921     */
922    static final int SAVE_DISABLED = 0x000010000;
923
924    /**
925     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
926     * property.</p>
927     * {@hide}
928     */
929    static final int SAVE_DISABLED_MASK = 0x000010000;
930
931    /**
932     * <p>Indicates that no drawing cache should ever be created for this view.<p>
933     * {@hide}
934     */
935    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
936
937    /**
938     * <p>Indicates this view can take / keep focus when int touch mode.</p>
939     * {@hide}
940     */
941    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
942
943    /** @hide */
944    @Retention(RetentionPolicy.SOURCE)
945    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
946    public @interface DrawingCacheQuality {}
947
948    /**
949     * <p>Enables low quality mode for the drawing cache.</p>
950     */
951    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
952
953    /**
954     * <p>Enables high quality mode for the drawing cache.</p>
955     */
956    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
957
958    /**
959     * <p>Enables automatic quality mode for the drawing cache.</p>
960     */
961    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
962
963    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
964            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
965    };
966
967    /**
968     * <p>Mask for use with setFlags indicating bits used for the cache
969     * quality property.</p>
970     * {@hide}
971     */
972    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
973
974    /**
975     * <p>
976     * Indicates this view can be long clicked. When long clickable, a View
977     * reacts to long clicks by notifying the OnLongClickListener or showing a
978     * context menu.
979     * </p>
980     * {@hide}
981     */
982    static final int LONG_CLICKABLE = 0x00200000;
983
984    /**
985     * <p>Indicates that this view gets its drawable states from its direct parent
986     * and ignores its original internal states.</p>
987     *
988     * @hide
989     */
990    static final int DUPLICATE_PARENT_STATE = 0x00400000;
991
992    /** @hide */
993    @IntDef({
994        SCROLLBARS_INSIDE_OVERLAY,
995        SCROLLBARS_INSIDE_INSET,
996        SCROLLBARS_OUTSIDE_OVERLAY,
997        SCROLLBARS_OUTSIDE_INSET
998    })
999    @Retention(RetentionPolicy.SOURCE)
1000    public @interface ScrollBarStyle {}
1001
1002    /**
1003     * The scrollbar style to display the scrollbars inside the content area,
1004     * without increasing the padding. The scrollbars will be overlaid with
1005     * translucency on the view's content.
1006     */
1007    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1008
1009    /**
1010     * The scrollbar style to display the scrollbars inside the padded area,
1011     * increasing the padding of the view. The scrollbars will not overlap the
1012     * content area of the view.
1013     */
1014    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1015
1016    /**
1017     * The scrollbar style to display the scrollbars at the edge of the view,
1018     * without increasing the padding. The scrollbars will be overlaid with
1019     * translucency.
1020     */
1021    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1022
1023    /**
1024     * The scrollbar style to display the scrollbars at the edge of the view,
1025     * increasing the padding of the view. The scrollbars will only overlap the
1026     * background, if any.
1027     */
1028    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1029
1030    /**
1031     * Mask to check if the scrollbar style is overlay or inset.
1032     * {@hide}
1033     */
1034    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1035
1036    /**
1037     * Mask to check if the scrollbar style is inside or outside.
1038     * {@hide}
1039     */
1040    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1041
1042    /**
1043     * Mask for scrollbar style.
1044     * {@hide}
1045     */
1046    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1047
1048    /**
1049     * View flag indicating that the screen should remain on while the
1050     * window containing this view is visible to the user.  This effectively
1051     * takes care of automatically setting the WindowManager's
1052     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1053     */
1054    public static final int KEEP_SCREEN_ON = 0x04000000;
1055
1056    /**
1057     * View flag indicating whether this view should have sound effects enabled
1058     * for events such as clicking and touching.
1059     */
1060    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1061
1062    /**
1063     * View flag indicating whether this view should have haptic feedback
1064     * enabled for events such as long presses.
1065     */
1066    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1067
1068    /**
1069     * <p>Indicates that the view hierarchy should stop saving state when
1070     * it reaches this view.  If state saving is initiated immediately at
1071     * the view, it will be allowed.
1072     * {@hide}
1073     */
1074    static final int PARENT_SAVE_DISABLED = 0x20000000;
1075
1076    /**
1077     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1078     * {@hide}
1079     */
1080    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1081
1082    /** @hide */
1083    @IntDef(flag = true,
1084            value = {
1085                FOCUSABLES_ALL,
1086                FOCUSABLES_TOUCH_MODE
1087            })
1088    @Retention(RetentionPolicy.SOURCE)
1089    public @interface FocusableMode {}
1090
1091    /**
1092     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1093     * should add all focusable Views regardless if they are focusable in touch mode.
1094     */
1095    public static final int FOCUSABLES_ALL = 0x00000000;
1096
1097    /**
1098     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1099     * should add only Views focusable in touch mode.
1100     */
1101    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1102
1103    /** @hide */
1104    @IntDef({
1105            FOCUS_BACKWARD,
1106            FOCUS_FORWARD,
1107            FOCUS_LEFT,
1108            FOCUS_UP,
1109            FOCUS_RIGHT,
1110            FOCUS_DOWN
1111    })
1112    @Retention(RetentionPolicy.SOURCE)
1113    public @interface FocusDirection {}
1114
1115    /** @hide */
1116    @IntDef({
1117            FOCUS_LEFT,
1118            FOCUS_UP,
1119            FOCUS_RIGHT,
1120            FOCUS_DOWN
1121    })
1122    @Retention(RetentionPolicy.SOURCE)
1123    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1124
1125    /**
1126     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1127     * item.
1128     */
1129    public static final int FOCUS_BACKWARD = 0x00000001;
1130
1131    /**
1132     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1133     * item.
1134     */
1135    public static final int FOCUS_FORWARD = 0x00000002;
1136
1137    /**
1138     * Use with {@link #focusSearch(int)}. Move focus to the left.
1139     */
1140    public static final int FOCUS_LEFT = 0x00000011;
1141
1142    /**
1143     * Use with {@link #focusSearch(int)}. Move focus up.
1144     */
1145    public static final int FOCUS_UP = 0x00000021;
1146
1147    /**
1148     * Use with {@link #focusSearch(int)}. Move focus to the right.
1149     */
1150    public static final int FOCUS_RIGHT = 0x00000042;
1151
1152    /**
1153     * Use with {@link #focusSearch(int)}. Move focus down.
1154     */
1155    public static final int FOCUS_DOWN = 0x00000082;
1156
1157    /**
1158     * Bits of {@link #getMeasuredWidthAndState()} and
1159     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1160     */
1161    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1162
1163    /**
1164     * Bits of {@link #getMeasuredWidthAndState()} and
1165     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1166     */
1167    public static final int MEASURED_STATE_MASK = 0xff000000;
1168
1169    /**
1170     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1171     * for functions that combine both width and height into a single int,
1172     * such as {@link #getMeasuredState()} and the childState argument of
1173     * {@link #resolveSizeAndState(int, int, int)}.
1174     */
1175    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1176
1177    /**
1178     * Bit of {@link #getMeasuredWidthAndState()} and
1179     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1180     * is smaller that the space the view would like to have.
1181     */
1182    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1183
1184    /**
1185     * Base View state sets
1186     */
1187    // Singles
1188    /**
1189     * Indicates the view has no states set. States are used with
1190     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1191     * view depending on its state.
1192     *
1193     * @see android.graphics.drawable.Drawable
1194     * @see #getDrawableState()
1195     */
1196    protected static final int[] EMPTY_STATE_SET;
1197    /**
1198     * Indicates the view is enabled. States are used with
1199     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1200     * view depending on its state.
1201     *
1202     * @see android.graphics.drawable.Drawable
1203     * @see #getDrawableState()
1204     */
1205    protected static final int[] ENABLED_STATE_SET;
1206    /**
1207     * Indicates the view is focused. States are used with
1208     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1209     * view depending on its state.
1210     *
1211     * @see android.graphics.drawable.Drawable
1212     * @see #getDrawableState()
1213     */
1214    protected static final int[] FOCUSED_STATE_SET;
1215    /**
1216     * Indicates the view is selected. States are used with
1217     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1218     * view depending on its state.
1219     *
1220     * @see android.graphics.drawable.Drawable
1221     * @see #getDrawableState()
1222     */
1223    protected static final int[] SELECTED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed. States are used with
1226     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1227     * view depending on its state.
1228     *
1229     * @see android.graphics.drawable.Drawable
1230     * @see #getDrawableState()
1231     */
1232    protected static final int[] PRESSED_STATE_SET;
1233    /**
1234     * Indicates the view's window has focus. States are used with
1235     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1236     * view depending on its state.
1237     *
1238     * @see android.graphics.drawable.Drawable
1239     * @see #getDrawableState()
1240     */
1241    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1242    // Doubles
1243    /**
1244     * Indicates the view is enabled and has the focus.
1245     *
1246     * @see #ENABLED_STATE_SET
1247     * @see #FOCUSED_STATE_SET
1248     */
1249    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is enabled and selected.
1252     *
1253     * @see #ENABLED_STATE_SET
1254     * @see #SELECTED_STATE_SET
1255     */
1256    protected static final int[] ENABLED_SELECTED_STATE_SET;
1257    /**
1258     * Indicates the view is enabled and that its window has focus.
1259     *
1260     * @see #ENABLED_STATE_SET
1261     * @see #WINDOW_FOCUSED_STATE_SET
1262     */
1263    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is focused and selected.
1266     *
1267     * @see #FOCUSED_STATE_SET
1268     * @see #SELECTED_STATE_SET
1269     */
1270    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1271    /**
1272     * Indicates the view has the focus and that its window has the focus.
1273     *
1274     * @see #FOCUSED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is selected and that its window has the focus.
1280     *
1281     * @see #SELECTED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1285    // Triples
1286    /**
1287     * Indicates the view is enabled, focused and selected.
1288     *
1289     * @see #ENABLED_STATE_SET
1290     * @see #FOCUSED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     */
1293    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1294    /**
1295     * Indicates the view is enabled, focused and its window has the focus.
1296     *
1297     * @see #ENABLED_STATE_SET
1298     * @see #FOCUSED_STATE_SET
1299     * @see #WINDOW_FOCUSED_STATE_SET
1300     */
1301    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1302    /**
1303     * Indicates the view is enabled, selected and its window has the focus.
1304     *
1305     * @see #ENABLED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is focused, selected and its window has the focus.
1312     *
1313     * @see #FOCUSED_STATE_SET
1314     * @see #SELECTED_STATE_SET
1315     * @see #WINDOW_FOCUSED_STATE_SET
1316     */
1317    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is enabled, focused, selected and its window
1320     * has the focus.
1321     *
1322     * @see #ENABLED_STATE_SET
1323     * @see #FOCUSED_STATE_SET
1324     * @see #SELECTED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed and its window has the focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #WINDOW_FOCUSED_STATE_SET
1333     */
1334    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1335    /**
1336     * Indicates the view is pressed and selected.
1337     *
1338     * @see #PRESSED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_SELECTED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, selected and its window has the focus.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #SELECTED_STATE_SET
1347     * @see #WINDOW_FOCUSED_STATE_SET
1348     */
1349    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1350    /**
1351     * Indicates the view is pressed and focused.
1352     *
1353     * @see #PRESSED_STATE_SET
1354     * @see #FOCUSED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed, focused and its window has the focus.
1359     *
1360     * @see #PRESSED_STATE_SET
1361     * @see #FOCUSED_STATE_SET
1362     * @see #WINDOW_FOCUSED_STATE_SET
1363     */
1364    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1365    /**
1366     * Indicates the view is pressed, focused and selected.
1367     *
1368     * @see #PRESSED_STATE_SET
1369     * @see #SELECTED_STATE_SET
1370     * @see #FOCUSED_STATE_SET
1371     */
1372    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1373    /**
1374     * Indicates the view is pressed, focused, selected and its window has the focus.
1375     *
1376     * @see #PRESSED_STATE_SET
1377     * @see #FOCUSED_STATE_SET
1378     * @see #SELECTED_STATE_SET
1379     * @see #WINDOW_FOCUSED_STATE_SET
1380     */
1381    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1382    /**
1383     * Indicates the view is pressed and enabled.
1384     *
1385     * @see #PRESSED_STATE_SET
1386     * @see #ENABLED_STATE_SET
1387     */
1388    protected static final int[] PRESSED_ENABLED_STATE_SET;
1389    /**
1390     * Indicates the view is pressed, enabled and its window has the focus.
1391     *
1392     * @see #PRESSED_STATE_SET
1393     * @see #ENABLED_STATE_SET
1394     * @see #WINDOW_FOCUSED_STATE_SET
1395     */
1396    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1397    /**
1398     * Indicates the view is pressed, enabled and selected.
1399     *
1400     * @see #PRESSED_STATE_SET
1401     * @see #ENABLED_STATE_SET
1402     * @see #SELECTED_STATE_SET
1403     */
1404    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1405    /**
1406     * Indicates the view is pressed, enabled, selected and its window has the
1407     * focus.
1408     *
1409     * @see #PRESSED_STATE_SET
1410     * @see #ENABLED_STATE_SET
1411     * @see #SELECTED_STATE_SET
1412     * @see #WINDOW_FOCUSED_STATE_SET
1413     */
1414    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1415    /**
1416     * Indicates the view is pressed, enabled and focused.
1417     *
1418     * @see #PRESSED_STATE_SET
1419     * @see #ENABLED_STATE_SET
1420     * @see #FOCUSED_STATE_SET
1421     */
1422    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1423    /**
1424     * Indicates the view is pressed, enabled, focused and its window has the
1425     * focus.
1426     *
1427     * @see #PRESSED_STATE_SET
1428     * @see #ENABLED_STATE_SET
1429     * @see #FOCUSED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1433    /**
1434     * Indicates the view is pressed, enabled, focused and selected.
1435     *
1436     * @see #PRESSED_STATE_SET
1437     * @see #ENABLED_STATE_SET
1438     * @see #SELECTED_STATE_SET
1439     * @see #FOCUSED_STATE_SET
1440     */
1441    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1442    /**
1443     * Indicates the view is pressed, enabled, focused, selected and its window
1444     * has the focus.
1445     *
1446     * @see #PRESSED_STATE_SET
1447     * @see #ENABLED_STATE_SET
1448     * @see #SELECTED_STATE_SET
1449     * @see #FOCUSED_STATE_SET
1450     * @see #WINDOW_FOCUSED_STATE_SET
1451     */
1452    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1453
1454    static {
1455        EMPTY_STATE_SET = StateSet.get(0);
1456
1457        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1458
1459        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1460        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1461                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1462
1463        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1464        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1465                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1466        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1467                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1468        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1469                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1470                        | StateSet.VIEW_STATE_FOCUSED);
1471
1472        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1473        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1474                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1475        ENABLED_SELECTED_STATE_SET = StateSet.get(
1476                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1477        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1478                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1479                        | StateSet.VIEW_STATE_ENABLED);
1480        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1481                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1482        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1483                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1484                        | StateSet.VIEW_STATE_ENABLED);
1485        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1486                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1487                        | StateSet.VIEW_STATE_ENABLED);
1488        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1489                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1490                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1491
1492        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1493        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1495        PRESSED_SELECTED_STATE_SET = StateSet.get(
1496                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1497        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1498                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1499                        | StateSet.VIEW_STATE_PRESSED);
1500        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1501                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1502        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1503                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1504                        | StateSet.VIEW_STATE_PRESSED);
1505        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1506                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1507                        | StateSet.VIEW_STATE_PRESSED);
1508        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1509                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1510                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1511        PRESSED_ENABLED_STATE_SET = StateSet.get(
1512                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1515                        | StateSet.VIEW_STATE_PRESSED);
1516        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1517                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1518                        | StateSet.VIEW_STATE_PRESSED);
1519        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1520                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1521                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1522        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1523                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1524                        | StateSet.VIEW_STATE_PRESSED);
1525        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1526                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1527                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1528        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1529                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1530                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1531        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1532                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1533                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1534                        | StateSet.VIEW_STATE_PRESSED);
1535    }
1536
1537    /**
1538     * Accessibility event types that are dispatched for text population.
1539     */
1540    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1541            AccessibilityEvent.TYPE_VIEW_CLICKED
1542            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1543            | AccessibilityEvent.TYPE_VIEW_SELECTED
1544            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1545            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1546            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1547            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1548            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1549            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1550            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1551            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1552
1553    /**
1554     * Temporary Rect currently for use in setBackground().  This will probably
1555     * be extended in the future to hold our own class with more than just
1556     * a Rect. :)
1557     */
1558    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1559
1560    /**
1561     * Map used to store views' tags.
1562     */
1563    private SparseArray<Object> mKeyedTags;
1564
1565    /**
1566     * The next available accessibility id.
1567     */
1568    private static int sNextAccessibilityViewId;
1569
1570    /**
1571     * The animation currently associated with this view.
1572     * @hide
1573     */
1574    protected Animation mCurrentAnimation = null;
1575
1576    /**
1577     * Width as measured during measure pass.
1578     * {@hide}
1579     */
1580    @ViewDebug.ExportedProperty(category = "measurement")
1581    int mMeasuredWidth;
1582
1583    /**
1584     * Height as measured during measure pass.
1585     * {@hide}
1586     */
1587    @ViewDebug.ExportedProperty(category = "measurement")
1588    int mMeasuredHeight;
1589
1590    /**
1591     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1592     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1593     * its display list. This flag, used only when hw accelerated, allows us to clear the
1594     * flag while retaining this information until it's needed (at getDisplayList() time and
1595     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1596     *
1597     * {@hide}
1598     */
1599    boolean mRecreateDisplayList = false;
1600
1601    /**
1602     * The view's identifier.
1603     * {@hide}
1604     *
1605     * @see #setId(int)
1606     * @see #getId()
1607     */
1608    @IdRes
1609    @ViewDebug.ExportedProperty(resolveId = true)
1610    int mID = NO_ID;
1611
1612    /**
1613     * The stable ID of this view for accessibility purposes.
1614     */
1615    int mAccessibilityViewId = NO_ID;
1616
1617    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1618
1619    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1620
1621    /**
1622     * The view's tag.
1623     * {@hide}
1624     *
1625     * @see #setTag(Object)
1626     * @see #getTag()
1627     */
1628    protected Object mTag = null;
1629
1630    // for mPrivateFlags:
1631    /** {@hide} */
1632    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1633    /** {@hide} */
1634    static final int PFLAG_FOCUSED                     = 0x00000002;
1635    /** {@hide} */
1636    static final int PFLAG_SELECTED                    = 0x00000004;
1637    /** {@hide} */
1638    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1639    /** {@hide} */
1640    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1641    /** {@hide} */
1642    static final int PFLAG_DRAWN                       = 0x00000020;
1643    /**
1644     * When this flag is set, this view is running an animation on behalf of its
1645     * children and should therefore not cancel invalidate requests, even if they
1646     * lie outside of this view's bounds.
1647     *
1648     * {@hide}
1649     */
1650    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1651    /** {@hide} */
1652    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1653    /** {@hide} */
1654    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1655    /** {@hide} */
1656    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1657    /** {@hide} */
1658    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1659    /** {@hide} */
1660    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1661    /** {@hide} */
1662    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1663    /** {@hide} */
1664    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1665
1666    private static final int PFLAG_PRESSED             = 0x00004000;
1667
1668    /** {@hide} */
1669    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1670    /**
1671     * Flag used to indicate that this view should be drawn once more (and only once
1672     * more) after its animation has completed.
1673     * {@hide}
1674     */
1675    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1676
1677    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1678
1679    /**
1680     * Indicates that the View returned true when onSetAlpha() was called and that
1681     * the alpha must be restored.
1682     * {@hide}
1683     */
1684    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1685
1686    /**
1687     * Set by {@link #setScrollContainer(boolean)}.
1688     */
1689    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1690
1691    /**
1692     * Set by {@link #setScrollContainer(boolean)}.
1693     */
1694    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1695
1696    /**
1697     * View flag indicating whether this view was invalidated (fully or partially.)
1698     *
1699     * @hide
1700     */
1701    static final int PFLAG_DIRTY                       = 0x00200000;
1702
1703    /**
1704     * View flag indicating whether this view was invalidated by an opaque
1705     * invalidate request.
1706     *
1707     * @hide
1708     */
1709    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1710
1711    /**
1712     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1713     *
1714     * @hide
1715     */
1716    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1717
1718    /**
1719     * Indicates whether the background is opaque.
1720     *
1721     * @hide
1722     */
1723    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1724
1725    /**
1726     * Indicates whether the scrollbars are opaque.
1727     *
1728     * @hide
1729     */
1730    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1731
1732    /**
1733     * Indicates whether the view is opaque.
1734     *
1735     * @hide
1736     */
1737    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1738
1739    /**
1740     * Indicates a prepressed state;
1741     * the short time between ACTION_DOWN and recognizing
1742     * a 'real' press. Prepressed is used to recognize quick taps
1743     * even when they are shorter than ViewConfiguration.getTapTimeout().
1744     *
1745     * @hide
1746     */
1747    private static final int PFLAG_PREPRESSED          = 0x02000000;
1748
1749    /**
1750     * Indicates whether the view is temporarily detached.
1751     *
1752     * @hide
1753     */
1754    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1755
1756    /**
1757     * Indicates that we should awaken scroll bars once attached
1758     *
1759     * @hide
1760     */
1761    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1762
1763    /**
1764     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1765     * @hide
1766     */
1767    private static final int PFLAG_HOVERED             = 0x10000000;
1768
1769    /**
1770     * no longer needed, should be reused
1771     */
1772    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1773
1774    /** {@hide} */
1775    static final int PFLAG_ACTIVATED                   = 0x40000000;
1776
1777    /**
1778     * Indicates that this view was specifically invalidated, not just dirtied because some
1779     * child view was invalidated. The flag is used to determine when we need to recreate
1780     * a view's display list (as opposed to just returning a reference to its existing
1781     * display list).
1782     *
1783     * @hide
1784     */
1785    static final int PFLAG_INVALIDATED                 = 0x80000000;
1786
1787    /**
1788     * Masks for mPrivateFlags2, as generated by dumpFlags():
1789     *
1790     * |-------|-------|-------|-------|
1791     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1792     *                                1  PFLAG2_DRAG_HOVERED
1793     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1794     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1795     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1796     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1797     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1798     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1799     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1800     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1801     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1802     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1803     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1804     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1805     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1806     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1807     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1808     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1809     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1810     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1811     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1812     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1813     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1814     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1815     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1816     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1817     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1818     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1819     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1820     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1821     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1822     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1823     *    1                              PFLAG2_PADDING_RESOLVED
1824     *   1                               PFLAG2_DRAWABLE_RESOLVED
1825     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1826     * |-------|-------|-------|-------|
1827     */
1828
1829    /**
1830     * Indicates that this view has reported that it can accept the current drag's content.
1831     * Cleared when the drag operation concludes.
1832     * @hide
1833     */
1834    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1835
1836    /**
1837     * Indicates that this view is currently directly under the drag location in a
1838     * drag-and-drop operation involving content that it can accept.  Cleared when
1839     * the drag exits the view, or when the drag operation concludes.
1840     * @hide
1841     */
1842    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1843
1844    /** @hide */
1845    @IntDef({
1846        LAYOUT_DIRECTION_LTR,
1847        LAYOUT_DIRECTION_RTL,
1848        LAYOUT_DIRECTION_INHERIT,
1849        LAYOUT_DIRECTION_LOCALE
1850    })
1851    @Retention(RetentionPolicy.SOURCE)
1852    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1853    public @interface LayoutDir {}
1854
1855    /** @hide */
1856    @IntDef({
1857        LAYOUT_DIRECTION_LTR,
1858        LAYOUT_DIRECTION_RTL
1859    })
1860    @Retention(RetentionPolicy.SOURCE)
1861    public @interface ResolvedLayoutDir {}
1862
1863    /**
1864     * Horizontal layout direction of this view is from Left to Right.
1865     * Use with {@link #setLayoutDirection}.
1866     */
1867    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1868
1869    /**
1870     * Horizontal layout direction of this view is from Right to Left.
1871     * Use with {@link #setLayoutDirection}.
1872     */
1873    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1874
1875    /**
1876     * Horizontal layout direction of this view is inherited from its parent.
1877     * Use with {@link #setLayoutDirection}.
1878     */
1879    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1880
1881    /**
1882     * Horizontal layout direction of this view is from deduced from the default language
1883     * script for the locale. Use with {@link #setLayoutDirection}.
1884     */
1885    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1886
1887    /**
1888     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1889     * @hide
1890     */
1891    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1892
1893    /**
1894     * Mask for use with private flags indicating bits used for horizontal layout direction.
1895     * @hide
1896     */
1897    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1898
1899    /**
1900     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1901     * right-to-left direction.
1902     * @hide
1903     */
1904    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1905
1906    /**
1907     * Indicates whether the view horizontal layout direction has been resolved.
1908     * @hide
1909     */
1910    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1911
1912    /**
1913     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1917            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1918
1919    /*
1920     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1921     * flag value.
1922     * @hide
1923     */
1924    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1925            LAYOUT_DIRECTION_LTR,
1926            LAYOUT_DIRECTION_RTL,
1927            LAYOUT_DIRECTION_INHERIT,
1928            LAYOUT_DIRECTION_LOCALE
1929    };
1930
1931    /**
1932     * Default horizontal layout direction.
1933     */
1934    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1935
1936    /**
1937     * Default horizontal layout direction.
1938     * @hide
1939     */
1940    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1941
1942    /**
1943     * Text direction is inherited through {@link ViewGroup}
1944     */
1945    public static final int TEXT_DIRECTION_INHERIT = 0;
1946
1947    /**
1948     * Text direction is using "first strong algorithm". The first strong directional character
1949     * determines the paragraph direction. If there is no strong directional character, the
1950     * paragraph direction is the view's resolved layout direction.
1951     */
1952    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1953
1954    /**
1955     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1956     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1957     * If there are neither, the paragraph direction is the view's resolved layout direction.
1958     */
1959    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1960
1961    /**
1962     * Text direction is forced to LTR.
1963     */
1964    public static final int TEXT_DIRECTION_LTR = 3;
1965
1966    /**
1967     * Text direction is forced to RTL.
1968     */
1969    public static final int TEXT_DIRECTION_RTL = 4;
1970
1971    /**
1972     * Text direction is coming from the system Locale.
1973     */
1974    public static final int TEXT_DIRECTION_LOCALE = 5;
1975
1976    /**
1977     * Text direction is using "first strong algorithm". The first strong directional character
1978     * determines the paragraph direction. If there is no strong directional character, the
1979     * paragraph direction is LTR.
1980     */
1981    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
1982
1983    /**
1984     * Text direction is using "first strong algorithm". The first strong directional character
1985     * determines the paragraph direction. If there is no strong directional character, the
1986     * paragraph direction is RTL.
1987     */
1988    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
1989
1990    /**
1991     * Default text direction is inherited
1992     */
1993    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1994
1995    /**
1996     * Default resolved text direction
1997     * @hide
1998     */
1999    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2000
2001    /**
2002     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2003     * @hide
2004     */
2005    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2006
2007    /**
2008     * Mask for use with private flags indicating bits used for text direction.
2009     * @hide
2010     */
2011    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2012            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2013
2014    /**
2015     * Array of text direction flags for mapping attribute "textDirection" to correct
2016     * flag value.
2017     * @hide
2018     */
2019    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2020            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2021            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2022            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2023            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2024            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2025            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2026            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2027            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2028    };
2029
2030    /**
2031     * Indicates whether the view text direction has been resolved.
2032     * @hide
2033     */
2034    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2035            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2036
2037    /**
2038     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2039     * @hide
2040     */
2041    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2042
2043    /**
2044     * Mask for use with private flags indicating bits used for resolved text direction.
2045     * @hide
2046     */
2047    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2048            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2049
2050    /**
2051     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2052     * @hide
2053     */
2054    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2055            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2056
2057    /** @hide */
2058    @IntDef({
2059        TEXT_ALIGNMENT_INHERIT,
2060        TEXT_ALIGNMENT_GRAVITY,
2061        TEXT_ALIGNMENT_CENTER,
2062        TEXT_ALIGNMENT_TEXT_START,
2063        TEXT_ALIGNMENT_TEXT_END,
2064        TEXT_ALIGNMENT_VIEW_START,
2065        TEXT_ALIGNMENT_VIEW_END
2066    })
2067    @Retention(RetentionPolicy.SOURCE)
2068    public @interface TextAlignment {}
2069
2070    /**
2071     * Default text alignment. The text alignment of this View is inherited from its parent.
2072     * Use with {@link #setTextAlignment(int)}
2073     */
2074    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2075
2076    /**
2077     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2078     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2079     *
2080     * Use with {@link #setTextAlignment(int)}
2081     */
2082    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2083
2084    /**
2085     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2086     *
2087     * Use with {@link #setTextAlignment(int)}
2088     */
2089    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2090
2091    /**
2092     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2093     *
2094     * Use with {@link #setTextAlignment(int)}
2095     */
2096    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2097
2098    /**
2099     * Center the paragraph, e.g. ALIGN_CENTER.
2100     *
2101     * Use with {@link #setTextAlignment(int)}
2102     */
2103    public static final int TEXT_ALIGNMENT_CENTER = 4;
2104
2105    /**
2106     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2107     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2108     *
2109     * Use with {@link #setTextAlignment(int)}
2110     */
2111    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2112
2113    /**
2114     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2115     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2116     *
2117     * Use with {@link #setTextAlignment(int)}
2118     */
2119    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2120
2121    /**
2122     * Default text alignment is inherited
2123     */
2124    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2125
2126    /**
2127     * Default resolved text alignment
2128     * @hide
2129     */
2130    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2131
2132    /**
2133      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2134      * @hide
2135      */
2136    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2137
2138    /**
2139      * Mask for use with private flags indicating bits used for text alignment.
2140      * @hide
2141      */
2142    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2143
2144    /**
2145     * Array of text direction flags for mapping attribute "textAlignment" to correct
2146     * flag value.
2147     * @hide
2148     */
2149    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2150            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2151            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2152            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2153            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2154            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2155            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2156            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2157    };
2158
2159    /**
2160     * Indicates whether the view text alignment has been resolved.
2161     * @hide
2162     */
2163    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2164
2165    /**
2166     * Bit shift to get the resolved text alignment.
2167     * @hide
2168     */
2169    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2170
2171    /**
2172     * Mask for use with private flags indicating bits used for text alignment.
2173     * @hide
2174     */
2175    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2176            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2177
2178    /**
2179     * Indicates whether if the view text alignment has been resolved to gravity
2180     */
2181    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2182            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2183
2184    // Accessiblity constants for mPrivateFlags2
2185
2186    /**
2187     * Shift for the bits in {@link #mPrivateFlags2} related to the
2188     * "importantForAccessibility" attribute.
2189     */
2190    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2191
2192    /**
2193     * Automatically determine whether a view is important for accessibility.
2194     */
2195    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2196
2197    /**
2198     * The view is important for accessibility.
2199     */
2200    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2201
2202    /**
2203     * The view is not important for accessibility.
2204     */
2205    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2206
2207    /**
2208     * The view is not important for accessibility, nor are any of its
2209     * descendant views.
2210     */
2211    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2212
2213    /**
2214     * The default whether the view is important for accessibility.
2215     */
2216    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2217
2218    /**
2219     * Mask for obtainig the bits which specify how to determine
2220     * whether a view is important for accessibility.
2221     */
2222    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2223        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2224        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2225        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2226
2227    /**
2228     * Shift for the bits in {@link #mPrivateFlags2} related to the
2229     * "accessibilityLiveRegion" attribute.
2230     */
2231    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2232
2233    /**
2234     * Live region mode specifying that accessibility services should not
2235     * automatically announce changes to this view. This is the default live
2236     * region mode for most views.
2237     * <p>
2238     * Use with {@link #setAccessibilityLiveRegion(int)}.
2239     */
2240    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2241
2242    /**
2243     * Live region mode specifying that accessibility services should announce
2244     * changes to this view.
2245     * <p>
2246     * Use with {@link #setAccessibilityLiveRegion(int)}.
2247     */
2248    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2249
2250    /**
2251     * Live region mode specifying that accessibility services should interrupt
2252     * ongoing speech to immediately announce changes to this view.
2253     * <p>
2254     * Use with {@link #setAccessibilityLiveRegion(int)}.
2255     */
2256    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2257
2258    /**
2259     * The default whether the view is important for accessibility.
2260     */
2261    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2262
2263    /**
2264     * Mask for obtaining the bits which specify a view's accessibility live
2265     * region mode.
2266     */
2267    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2268            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2269            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2270
2271    /**
2272     * Flag indicating whether a view has accessibility focus.
2273     */
2274    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2275
2276    /**
2277     * Flag whether the accessibility state of the subtree rooted at this view changed.
2278     */
2279    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2280
2281    /**
2282     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2283     * is used to check whether later changes to the view's transform should invalidate the
2284     * view to force the quickReject test to run again.
2285     */
2286    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2287
2288    /**
2289     * Flag indicating that start/end padding has been resolved into left/right padding
2290     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2291     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2292     * during measurement. In some special cases this is required such as when an adapter-based
2293     * view measures prospective children without attaching them to a window.
2294     */
2295    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2296
2297    /**
2298     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2299     */
2300    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2301
2302    /**
2303     * Indicates that the view is tracking some sort of transient state
2304     * that the app should not need to be aware of, but that the framework
2305     * should take special care to preserve.
2306     */
2307    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2308
2309    /**
2310     * Group of bits indicating that RTL properties resolution is done.
2311     */
2312    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2313            PFLAG2_TEXT_DIRECTION_RESOLVED |
2314            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2315            PFLAG2_PADDING_RESOLVED |
2316            PFLAG2_DRAWABLE_RESOLVED;
2317
2318    // There are a couple of flags left in mPrivateFlags2
2319
2320    /* End of masks for mPrivateFlags2 */
2321
2322    /**
2323     * Masks for mPrivateFlags3, as generated by dumpFlags():
2324     *
2325     * |-------|-------|-------|-------|
2326     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2327     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2328     *                               1   PFLAG3_IS_LAID_OUT
2329     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2330     *                             1     PFLAG3_CALLED_SUPER
2331     *                            1      PFLAG3_APPLYING_INSETS
2332     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2333     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2334     *                         1         PFLAG3_ASSIST_BLOCKED
2335     * |-------|-------|-------|-------|
2336     */
2337
2338    /**
2339     * Flag indicating that view has a transform animation set on it. This is used to track whether
2340     * an animation is cleared between successive frames, in order to tell the associated
2341     * DisplayList to clear its animation matrix.
2342     */
2343    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2344
2345    /**
2346     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2347     * animation is cleared between successive frames, in order to tell the associated
2348     * DisplayList to restore its alpha value.
2349     */
2350    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2351
2352    /**
2353     * Flag indicating that the view has been through at least one layout since it
2354     * was last attached to a window.
2355     */
2356    static final int PFLAG3_IS_LAID_OUT = 0x4;
2357
2358    /**
2359     * Flag indicating that a call to measure() was skipped and should be done
2360     * instead when layout() is invoked.
2361     */
2362    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2363
2364    /**
2365     * Flag indicating that an overridden method correctly called down to
2366     * the superclass implementation as required by the API spec.
2367     */
2368    static final int PFLAG3_CALLED_SUPER = 0x10;
2369
2370    /**
2371     * Flag indicating that we're in the process of applying window insets.
2372     */
2373    static final int PFLAG3_APPLYING_INSETS = 0x20;
2374
2375    /**
2376     * Flag indicating that we're in the process of fitting system windows using the old method.
2377     */
2378    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2379
2380    /**
2381     * Flag indicating that nested scrolling is enabled for this view.
2382     * The view will optionally cooperate with views up its parent chain to allow for
2383     * integrated nested scrolling along the same axis.
2384     */
2385    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2386
2387    /* End of masks for mPrivateFlags3 */
2388
2389    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2390
2391    /**
2392     * <p>Indicates that we are allowing {@link android.view.ViewAssistStructure} to traverse
2393     * into this view.<p>
2394     */
2395    static final int PFLAG3_ASSIST_BLOCKED = 0x100;
2396
2397    /**
2398     * Always allow a user to over-scroll this view, provided it is a
2399     * view that can scroll.
2400     *
2401     * @see #getOverScrollMode()
2402     * @see #setOverScrollMode(int)
2403     */
2404    public static final int OVER_SCROLL_ALWAYS = 0;
2405
2406    /**
2407     * Allow a user to over-scroll this view only if the content is large
2408     * enough to meaningfully scroll, provided it is a view that can scroll.
2409     *
2410     * @see #getOverScrollMode()
2411     * @see #setOverScrollMode(int)
2412     */
2413    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2414
2415    /**
2416     * Never allow a user to over-scroll this view.
2417     *
2418     * @see #getOverScrollMode()
2419     * @see #setOverScrollMode(int)
2420     */
2421    public static final int OVER_SCROLL_NEVER = 2;
2422
2423    /**
2424     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2425     * requested the system UI (status bar) to be visible (the default).
2426     *
2427     * @see #setSystemUiVisibility(int)
2428     */
2429    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2430
2431    /**
2432     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2433     * system UI to enter an unobtrusive "low profile" mode.
2434     *
2435     * <p>This is for use in games, book readers, video players, or any other
2436     * "immersive" application where the usual system chrome is deemed too distracting.
2437     *
2438     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2439     *
2440     * @see #setSystemUiVisibility(int)
2441     */
2442    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2443
2444    /**
2445     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2446     * system navigation be temporarily hidden.
2447     *
2448     * <p>This is an even less obtrusive state than that called for by
2449     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2450     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2451     * those to disappear. This is useful (in conjunction with the
2452     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2453     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2454     * window flags) for displaying content using every last pixel on the display.
2455     *
2456     * <p>There is a limitation: because navigation controls are so important, the least user
2457     * interaction will cause them to reappear immediately.  When this happens, both
2458     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2459     * so that both elements reappear at the same time.
2460     *
2461     * @see #setSystemUiVisibility(int)
2462     */
2463    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2464
2465    /**
2466     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2467     * into the normal fullscreen mode so that its content can take over the screen
2468     * while still allowing the user to interact with the application.
2469     *
2470     * <p>This has the same visual effect as
2471     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2472     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2473     * meaning that non-critical screen decorations (such as the status bar) will be
2474     * hidden while the user is in the View's window, focusing the experience on
2475     * that content.  Unlike the window flag, if you are using ActionBar in
2476     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2477     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2478     * hide the action bar.
2479     *
2480     * <p>This approach to going fullscreen is best used over the window flag when
2481     * it is a transient state -- that is, the application does this at certain
2482     * points in its user interaction where it wants to allow the user to focus
2483     * on content, but not as a continuous state.  For situations where the application
2484     * would like to simply stay full screen the entire time (such as a game that
2485     * wants to take over the screen), the
2486     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2487     * is usually a better approach.  The state set here will be removed by the system
2488     * in various situations (such as the user moving to another application) like
2489     * the other system UI states.
2490     *
2491     * <p>When using this flag, the application should provide some easy facility
2492     * for the user to go out of it.  A common example would be in an e-book
2493     * reader, where tapping on the screen brings back whatever screen and UI
2494     * decorations that had been hidden while the user was immersed in reading
2495     * the book.
2496     *
2497     * @see #setSystemUiVisibility(int)
2498     */
2499    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2500
2501    /**
2502     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2503     * flags, we would like a stable view of the content insets given to
2504     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2505     * will always represent the worst case that the application can expect
2506     * as a continuous state.  In the stock Android UI this is the space for
2507     * the system bar, nav bar, and status bar, but not more transient elements
2508     * such as an input method.
2509     *
2510     * The stable layout your UI sees is based on the system UI modes you can
2511     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2512     * then you will get a stable layout for changes of the
2513     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2514     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2515     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2516     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2517     * with a stable layout.  (Note that you should avoid using
2518     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2519     *
2520     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2521     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2522     * then a hidden status bar will be considered a "stable" state for purposes
2523     * here.  This allows your UI to continually hide the status bar, while still
2524     * using the system UI flags to hide the action bar while still retaining
2525     * a stable layout.  Note that changing the window fullscreen flag will never
2526     * provide a stable layout for a clean transition.
2527     *
2528     * <p>If you are using ActionBar in
2529     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2530     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2531     * insets it adds to those given to the application.
2532     */
2533    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2534
2535    /**
2536     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2537     * to be laid out as if it has requested
2538     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2539     * allows it to avoid artifacts when switching in and out of that mode, at
2540     * the expense that some of its user interface may be covered by screen
2541     * decorations when they are shown.  You can perform layout of your inner
2542     * UI elements to account for the navigation system UI through the
2543     * {@link #fitSystemWindows(Rect)} method.
2544     */
2545    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2546
2547    /**
2548     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2549     * to be laid out as if it has requested
2550     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2551     * allows it to avoid artifacts when switching in and out of that mode, at
2552     * the expense that some of its user interface may be covered by screen
2553     * decorations when they are shown.  You can perform layout of your inner
2554     * UI elements to account for non-fullscreen system UI through the
2555     * {@link #fitSystemWindows(Rect)} method.
2556     */
2557    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2558
2559    /**
2560     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2561     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2562     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2563     * user interaction.
2564     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2565     * has an effect when used in combination with that flag.</p>
2566     */
2567    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2568
2569    /**
2570     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2571     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2572     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2573     * experience while also hiding the system bars.  If this flag is not set,
2574     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2575     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2576     * if the user swipes from the top of the screen.
2577     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2578     * system gestures, such as swiping from the top of the screen.  These transient system bars
2579     * will overlay app’s content, may have some degree of transparency, and will automatically
2580     * hide after a short timeout.
2581     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2582     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2583     * with one or both of those flags.</p>
2584     */
2585    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2586
2587    /**
2588     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2589     * is compatible with light status bar backgrounds.
2590     *
2591     * <p>For this to take effect, the window must request
2592     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2593     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2594     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2595     *         FLAG_TRANSLUCENT_STATUS}.
2596     *
2597     * @see android.R.attr#windowLightStatusBar
2598     */
2599    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2600
2601    /**
2602     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2603     */
2604    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2605
2606    /**
2607     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2608     */
2609    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2610
2611    /**
2612     * @hide
2613     *
2614     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2615     * out of the public fields to keep the undefined bits out of the developer's way.
2616     *
2617     * Flag to make the status bar not expandable.  Unless you also
2618     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2619     */
2620    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2621
2622    /**
2623     * @hide
2624     *
2625     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2626     * out of the public fields to keep the undefined bits out of the developer's way.
2627     *
2628     * Flag to hide notification icons and scrolling ticker text.
2629     */
2630    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2631
2632    /**
2633     * @hide
2634     *
2635     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2636     * out of the public fields to keep the undefined bits out of the developer's way.
2637     *
2638     * Flag to disable incoming notification alerts.  This will not block
2639     * icons, but it will block sound, vibrating and other visual or aural notifications.
2640     */
2641    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2642
2643    /**
2644     * @hide
2645     *
2646     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2647     * out of the public fields to keep the undefined bits out of the developer's way.
2648     *
2649     * Flag to hide only the scrolling ticker.  Note that
2650     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2651     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2652     */
2653    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2654
2655    /**
2656     * @hide
2657     *
2658     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2659     * out of the public fields to keep the undefined bits out of the developer's way.
2660     *
2661     * Flag to hide the center system info area.
2662     */
2663    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2664
2665    /**
2666     * @hide
2667     *
2668     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2669     * out of the public fields to keep the undefined bits out of the developer's way.
2670     *
2671     * Flag to hide only the home button.  Don't use this
2672     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2673     */
2674    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2675
2676    /**
2677     * @hide
2678     *
2679     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2680     * out of the public fields to keep the undefined bits out of the developer's way.
2681     *
2682     * Flag to hide only the back button. Don't use this
2683     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2684     */
2685    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2686
2687    /**
2688     * @hide
2689     *
2690     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2691     * out of the public fields to keep the undefined bits out of the developer's way.
2692     *
2693     * Flag to hide only the clock.  You might use this if your activity has
2694     * its own clock making the status bar's clock redundant.
2695     */
2696    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2697
2698    /**
2699     * @hide
2700     *
2701     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2702     * out of the public fields to keep the undefined bits out of the developer's way.
2703     *
2704     * Flag to hide only the recent apps button. Don't use this
2705     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2706     */
2707    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
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 disable the global search gesture. Don't use this
2716     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2717     */
2718    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2719
2720    /**
2721     * @hide
2722     *
2723     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2724     * out of the public fields to keep the undefined bits out of the developer's way.
2725     *
2726     * Flag to specify that the status bar is displayed in transient mode.
2727     */
2728    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2729
2730    /**
2731     * @hide
2732     *
2733     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2734     * out of the public fields to keep the undefined bits out of the developer's way.
2735     *
2736     * Flag to specify that the navigation bar is displayed in transient mode.
2737     */
2738    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2739
2740    /**
2741     * @hide
2742     *
2743     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2744     * out of the public fields to keep the undefined bits out of the developer's way.
2745     *
2746     * Flag to specify that the hidden status bar would like to be shown.
2747     */
2748    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2749
2750    /**
2751     * @hide
2752     *
2753     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2754     * out of the public fields to keep the undefined bits out of the developer's way.
2755     *
2756     * Flag to specify that the hidden navigation bar would like to be shown.
2757     */
2758    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2759
2760    /**
2761     * @hide
2762     *
2763     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2764     * out of the public fields to keep the undefined bits out of the developer's way.
2765     *
2766     * Flag to specify that the status bar is displayed in translucent mode.
2767     */
2768    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2769
2770    /**
2771     * @hide
2772     *
2773     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2774     * out of the public fields to keep the undefined bits out of the developer's way.
2775     *
2776     * Flag to specify that the navigation bar is displayed in translucent mode.
2777     */
2778    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2779
2780    /**
2781     * @hide
2782     *
2783     * Whether Recents is visible or not.
2784     */
2785    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2786
2787    /**
2788     * @hide
2789     *
2790     * Makes system ui transparent.
2791     */
2792    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2793
2794    /**
2795     * @hide
2796     */
2797    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2798
2799    /**
2800     * These are the system UI flags that can be cleared by events outside
2801     * of an application.  Currently this is just the ability to tap on the
2802     * screen while hiding the navigation bar to have it return.
2803     * @hide
2804     */
2805    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2806            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2807            | SYSTEM_UI_FLAG_FULLSCREEN;
2808
2809    /**
2810     * Flags that can impact the layout in relation to system UI.
2811     */
2812    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2813            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2814            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2815
2816    /** @hide */
2817    @IntDef(flag = true,
2818            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2819    @Retention(RetentionPolicy.SOURCE)
2820    public @interface FindViewFlags {}
2821
2822    /**
2823     * Find views that render the specified text.
2824     *
2825     * @see #findViewsWithText(ArrayList, CharSequence, int)
2826     */
2827    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2828
2829    /**
2830     * Find find views that contain the specified content description.
2831     *
2832     * @see #findViewsWithText(ArrayList, CharSequence, int)
2833     */
2834    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2835
2836    /**
2837     * Find views that contain {@link AccessibilityNodeProvider}. Such
2838     * a View is a root of virtual view hierarchy and may contain the searched
2839     * text. If this flag is set Views with providers are automatically
2840     * added and it is a responsibility of the client to call the APIs of
2841     * the provider to determine whether the virtual tree rooted at this View
2842     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2843     * representing the virtual views with this text.
2844     *
2845     * @see #findViewsWithText(ArrayList, CharSequence, int)
2846     *
2847     * @hide
2848     */
2849    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2850
2851    /**
2852     * The undefined cursor position.
2853     *
2854     * @hide
2855     */
2856    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2857
2858    /**
2859     * Indicates that the screen has changed state and is now off.
2860     *
2861     * @see #onScreenStateChanged(int)
2862     */
2863    public static final int SCREEN_STATE_OFF = 0x0;
2864
2865    /**
2866     * Indicates that the screen has changed state and is now on.
2867     *
2868     * @see #onScreenStateChanged(int)
2869     */
2870    public static final int SCREEN_STATE_ON = 0x1;
2871
2872    /**
2873     * Indicates no axis of view scrolling.
2874     */
2875    public static final int SCROLL_AXIS_NONE = 0;
2876
2877    /**
2878     * Indicates scrolling along the horizontal axis.
2879     */
2880    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2881
2882    /**
2883     * Indicates scrolling along the vertical axis.
2884     */
2885    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2886
2887    /**
2888     * Controls the over-scroll mode for this view.
2889     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2890     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2891     * and {@link #OVER_SCROLL_NEVER}.
2892     */
2893    private int mOverScrollMode;
2894
2895    /**
2896     * The parent this view is attached to.
2897     * {@hide}
2898     *
2899     * @see #getParent()
2900     */
2901    protected ViewParent mParent;
2902
2903    /**
2904     * {@hide}
2905     */
2906    AttachInfo mAttachInfo;
2907
2908    /**
2909     * {@hide}
2910     */
2911    @ViewDebug.ExportedProperty(flagMapping = {
2912        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2913                name = "FORCE_LAYOUT"),
2914        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2915                name = "LAYOUT_REQUIRED"),
2916        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2917            name = "DRAWING_CACHE_INVALID", outputIf = false),
2918        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2919        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2920        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2921        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2922    }, formatToHexString = true)
2923    int mPrivateFlags;
2924    int mPrivateFlags2;
2925    int mPrivateFlags3;
2926
2927    /**
2928     * This view's request for the visibility of the status bar.
2929     * @hide
2930     */
2931    @ViewDebug.ExportedProperty(flagMapping = {
2932        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2933                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2934                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2935        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2936                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2937                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2938        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2939                                equals = SYSTEM_UI_FLAG_VISIBLE,
2940                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2941    }, formatToHexString = true)
2942    int mSystemUiVisibility;
2943
2944    /**
2945     * Reference count for transient state.
2946     * @see #setHasTransientState(boolean)
2947     */
2948    int mTransientStateCount = 0;
2949
2950    /**
2951     * Count of how many windows this view has been attached to.
2952     */
2953    int mWindowAttachCount;
2954
2955    /**
2956     * The layout parameters associated with this view and used by the parent
2957     * {@link android.view.ViewGroup} to determine how this view should be
2958     * laid out.
2959     * {@hide}
2960     */
2961    protected ViewGroup.LayoutParams mLayoutParams;
2962
2963    /**
2964     * The view flags hold various views states.
2965     * {@hide}
2966     */
2967    @ViewDebug.ExportedProperty(formatToHexString = true)
2968    int mViewFlags;
2969
2970    static class TransformationInfo {
2971        /**
2972         * The transform matrix for the View. This transform is calculated internally
2973         * based on the translation, rotation, and scale properties.
2974         *
2975         * Do *not* use this variable directly; instead call getMatrix(), which will
2976         * load the value from the View's RenderNode.
2977         */
2978        private final Matrix mMatrix = new Matrix();
2979
2980        /**
2981         * The inverse transform matrix for the View. This transform is calculated
2982         * internally based on the translation, rotation, and scale properties.
2983         *
2984         * Do *not* use this variable directly; instead call getInverseMatrix(),
2985         * which will load the value from the View's RenderNode.
2986         */
2987        private Matrix mInverseMatrix;
2988
2989        /**
2990         * The opacity of the View. This is a value from 0 to 1, where 0 means
2991         * completely transparent and 1 means completely opaque.
2992         */
2993        @ViewDebug.ExportedProperty
2994        float mAlpha = 1f;
2995
2996        /**
2997         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2998         * property only used by transitions, which is composited with the other alpha
2999         * values to calculate the final visual alpha value.
3000         */
3001        float mTransitionAlpha = 1f;
3002    }
3003
3004    TransformationInfo mTransformationInfo;
3005
3006    /**
3007     * Current clip bounds. to which all drawing of this view are constrained.
3008     */
3009    Rect mClipBounds = null;
3010
3011    private boolean mLastIsOpaque;
3012
3013    /**
3014     * The distance in pixels from the left edge of this view's parent
3015     * to the left edge of this view.
3016     * {@hide}
3017     */
3018    @ViewDebug.ExportedProperty(category = "layout")
3019    protected int mLeft;
3020    /**
3021     * The distance in pixels from the left edge of this view's parent
3022     * to the right edge of this view.
3023     * {@hide}
3024     */
3025    @ViewDebug.ExportedProperty(category = "layout")
3026    protected int mRight;
3027    /**
3028     * The distance in pixels from the top edge of this view's parent
3029     * to the top edge of this view.
3030     * {@hide}
3031     */
3032    @ViewDebug.ExportedProperty(category = "layout")
3033    protected int mTop;
3034    /**
3035     * The distance in pixels from the top edge of this view's parent
3036     * to the bottom edge of this view.
3037     * {@hide}
3038     */
3039    @ViewDebug.ExportedProperty(category = "layout")
3040    protected int mBottom;
3041
3042    /**
3043     * The offset, in pixels, by which the content of this view is scrolled
3044     * horizontally.
3045     * {@hide}
3046     */
3047    @ViewDebug.ExportedProperty(category = "scrolling")
3048    protected int mScrollX;
3049    /**
3050     * The offset, in pixels, by which the content of this view is scrolled
3051     * vertically.
3052     * {@hide}
3053     */
3054    @ViewDebug.ExportedProperty(category = "scrolling")
3055    protected int mScrollY;
3056
3057    /**
3058     * The left padding in pixels, that is the distance in pixels between the
3059     * left edge of this view and the left edge of its content.
3060     * {@hide}
3061     */
3062    @ViewDebug.ExportedProperty(category = "padding")
3063    protected int mPaddingLeft = 0;
3064    /**
3065     * The right padding in pixels, that is the distance in pixels between the
3066     * right edge of this view and the right edge of its content.
3067     * {@hide}
3068     */
3069    @ViewDebug.ExportedProperty(category = "padding")
3070    protected int mPaddingRight = 0;
3071    /**
3072     * The top padding in pixels, that is the distance in pixels between the
3073     * top edge of this view and the top edge of its content.
3074     * {@hide}
3075     */
3076    @ViewDebug.ExportedProperty(category = "padding")
3077    protected int mPaddingTop;
3078    /**
3079     * The bottom padding in pixels, that is the distance in pixels between the
3080     * bottom edge of this view and the bottom edge of its content.
3081     * {@hide}
3082     */
3083    @ViewDebug.ExportedProperty(category = "padding")
3084    protected int mPaddingBottom;
3085
3086    /**
3087     * The layout insets in pixels, that is the distance in pixels between the
3088     * visible edges of this view its bounds.
3089     */
3090    private Insets mLayoutInsets;
3091
3092    /**
3093     * Briefly describes the view and is primarily used for accessibility support.
3094     */
3095    private CharSequence mContentDescription;
3096
3097    /**
3098     * Specifies the id of a view for which this view serves as a label for
3099     * accessibility purposes.
3100     */
3101    private int mLabelForId = View.NO_ID;
3102
3103    /**
3104     * Predicate for matching labeled view id with its label for
3105     * accessibility purposes.
3106     */
3107    private MatchLabelForPredicate mMatchLabelForPredicate;
3108
3109    /**
3110     * Specifies a view before which this one is visited in accessibility traversal.
3111     */
3112    private int mAccessibilityTraversalBeforeId = NO_ID;
3113
3114    /**
3115     * Specifies a view after which this one is visited in accessibility traversal.
3116     */
3117    private int mAccessibilityTraversalAfterId = NO_ID;
3118
3119    /**
3120     * Predicate for matching a view by its id.
3121     */
3122    private MatchIdPredicate mMatchIdPredicate;
3123
3124    /**
3125     * Cache the paddingRight set by the user to append to the scrollbar's size.
3126     *
3127     * @hide
3128     */
3129    @ViewDebug.ExportedProperty(category = "padding")
3130    protected int mUserPaddingRight;
3131
3132    /**
3133     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3134     *
3135     * @hide
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    protected int mUserPaddingBottom;
3139
3140    /**
3141     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3142     *
3143     * @hide
3144     */
3145    @ViewDebug.ExportedProperty(category = "padding")
3146    protected int mUserPaddingLeft;
3147
3148    /**
3149     * Cache the paddingStart set by the user to append to the scrollbar's size.
3150     *
3151     */
3152    @ViewDebug.ExportedProperty(category = "padding")
3153    int mUserPaddingStart;
3154
3155    /**
3156     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3157     *
3158     */
3159    @ViewDebug.ExportedProperty(category = "padding")
3160    int mUserPaddingEnd;
3161
3162    /**
3163     * Cache initial left padding.
3164     *
3165     * @hide
3166     */
3167    int mUserPaddingLeftInitial;
3168
3169    /**
3170     * Cache initial right padding.
3171     *
3172     * @hide
3173     */
3174    int mUserPaddingRightInitial;
3175
3176    /**
3177     * Default undefined padding
3178     */
3179    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3180
3181    /**
3182     * Cache if a left padding has been defined
3183     */
3184    private boolean mLeftPaddingDefined = false;
3185
3186    /**
3187     * Cache if a right padding has been defined
3188     */
3189    private boolean mRightPaddingDefined = false;
3190
3191    /**
3192     * @hide
3193     */
3194    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3195    /**
3196     * @hide
3197     */
3198    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3199
3200    private LongSparseLongArray mMeasureCache;
3201
3202    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3203    private Drawable mBackground;
3204    private TintInfo mBackgroundTint;
3205
3206    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3207    private ForegroundInfo mForegroundInfo;
3208
3209    /**
3210     * RenderNode used for backgrounds.
3211     * <p>
3212     * When non-null and valid, this is expected to contain an up-to-date copy
3213     * of the background drawable. It is cleared on temporary detach, and reset
3214     * on cleanup.
3215     */
3216    private RenderNode mBackgroundRenderNode;
3217
3218    private int mBackgroundResource;
3219    private boolean mBackgroundSizeChanged;
3220
3221    private String mTransitionName;
3222
3223    static class TintInfo {
3224        ColorStateList mTintList;
3225        PorterDuff.Mode mTintMode;
3226        boolean mHasTintMode;
3227        boolean mHasTintList;
3228    }
3229
3230    private static class ForegroundInfo {
3231        private Drawable mDrawable;
3232        private TintInfo mTintInfo;
3233        private int mGravity = Gravity.FILL;
3234        private boolean mInsidePadding = true;
3235        private boolean mBoundsChanged = true;
3236        private final Rect mSelfBounds = new Rect();
3237        private final Rect mOverlayBounds = new Rect();
3238    }
3239
3240    static class ListenerInfo {
3241        /**
3242         * Listener used to dispatch focus change events.
3243         * This field should be made private, so it is hidden from the SDK.
3244         * {@hide}
3245         */
3246        protected OnFocusChangeListener mOnFocusChangeListener;
3247
3248        /**
3249         * Listeners for layout change events.
3250         */
3251        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3252
3253        protected OnScrollChangeListener mOnScrollChangeListener;
3254
3255        /**
3256         * Listeners for attach events.
3257         */
3258        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3259
3260        /**
3261         * Listener used to dispatch click events.
3262         * This field should be made private, so it is hidden from the SDK.
3263         * {@hide}
3264         */
3265        public OnClickListener mOnClickListener;
3266
3267        /**
3268         * Listener used to dispatch long click events.
3269         * This field should be made private, so it is hidden from the SDK.
3270         * {@hide}
3271         */
3272        protected OnLongClickListener mOnLongClickListener;
3273
3274        /**
3275         * Listener used to build the context menu.
3276         * This field should be made private, so it is hidden from the SDK.
3277         * {@hide}
3278         */
3279        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3280
3281        private OnKeyListener mOnKeyListener;
3282
3283        private OnTouchListener mOnTouchListener;
3284
3285        private OnHoverListener mOnHoverListener;
3286
3287        private OnGenericMotionListener mOnGenericMotionListener;
3288
3289        private OnDragListener mOnDragListener;
3290
3291        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3292
3293        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3294    }
3295
3296    ListenerInfo mListenerInfo;
3297
3298    /**
3299     * The application environment this view lives in.
3300     * This field should be made private, so it is hidden from the SDK.
3301     * {@hide}
3302     */
3303    @ViewDebug.ExportedProperty(deepExport = true)
3304    protected Context mContext;
3305
3306    private final Resources mResources;
3307
3308    private ScrollabilityCache mScrollCache;
3309
3310    private int[] mDrawableState = null;
3311
3312    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3313
3314    /**
3315     * Animator that automatically runs based on state changes.
3316     */
3317    private StateListAnimator mStateListAnimator;
3318
3319    /**
3320     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3321     * the user may specify which view to go to next.
3322     */
3323    private int mNextFocusLeftId = View.NO_ID;
3324
3325    /**
3326     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3327     * the user may specify which view to go to next.
3328     */
3329    private int mNextFocusRightId = View.NO_ID;
3330
3331    /**
3332     * When this view has focus and the next focus is {@link #FOCUS_UP},
3333     * the user may specify which view to go to next.
3334     */
3335    private int mNextFocusUpId = View.NO_ID;
3336
3337    /**
3338     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3339     * the user may specify which view to go to next.
3340     */
3341    private int mNextFocusDownId = View.NO_ID;
3342
3343    /**
3344     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3345     * the user may specify which view to go to next.
3346     */
3347    int mNextFocusForwardId = View.NO_ID;
3348
3349    private CheckForLongPress mPendingCheckForLongPress;
3350    private CheckForTap mPendingCheckForTap = null;
3351    private PerformClick mPerformClick;
3352    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3353
3354    private UnsetPressedState mUnsetPressedState;
3355
3356    /**
3357     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3358     * up event while a long press is invoked as soon as the long press duration is reached, so
3359     * a long press could be performed before the tap is checked, in which case the tap's action
3360     * should not be invoked.
3361     */
3362    private boolean mHasPerformedLongPress;
3363
3364    /**
3365     * The minimum height of the view. We'll try our best to have the height
3366     * of this view to at least this amount.
3367     */
3368    @ViewDebug.ExportedProperty(category = "measurement")
3369    private int mMinHeight;
3370
3371    /**
3372     * The minimum width of the view. We'll try our best to have the width
3373     * of this view to at least this amount.
3374     */
3375    @ViewDebug.ExportedProperty(category = "measurement")
3376    private int mMinWidth;
3377
3378    /**
3379     * The delegate to handle touch events that are physically in this view
3380     * but should be handled by another view.
3381     */
3382    private TouchDelegate mTouchDelegate = null;
3383
3384    /**
3385     * Solid color to use as a background when creating the drawing cache. Enables
3386     * the cache to use 16 bit bitmaps instead of 32 bit.
3387     */
3388    private int mDrawingCacheBackgroundColor = 0;
3389
3390    /**
3391     * Special tree observer used when mAttachInfo is null.
3392     */
3393    private ViewTreeObserver mFloatingTreeObserver;
3394
3395    /**
3396     * Cache the touch slop from the context that created the view.
3397     */
3398    private int mTouchSlop;
3399
3400    /**
3401     * Object that handles automatic animation of view properties.
3402     */
3403    private ViewPropertyAnimator mAnimator = null;
3404
3405    /**
3406     * Flag indicating that a drag can cross window boundaries.  When
3407     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3408     * with this flag set, all visible applications will be able to participate
3409     * in the drag operation and receive the dragged content.
3410     *
3411     * @hide
3412     */
3413    public static final int DRAG_FLAG_GLOBAL = 1;
3414
3415    /**
3416     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3417     */
3418    private float mVerticalScrollFactor;
3419
3420    /**
3421     * Position of the vertical scroll bar.
3422     */
3423    private int mVerticalScrollbarPosition;
3424
3425    /**
3426     * Position the scroll bar at the default position as determined by the system.
3427     */
3428    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3429
3430    /**
3431     * Position the scroll bar along the left edge.
3432     */
3433    public static final int SCROLLBAR_POSITION_LEFT = 1;
3434
3435    /**
3436     * Position the scroll bar along the right edge.
3437     */
3438    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3439
3440    /**
3441     * Indicates that the view does not have a layer.
3442     *
3443     * @see #getLayerType()
3444     * @see #setLayerType(int, android.graphics.Paint)
3445     * @see #LAYER_TYPE_SOFTWARE
3446     * @see #LAYER_TYPE_HARDWARE
3447     */
3448    public static final int LAYER_TYPE_NONE = 0;
3449
3450    /**
3451     * <p>Indicates that the view has a software layer. A software layer is backed
3452     * by a bitmap and causes the view to be rendered using Android's software
3453     * rendering pipeline, even if hardware acceleration is enabled.</p>
3454     *
3455     * <p>Software layers have various usages:</p>
3456     * <p>When the application is not using hardware acceleration, a software layer
3457     * is useful to apply a specific color filter and/or blending mode and/or
3458     * translucency to a view and all its children.</p>
3459     * <p>When the application is using hardware acceleration, a software layer
3460     * is useful to render drawing primitives not supported by the hardware
3461     * accelerated pipeline. It can also be used to cache a complex view tree
3462     * into a texture and reduce the complexity of drawing operations. For instance,
3463     * when animating a complex view tree with a translation, a software layer can
3464     * be used to render the view tree only once.</p>
3465     * <p>Software layers should be avoided when the affected view tree updates
3466     * often. Every update will require to re-render the software layer, which can
3467     * potentially be slow (particularly when hardware acceleration is turned on
3468     * since the layer will have to be uploaded into a hardware texture after every
3469     * update.)</p>
3470     *
3471     * @see #getLayerType()
3472     * @see #setLayerType(int, android.graphics.Paint)
3473     * @see #LAYER_TYPE_NONE
3474     * @see #LAYER_TYPE_HARDWARE
3475     */
3476    public static final int LAYER_TYPE_SOFTWARE = 1;
3477
3478    /**
3479     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3480     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3481     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3482     * rendering pipeline, but only if hardware acceleration is turned on for the
3483     * view hierarchy. When hardware acceleration is turned off, hardware layers
3484     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3485     *
3486     * <p>A hardware layer is useful to apply a specific color filter and/or
3487     * blending mode and/or translucency to a view and all its children.</p>
3488     * <p>A hardware layer can be used to cache a complex view tree into a
3489     * texture and reduce the complexity of drawing operations. For instance,
3490     * when animating a complex view tree with a translation, a hardware layer can
3491     * be used to render the view tree only once.</p>
3492     * <p>A hardware layer can also be used to increase the rendering quality when
3493     * rotation transformations are applied on a view. It can also be used to
3494     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3495     *
3496     * @see #getLayerType()
3497     * @see #setLayerType(int, android.graphics.Paint)
3498     * @see #LAYER_TYPE_NONE
3499     * @see #LAYER_TYPE_SOFTWARE
3500     */
3501    public static final int LAYER_TYPE_HARDWARE = 2;
3502
3503    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3504            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3505            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3506            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3507    })
3508    int mLayerType = LAYER_TYPE_NONE;
3509    Paint mLayerPaint;
3510
3511    /**
3512     * Set to true when drawing cache is enabled and cannot be created.
3513     *
3514     * @hide
3515     */
3516    public boolean mCachingFailed;
3517    private Bitmap mDrawingCache;
3518    private Bitmap mUnscaledDrawingCache;
3519
3520    /**
3521     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3522     * <p>
3523     * When non-null and valid, this is expected to contain an up-to-date copy
3524     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3525     * cleanup.
3526     */
3527    final RenderNode mRenderNode;
3528
3529    /**
3530     * Set to true when the view is sending hover accessibility events because it
3531     * is the innermost hovered view.
3532     */
3533    private boolean mSendingHoverAccessibilityEvents;
3534
3535    /**
3536     * Delegate for injecting accessibility functionality.
3537     */
3538    AccessibilityDelegate mAccessibilityDelegate;
3539
3540    /**
3541     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3542     * and add/remove objects to/from the overlay directly through the Overlay methods.
3543     */
3544    ViewOverlay mOverlay;
3545
3546    /**
3547     * The currently active parent view for receiving delegated nested scrolling events.
3548     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3549     * by {@link #stopNestedScroll()} at the same point where we clear
3550     * requestDisallowInterceptTouchEvent.
3551     */
3552    private ViewParent mNestedScrollingParent;
3553
3554    /**
3555     * Consistency verifier for debugging purposes.
3556     * @hide
3557     */
3558    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3559            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3560                    new InputEventConsistencyVerifier(this, 0) : null;
3561
3562    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3563
3564    private int[] mTempNestedScrollConsumed;
3565
3566    /**
3567     * An overlay is going to draw this View instead of being drawn as part of this
3568     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3569     * when this view is invalidated.
3570     */
3571    GhostView mGhostView;
3572
3573    /**
3574     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3575     * @hide
3576     */
3577    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3578    public String[] mAttributes;
3579
3580    /**
3581     * Maps a Resource id to its name.
3582     */
3583    private static SparseArray<String> mAttributeMap;
3584
3585    /**
3586     * @hide
3587     */
3588    String mStartActivityRequestWho;
3589
3590    /**
3591     * Simple constructor to use when creating a view from code.
3592     *
3593     * @param context The Context the view is running in, through which it can
3594     *        access the current theme, resources, etc.
3595     */
3596    public View(Context context) {
3597        mContext = context;
3598        mResources = context != null ? context.getResources() : null;
3599        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3600        // Set some flags defaults
3601        mPrivateFlags2 =
3602                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3603                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3604                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3605                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3606                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3607                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3608        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3609        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3610        mUserPaddingStart = UNDEFINED_PADDING;
3611        mUserPaddingEnd = UNDEFINED_PADDING;
3612        mRenderNode = RenderNode.create(getClass().getName(), this);
3613
3614        if (!sCompatibilityDone && context != null) {
3615            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3616
3617            // Older apps may need this compatibility hack for measurement.
3618            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3619
3620            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3621            // of whether a layout was requested on that View.
3622            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3623
3624            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3625
3626            sCompatibilityDone = true;
3627        }
3628    }
3629
3630    /**
3631     * Constructor that is called when inflating a view from XML. This is called
3632     * when a view is being constructed from an XML file, supplying attributes
3633     * that were specified in the XML file. This version uses a default style of
3634     * 0, so the only attribute values applied are those in the Context's Theme
3635     * and the given AttributeSet.
3636     *
3637     * <p>
3638     * The method onFinishInflate() will be called after all children have been
3639     * added.
3640     *
3641     * @param context The Context the view is running in, through which it can
3642     *        access the current theme, resources, etc.
3643     * @param attrs The attributes of the XML tag that is inflating the view.
3644     * @see #View(Context, AttributeSet, int)
3645     */
3646    public View(Context context, @Nullable AttributeSet attrs) {
3647        this(context, attrs, 0);
3648    }
3649
3650    /**
3651     * Perform inflation from XML and apply a class-specific base style from a
3652     * theme attribute. This constructor of View allows subclasses to use their
3653     * own base style when they are inflating. For example, a Button class's
3654     * constructor would call this version of the super class constructor and
3655     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3656     * allows the theme's button style to modify all of the base view attributes
3657     * (in particular its background) as well as the Button class's attributes.
3658     *
3659     * @param context The Context the view is running in, through which it can
3660     *        access the current theme, resources, etc.
3661     * @param attrs The attributes of the XML tag that is inflating the view.
3662     * @param defStyleAttr An attribute in the current theme that contains a
3663     *        reference to a style resource that supplies default values for
3664     *        the view. Can be 0 to not look for defaults.
3665     * @see #View(Context, AttributeSet)
3666     */
3667    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3668        this(context, attrs, defStyleAttr, 0);
3669    }
3670
3671    /**
3672     * Perform inflation from XML and apply a class-specific base style from a
3673     * theme attribute or style resource. This constructor of View allows
3674     * subclasses to use their own base style when they are inflating.
3675     * <p>
3676     * When determining the final value of a particular attribute, there are
3677     * four inputs that come into play:
3678     * <ol>
3679     * <li>Any attribute values in the given AttributeSet.
3680     * <li>The style resource specified in the AttributeSet (named "style").
3681     * <li>The default style specified by <var>defStyleAttr</var>.
3682     * <li>The default style specified by <var>defStyleRes</var>.
3683     * <li>The base values in this theme.
3684     * </ol>
3685     * <p>
3686     * Each of these inputs is considered in-order, with the first listed taking
3687     * precedence over the following ones. In other words, if in the
3688     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3689     * , then the button's text will <em>always</em> be black, regardless of
3690     * what is specified in any of the styles.
3691     *
3692     * @param context The Context the view is running in, through which it can
3693     *        access the current theme, resources, etc.
3694     * @param attrs The attributes of the XML tag that is inflating the view.
3695     * @param defStyleAttr An attribute in the current theme that contains a
3696     *        reference to a style resource that supplies default values for
3697     *        the view. Can be 0 to not look for defaults.
3698     * @param defStyleRes A resource identifier of a style resource that
3699     *        supplies default values for the view, used only if
3700     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3701     *        to not look for defaults.
3702     * @see #View(Context, AttributeSet, int)
3703     */
3704    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3705        this(context);
3706
3707        final TypedArray a = context.obtainStyledAttributes(
3708                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3709
3710        if (mDebugViewAttributes) {
3711            saveAttributeData(attrs, a);
3712        }
3713
3714        Drawable background = null;
3715
3716        int leftPadding = -1;
3717        int topPadding = -1;
3718        int rightPadding = -1;
3719        int bottomPadding = -1;
3720        int startPadding = UNDEFINED_PADDING;
3721        int endPadding = UNDEFINED_PADDING;
3722
3723        int padding = -1;
3724
3725        int viewFlagValues = 0;
3726        int viewFlagMasks = 0;
3727
3728        boolean setScrollContainer = false;
3729
3730        int x = 0;
3731        int y = 0;
3732
3733        float tx = 0;
3734        float ty = 0;
3735        float tz = 0;
3736        float elevation = 0;
3737        float rotation = 0;
3738        float rotationX = 0;
3739        float rotationY = 0;
3740        float sx = 1f;
3741        float sy = 1f;
3742        boolean transformSet = false;
3743
3744        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3745        int overScrollMode = mOverScrollMode;
3746        boolean initializeScrollbars = false;
3747
3748        boolean startPaddingDefined = false;
3749        boolean endPaddingDefined = false;
3750        boolean leftPaddingDefined = false;
3751        boolean rightPaddingDefined = false;
3752
3753        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3754
3755        final int N = a.getIndexCount();
3756        for (int i = 0; i < N; i++) {
3757            int attr = a.getIndex(i);
3758            switch (attr) {
3759                case com.android.internal.R.styleable.View_background:
3760                    background = a.getDrawable(attr);
3761                    break;
3762                case com.android.internal.R.styleable.View_padding:
3763                    padding = a.getDimensionPixelSize(attr, -1);
3764                    mUserPaddingLeftInitial = padding;
3765                    mUserPaddingRightInitial = padding;
3766                    leftPaddingDefined = true;
3767                    rightPaddingDefined = true;
3768                    break;
3769                 case com.android.internal.R.styleable.View_paddingLeft:
3770                    leftPadding = a.getDimensionPixelSize(attr, -1);
3771                    mUserPaddingLeftInitial = leftPadding;
3772                    leftPaddingDefined = true;
3773                    break;
3774                case com.android.internal.R.styleable.View_paddingTop:
3775                    topPadding = a.getDimensionPixelSize(attr, -1);
3776                    break;
3777                case com.android.internal.R.styleable.View_paddingRight:
3778                    rightPadding = a.getDimensionPixelSize(attr, -1);
3779                    mUserPaddingRightInitial = rightPadding;
3780                    rightPaddingDefined = true;
3781                    break;
3782                case com.android.internal.R.styleable.View_paddingBottom:
3783                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3784                    break;
3785                case com.android.internal.R.styleable.View_paddingStart:
3786                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3787                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3788                    break;
3789                case com.android.internal.R.styleable.View_paddingEnd:
3790                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3791                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3792                    break;
3793                case com.android.internal.R.styleable.View_scrollX:
3794                    x = a.getDimensionPixelOffset(attr, 0);
3795                    break;
3796                case com.android.internal.R.styleable.View_scrollY:
3797                    y = a.getDimensionPixelOffset(attr, 0);
3798                    break;
3799                case com.android.internal.R.styleable.View_alpha:
3800                    setAlpha(a.getFloat(attr, 1f));
3801                    break;
3802                case com.android.internal.R.styleable.View_transformPivotX:
3803                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3804                    break;
3805                case com.android.internal.R.styleable.View_transformPivotY:
3806                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3807                    break;
3808                case com.android.internal.R.styleable.View_translationX:
3809                    tx = a.getDimensionPixelOffset(attr, 0);
3810                    transformSet = true;
3811                    break;
3812                case com.android.internal.R.styleable.View_translationY:
3813                    ty = a.getDimensionPixelOffset(attr, 0);
3814                    transformSet = true;
3815                    break;
3816                case com.android.internal.R.styleable.View_translationZ:
3817                    tz = a.getDimensionPixelOffset(attr, 0);
3818                    transformSet = true;
3819                    break;
3820                case com.android.internal.R.styleable.View_elevation:
3821                    elevation = a.getDimensionPixelOffset(attr, 0);
3822                    transformSet = true;
3823                    break;
3824                case com.android.internal.R.styleable.View_rotation:
3825                    rotation = a.getFloat(attr, 0);
3826                    transformSet = true;
3827                    break;
3828                case com.android.internal.R.styleable.View_rotationX:
3829                    rotationX = a.getFloat(attr, 0);
3830                    transformSet = true;
3831                    break;
3832                case com.android.internal.R.styleable.View_rotationY:
3833                    rotationY = a.getFloat(attr, 0);
3834                    transformSet = true;
3835                    break;
3836                case com.android.internal.R.styleable.View_scaleX:
3837                    sx = a.getFloat(attr, 1f);
3838                    transformSet = true;
3839                    break;
3840                case com.android.internal.R.styleable.View_scaleY:
3841                    sy = a.getFloat(attr, 1f);
3842                    transformSet = true;
3843                    break;
3844                case com.android.internal.R.styleable.View_id:
3845                    mID = a.getResourceId(attr, NO_ID);
3846                    break;
3847                case com.android.internal.R.styleable.View_tag:
3848                    mTag = a.getText(attr);
3849                    break;
3850                case com.android.internal.R.styleable.View_fitsSystemWindows:
3851                    if (a.getBoolean(attr, false)) {
3852                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3853                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3854                    }
3855                    break;
3856                case com.android.internal.R.styleable.View_focusable:
3857                    if (a.getBoolean(attr, false)) {
3858                        viewFlagValues |= FOCUSABLE;
3859                        viewFlagMasks |= FOCUSABLE_MASK;
3860                    }
3861                    break;
3862                case com.android.internal.R.styleable.View_focusableInTouchMode:
3863                    if (a.getBoolean(attr, false)) {
3864                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3865                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3866                    }
3867                    break;
3868                case com.android.internal.R.styleable.View_clickable:
3869                    if (a.getBoolean(attr, false)) {
3870                        viewFlagValues |= CLICKABLE;
3871                        viewFlagMasks |= CLICKABLE;
3872                    }
3873                    break;
3874                case com.android.internal.R.styleable.View_longClickable:
3875                    if (a.getBoolean(attr, false)) {
3876                        viewFlagValues |= LONG_CLICKABLE;
3877                        viewFlagMasks |= LONG_CLICKABLE;
3878                    }
3879                    break;
3880                case com.android.internal.R.styleable.View_saveEnabled:
3881                    if (!a.getBoolean(attr, true)) {
3882                        viewFlagValues |= SAVE_DISABLED;
3883                        viewFlagMasks |= SAVE_DISABLED_MASK;
3884                    }
3885                    break;
3886                case com.android.internal.R.styleable.View_assistBlocked:
3887                    if (a.getBoolean(attr, false)) {
3888                        mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
3889                    }
3890                    break;
3891                case com.android.internal.R.styleable.View_duplicateParentState:
3892                    if (a.getBoolean(attr, false)) {
3893                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3894                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3895                    }
3896                    break;
3897                case com.android.internal.R.styleable.View_visibility:
3898                    final int visibility = a.getInt(attr, 0);
3899                    if (visibility != 0) {
3900                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3901                        viewFlagMasks |= VISIBILITY_MASK;
3902                    }
3903                    break;
3904                case com.android.internal.R.styleable.View_layoutDirection:
3905                    // Clear any layout direction flags (included resolved bits) already set
3906                    mPrivateFlags2 &=
3907                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3908                    // Set the layout direction flags depending on the value of the attribute
3909                    final int layoutDirection = a.getInt(attr, -1);
3910                    final int value = (layoutDirection != -1) ?
3911                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3912                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3913                    break;
3914                case com.android.internal.R.styleable.View_drawingCacheQuality:
3915                    final int cacheQuality = a.getInt(attr, 0);
3916                    if (cacheQuality != 0) {
3917                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3918                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3919                    }
3920                    break;
3921                case com.android.internal.R.styleable.View_contentDescription:
3922                    setContentDescription(a.getString(attr));
3923                    break;
3924                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3925                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3926                    break;
3927                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3928                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3929                    break;
3930                case com.android.internal.R.styleable.View_labelFor:
3931                    setLabelFor(a.getResourceId(attr, NO_ID));
3932                    break;
3933                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3934                    if (!a.getBoolean(attr, true)) {
3935                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3936                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3937                    }
3938                    break;
3939                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3940                    if (!a.getBoolean(attr, true)) {
3941                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3942                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3943                    }
3944                    break;
3945                case R.styleable.View_scrollbars:
3946                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3947                    if (scrollbars != SCROLLBARS_NONE) {
3948                        viewFlagValues |= scrollbars;
3949                        viewFlagMasks |= SCROLLBARS_MASK;
3950                        initializeScrollbars = true;
3951                    }
3952                    break;
3953                //noinspection deprecation
3954                case R.styleable.View_fadingEdge:
3955                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3956                        // Ignore the attribute starting with ICS
3957                        break;
3958                    }
3959                    // With builds < ICS, fall through and apply fading edges
3960                case R.styleable.View_requiresFadingEdge:
3961                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3962                    if (fadingEdge != FADING_EDGE_NONE) {
3963                        viewFlagValues |= fadingEdge;
3964                        viewFlagMasks |= FADING_EDGE_MASK;
3965                        initializeFadingEdgeInternal(a);
3966                    }
3967                    break;
3968                case R.styleable.View_scrollbarStyle:
3969                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3970                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3971                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3972                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3973                    }
3974                    break;
3975                case R.styleable.View_isScrollContainer:
3976                    setScrollContainer = true;
3977                    if (a.getBoolean(attr, false)) {
3978                        setScrollContainer(true);
3979                    }
3980                    break;
3981                case com.android.internal.R.styleable.View_keepScreenOn:
3982                    if (a.getBoolean(attr, false)) {
3983                        viewFlagValues |= KEEP_SCREEN_ON;
3984                        viewFlagMasks |= KEEP_SCREEN_ON;
3985                    }
3986                    break;
3987                case R.styleable.View_filterTouchesWhenObscured:
3988                    if (a.getBoolean(attr, false)) {
3989                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3990                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3991                    }
3992                    break;
3993                case R.styleable.View_nextFocusLeft:
3994                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3995                    break;
3996                case R.styleable.View_nextFocusRight:
3997                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3998                    break;
3999                case R.styleable.View_nextFocusUp:
4000                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4001                    break;
4002                case R.styleable.View_nextFocusDown:
4003                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4004                    break;
4005                case R.styleable.View_nextFocusForward:
4006                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4007                    break;
4008                case R.styleable.View_minWidth:
4009                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4010                    break;
4011                case R.styleable.View_minHeight:
4012                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4013                    break;
4014                case R.styleable.View_onClick:
4015                    if (context.isRestricted()) {
4016                        throw new IllegalStateException("The android:onClick attribute cannot "
4017                                + "be used within a restricted context");
4018                    }
4019
4020                    final String handlerName = a.getString(attr);
4021                    if (handlerName != null) {
4022                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4023                    }
4024                    break;
4025                case R.styleable.View_overScrollMode:
4026                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4027                    break;
4028                case R.styleable.View_verticalScrollbarPosition:
4029                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4030                    break;
4031                case R.styleable.View_layerType:
4032                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4033                    break;
4034                case R.styleable.View_textDirection:
4035                    // Clear any text direction flag already set
4036                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4037                    // Set the text direction flags depending on the value of the attribute
4038                    final int textDirection = a.getInt(attr, -1);
4039                    if (textDirection != -1) {
4040                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4041                    }
4042                    break;
4043                case R.styleable.View_textAlignment:
4044                    // Clear any text alignment flag already set
4045                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4046                    // Set the text alignment flag depending on the value of the attribute
4047                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4048                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4049                    break;
4050                case R.styleable.View_importantForAccessibility:
4051                    setImportantForAccessibility(a.getInt(attr,
4052                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4053                    break;
4054                case R.styleable.View_accessibilityLiveRegion:
4055                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4056                    break;
4057                case R.styleable.View_transitionName:
4058                    setTransitionName(a.getString(attr));
4059                    break;
4060                case R.styleable.View_nestedScrollingEnabled:
4061                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4062                    break;
4063                case R.styleable.View_stateListAnimator:
4064                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4065                            a.getResourceId(attr, 0)));
4066                    break;
4067                case R.styleable.View_backgroundTint:
4068                    // This will get applied later during setBackground().
4069                    if (mBackgroundTint == null) {
4070                        mBackgroundTint = new TintInfo();
4071                    }
4072                    mBackgroundTint.mTintList = a.getColorStateList(
4073                            R.styleable.View_backgroundTint);
4074                    mBackgroundTint.mHasTintList = true;
4075                    break;
4076                case R.styleable.View_backgroundTintMode:
4077                    // This will get applied later during setBackground().
4078                    if (mBackgroundTint == null) {
4079                        mBackgroundTint = new TintInfo();
4080                    }
4081                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4082                            R.styleable.View_backgroundTintMode, -1), null);
4083                    mBackgroundTint.mHasTintMode = true;
4084                    break;
4085                case R.styleable.View_outlineProvider:
4086                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4087                            PROVIDER_BACKGROUND));
4088                    break;
4089                case R.styleable.View_foreground:
4090                    setForeground(a.getDrawable(attr));
4091                    break;
4092                case R.styleable.View_foregroundGravity:
4093                    setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4094                    break;
4095                case R.styleable.View_foregroundTintMode:
4096                    setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4097                    break;
4098                case R.styleable.View_foregroundTint:
4099                    setForegroundTintList(a.getColorStateList(attr));
4100                    break;
4101                case R.styleable.View_foregroundInsidePadding:
4102                    if (mForegroundInfo == null) {
4103                        mForegroundInfo = new ForegroundInfo();
4104                    }
4105                    mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4106                            mForegroundInfo.mInsidePadding);
4107                    break;
4108            }
4109        }
4110
4111        setOverScrollMode(overScrollMode);
4112
4113        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4114        // the resolved layout direction). Those cached values will be used later during padding
4115        // resolution.
4116        mUserPaddingStart = startPadding;
4117        mUserPaddingEnd = endPadding;
4118
4119        if (background != null) {
4120            setBackground(background);
4121        }
4122
4123        // setBackground above will record that padding is currently provided by the background.
4124        // If we have padding specified via xml, record that here instead and use it.
4125        mLeftPaddingDefined = leftPaddingDefined;
4126        mRightPaddingDefined = rightPaddingDefined;
4127
4128        if (padding >= 0) {
4129            leftPadding = padding;
4130            topPadding = padding;
4131            rightPadding = padding;
4132            bottomPadding = padding;
4133            mUserPaddingLeftInitial = padding;
4134            mUserPaddingRightInitial = padding;
4135        }
4136
4137        if (isRtlCompatibilityMode()) {
4138            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4139            // left / right padding are used if defined (meaning here nothing to do). If they are not
4140            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4141            // start / end and resolve them as left / right (layout direction is not taken into account).
4142            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4143            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4144            // defined.
4145            if (!mLeftPaddingDefined && startPaddingDefined) {
4146                leftPadding = startPadding;
4147            }
4148            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4149            if (!mRightPaddingDefined && endPaddingDefined) {
4150                rightPadding = endPadding;
4151            }
4152            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4153        } else {
4154            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4155            // values defined. Otherwise, left /right values are used.
4156            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4157            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4158            // defined.
4159            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4160
4161            if (mLeftPaddingDefined && !hasRelativePadding) {
4162                mUserPaddingLeftInitial = leftPadding;
4163            }
4164            if (mRightPaddingDefined && !hasRelativePadding) {
4165                mUserPaddingRightInitial = rightPadding;
4166            }
4167        }
4168
4169        internalSetPadding(
4170                mUserPaddingLeftInitial,
4171                topPadding >= 0 ? topPadding : mPaddingTop,
4172                mUserPaddingRightInitial,
4173                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4174
4175        if (viewFlagMasks != 0) {
4176            setFlags(viewFlagValues, viewFlagMasks);
4177        }
4178
4179        if (initializeScrollbars) {
4180            initializeScrollbarsInternal(a);
4181        }
4182
4183        a.recycle();
4184
4185        // Needs to be called after mViewFlags is set
4186        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4187            recomputePadding();
4188        }
4189
4190        if (x != 0 || y != 0) {
4191            scrollTo(x, y);
4192        }
4193
4194        if (transformSet) {
4195            setTranslationX(tx);
4196            setTranslationY(ty);
4197            setTranslationZ(tz);
4198            setElevation(elevation);
4199            setRotation(rotation);
4200            setRotationX(rotationX);
4201            setRotationY(rotationY);
4202            setScaleX(sx);
4203            setScaleY(sy);
4204        }
4205
4206        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4207            setScrollContainer(true);
4208        }
4209
4210        computeOpaqueFlags();
4211    }
4212
4213    /**
4214     * An implementation of OnClickListener that attempts to lazily load a
4215     * named click handling method from a parent or ancestor context.
4216     */
4217    private static class DeclaredOnClickListener implements OnClickListener {
4218        private final View mHostView;
4219        private final String mMethodName;
4220
4221        private Method mMethod;
4222
4223        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4224            mHostView = hostView;
4225            mMethodName = methodName;
4226        }
4227
4228        @Override
4229        public void onClick(@NonNull View v) {
4230            if (mMethod == null) {
4231                mMethod = resolveMethod(mHostView.getContext(), mMethodName);
4232            }
4233
4234            try {
4235                mMethod.invoke(mHostView.getContext(), v);
4236            } catch (IllegalAccessException e) {
4237                throw new IllegalStateException(
4238                        "Could not execute non-public method for android:onClick", e);
4239            } catch (InvocationTargetException e) {
4240                throw new IllegalStateException(
4241                        "Could not execute method for android:onClick", e);
4242            }
4243        }
4244
4245        @NonNull
4246        private Method resolveMethod(@Nullable Context context, @NonNull String name) {
4247            while (context != null) {
4248                try {
4249                    if (!context.isRestricted()) {
4250                        return context.getClass().getMethod(mMethodName, View.class);
4251                    }
4252                } catch (NoSuchMethodException e) {
4253                    // Failed to find method, keep searching up the hierarchy.
4254                }
4255
4256                if (context instanceof ContextWrapper) {
4257                    context = ((ContextWrapper) context).getBaseContext();
4258                } else {
4259                    // Can't search up the hierarchy, null out and fail.
4260                    context = null;
4261                }
4262            }
4263
4264            final int id = mHostView.getId();
4265            final String idText = id == NO_ID ? "" : " with id '"
4266                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4267            throw new IllegalStateException("Could not find method " + mMethodName
4268                    + "(View) in a parent or ancestor Context for android:onClick "
4269                    + "attribute defined on view " + mHostView.getClass() + idText);
4270        }
4271    }
4272
4273    /**
4274     * Non-public constructor for use in testing
4275     */
4276    View() {
4277        mResources = null;
4278        mRenderNode = RenderNode.create(getClass().getName(), this);
4279    }
4280
4281    private static SparseArray<String> getAttributeMap() {
4282        if (mAttributeMap == null) {
4283            mAttributeMap = new SparseArray<String>();
4284        }
4285        return mAttributeMap;
4286    }
4287
4288    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4289        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4290        mAttributes = new String[length];
4291
4292        int i = 0;
4293        if (attrs != null) {
4294            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4295                mAttributes[i] = attrs.getAttributeName(i);
4296                mAttributes[i + 1] = attrs.getAttributeValue(i);
4297            }
4298
4299        }
4300
4301        SparseArray<String> attributeMap = getAttributeMap();
4302        for (int j = 0; j < a.length(); ++j) {
4303            if (a.hasValue(j)) {
4304                try {
4305                    int resourceId = a.getResourceId(j, 0);
4306                    if (resourceId == 0) {
4307                        continue;
4308                    }
4309
4310                    String resourceName = attributeMap.get(resourceId);
4311                    if (resourceName == null) {
4312                        resourceName = a.getResources().getResourceName(resourceId);
4313                        attributeMap.put(resourceId, resourceName);
4314                    }
4315
4316                    mAttributes[i] = resourceName;
4317                    mAttributes[i + 1] = a.getText(j).toString();
4318                    i += 2;
4319                } catch (Resources.NotFoundException e) {
4320                    // if we can't get the resource name, we just ignore it
4321                }
4322            }
4323        }
4324    }
4325
4326    public String toString() {
4327        StringBuilder out = new StringBuilder(128);
4328        out.append(getClass().getName());
4329        out.append('{');
4330        out.append(Integer.toHexString(System.identityHashCode(this)));
4331        out.append(' ');
4332        switch (mViewFlags&VISIBILITY_MASK) {
4333            case VISIBLE: out.append('V'); break;
4334            case INVISIBLE: out.append('I'); break;
4335            case GONE: out.append('G'); break;
4336            default: out.append('.'); break;
4337        }
4338        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4339        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4340        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4341        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4342        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4343        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4344        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4345        out.append(' ');
4346        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4347        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4348        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4349        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4350            out.append('p');
4351        } else {
4352            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4353        }
4354        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4355        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4356        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4357        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4358        out.append(' ');
4359        out.append(mLeft);
4360        out.append(',');
4361        out.append(mTop);
4362        out.append('-');
4363        out.append(mRight);
4364        out.append(',');
4365        out.append(mBottom);
4366        final int id = getId();
4367        if (id != NO_ID) {
4368            out.append(" #");
4369            out.append(Integer.toHexString(id));
4370            final Resources r = mResources;
4371            if (Resources.resourceHasPackage(id) && r != null) {
4372                try {
4373                    String pkgname;
4374                    switch (id&0xff000000) {
4375                        case 0x7f000000:
4376                            pkgname="app";
4377                            break;
4378                        case 0x01000000:
4379                            pkgname="android";
4380                            break;
4381                        default:
4382                            pkgname = r.getResourcePackageName(id);
4383                            break;
4384                    }
4385                    String typename = r.getResourceTypeName(id);
4386                    String entryname = r.getResourceEntryName(id);
4387                    out.append(" ");
4388                    out.append(pkgname);
4389                    out.append(":");
4390                    out.append(typename);
4391                    out.append("/");
4392                    out.append(entryname);
4393                } catch (Resources.NotFoundException e) {
4394                }
4395            }
4396        }
4397        out.append("}");
4398        return out.toString();
4399    }
4400
4401    /**
4402     * <p>
4403     * Initializes the fading edges from a given set of styled attributes. This
4404     * method should be called by subclasses that need fading edges and when an
4405     * instance of these subclasses is created programmatically rather than
4406     * being inflated from XML. This method is automatically called when the XML
4407     * is inflated.
4408     * </p>
4409     *
4410     * @param a the styled attributes set to initialize the fading edges from
4411     *
4412     * @removed
4413     */
4414    protected void initializeFadingEdge(TypedArray a) {
4415        // This method probably shouldn't have been included in the SDK to begin with.
4416        // It relies on 'a' having been initialized using an attribute filter array that is
4417        // not publicly available to the SDK. The old method has been renamed
4418        // to initializeFadingEdgeInternal and hidden for framework use only;
4419        // this one initializes using defaults to make it safe to call for apps.
4420
4421        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4422
4423        initializeFadingEdgeInternal(arr);
4424
4425        arr.recycle();
4426    }
4427
4428    /**
4429     * <p>
4430     * Initializes the fading edges from a given set of styled attributes. This
4431     * method should be called by subclasses that need fading edges 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 fading edges from
4438     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4439     */
4440    protected void initializeFadingEdgeInternal(TypedArray a) {
4441        initScrollCache();
4442
4443        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4444                R.styleable.View_fadingEdgeLength,
4445                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4446    }
4447
4448    /**
4449     * Returns the size of the vertical faded edges used to indicate that more
4450     * content in this view is visible.
4451     *
4452     * @return The size in pixels of the vertical faded edge or 0 if vertical
4453     *         faded edges are not enabled for this view.
4454     * @attr ref android.R.styleable#View_fadingEdgeLength
4455     */
4456    public int getVerticalFadingEdgeLength() {
4457        if (isVerticalFadingEdgeEnabled()) {
4458            ScrollabilityCache cache = mScrollCache;
4459            if (cache != null) {
4460                return cache.fadingEdgeLength;
4461            }
4462        }
4463        return 0;
4464    }
4465
4466    /**
4467     * Set the size of the faded edge used to indicate that more content in this
4468     * view is available.  Will not change whether the fading edge is enabled; use
4469     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4470     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4471     * for the vertical or horizontal fading edges.
4472     *
4473     * @param length The size in pixels of the faded edge used to indicate that more
4474     *        content in this view is visible.
4475     */
4476    public void setFadingEdgeLength(int length) {
4477        initScrollCache();
4478        mScrollCache.fadingEdgeLength = length;
4479    }
4480
4481    /**
4482     * Returns the size of the horizontal faded edges used to indicate that more
4483     * content in this view is visible.
4484     *
4485     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4486     *         faded edges are not enabled for this view.
4487     * @attr ref android.R.styleable#View_fadingEdgeLength
4488     */
4489    public int getHorizontalFadingEdgeLength() {
4490        if (isHorizontalFadingEdgeEnabled()) {
4491            ScrollabilityCache cache = mScrollCache;
4492            if (cache != null) {
4493                return cache.fadingEdgeLength;
4494            }
4495        }
4496        return 0;
4497    }
4498
4499    /**
4500     * Returns the width of the vertical scrollbar.
4501     *
4502     * @return The width in pixels of the vertical scrollbar or 0 if there
4503     *         is no vertical scrollbar.
4504     */
4505    public int getVerticalScrollbarWidth() {
4506        ScrollabilityCache cache = mScrollCache;
4507        if (cache != null) {
4508            ScrollBarDrawable scrollBar = cache.scrollBar;
4509            if (scrollBar != null) {
4510                int size = scrollBar.getSize(true);
4511                if (size <= 0) {
4512                    size = cache.scrollBarSize;
4513                }
4514                return size;
4515            }
4516            return 0;
4517        }
4518        return 0;
4519    }
4520
4521    /**
4522     * Returns the height of the horizontal scrollbar.
4523     *
4524     * @return The height in pixels of the horizontal scrollbar or 0 if
4525     *         there is no horizontal scrollbar.
4526     */
4527    protected int getHorizontalScrollbarHeight() {
4528        ScrollabilityCache cache = mScrollCache;
4529        if (cache != null) {
4530            ScrollBarDrawable scrollBar = cache.scrollBar;
4531            if (scrollBar != null) {
4532                int size = scrollBar.getSize(false);
4533                if (size <= 0) {
4534                    size = cache.scrollBarSize;
4535                }
4536                return size;
4537            }
4538            return 0;
4539        }
4540        return 0;
4541    }
4542
4543    /**
4544     * <p>
4545     * Initializes the scrollbars from a given set of styled attributes. This
4546     * method should be called by subclasses that need scrollbars and when an
4547     * instance of these subclasses is created programmatically rather than
4548     * being inflated from XML. This method is automatically called when the XML
4549     * is inflated.
4550     * </p>
4551     *
4552     * @param a the styled attributes set to initialize the scrollbars from
4553     *
4554     * @removed
4555     */
4556    protected void initializeScrollbars(TypedArray a) {
4557        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4558        // using the View filter array which is not available to the SDK. As such, internal
4559        // framework usage now uses initializeScrollbarsInternal and we grab a default
4560        // TypedArray with the right filter instead here.
4561        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4562
4563        initializeScrollbarsInternal(arr);
4564
4565        // We ignored the method parameter. Recycle the one we actually did use.
4566        arr.recycle();
4567    }
4568
4569    /**
4570     * <p>
4571     * Initializes the scrollbars from a given set of styled attributes. This
4572     * method should be called by subclasses that need scrollbars and when an
4573     * instance of these subclasses is created programmatically rather than
4574     * being inflated from XML. This method is automatically called when the XML
4575     * is inflated.
4576     * </p>
4577     *
4578     * @param a the styled attributes set to initialize the scrollbars from
4579     * @hide
4580     */
4581    protected void initializeScrollbarsInternal(TypedArray a) {
4582        initScrollCache();
4583
4584        final ScrollabilityCache scrollabilityCache = mScrollCache;
4585
4586        if (scrollabilityCache.scrollBar == null) {
4587            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4588            scrollabilityCache.scrollBar.setCallback(this);
4589            scrollabilityCache.scrollBar.setState(getDrawableState());
4590        }
4591
4592        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4593
4594        if (!fadeScrollbars) {
4595            scrollabilityCache.state = ScrollabilityCache.ON;
4596        }
4597        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4598
4599
4600        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4601                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4602                        .getScrollBarFadeDuration());
4603        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4604                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4605                ViewConfiguration.getScrollDefaultDelay());
4606
4607
4608        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4609                com.android.internal.R.styleable.View_scrollbarSize,
4610                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4611
4612        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4613        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4614
4615        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4616        if (thumb != null) {
4617            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4618        }
4619
4620        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4621                false);
4622        if (alwaysDraw) {
4623            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4624        }
4625
4626        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4627        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4628
4629        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4630        if (thumb != null) {
4631            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4632        }
4633
4634        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4635                false);
4636        if (alwaysDraw) {
4637            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4638        }
4639
4640        // Apply layout direction to the new Drawables if needed
4641        final int layoutDirection = getLayoutDirection();
4642        if (track != null) {
4643            track.setLayoutDirection(layoutDirection);
4644        }
4645        if (thumb != null) {
4646            thumb.setLayoutDirection(layoutDirection);
4647        }
4648
4649        // Re-apply user/background padding so that scrollbar(s) get added
4650        resolvePadding();
4651    }
4652
4653    /**
4654     * <p>
4655     * Initalizes the scrollability cache if necessary.
4656     * </p>
4657     */
4658    private void initScrollCache() {
4659        if (mScrollCache == null) {
4660            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4661        }
4662    }
4663
4664    private ScrollabilityCache getScrollCache() {
4665        initScrollCache();
4666        return mScrollCache;
4667    }
4668
4669    /**
4670     * Set the position of the vertical scroll bar. Should be one of
4671     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4672     * {@link #SCROLLBAR_POSITION_RIGHT}.
4673     *
4674     * @param position Where the vertical scroll bar should be positioned.
4675     */
4676    public void setVerticalScrollbarPosition(int position) {
4677        if (mVerticalScrollbarPosition != position) {
4678            mVerticalScrollbarPosition = position;
4679            computeOpaqueFlags();
4680            resolvePadding();
4681        }
4682    }
4683
4684    /**
4685     * @return The position where the vertical scroll bar will show, if applicable.
4686     * @see #setVerticalScrollbarPosition(int)
4687     */
4688    public int getVerticalScrollbarPosition() {
4689        return mVerticalScrollbarPosition;
4690    }
4691
4692    ListenerInfo getListenerInfo() {
4693        if (mListenerInfo != null) {
4694            return mListenerInfo;
4695        }
4696        mListenerInfo = new ListenerInfo();
4697        return mListenerInfo;
4698    }
4699
4700    /**
4701     * Register a callback to be invoked when the scroll X or Y positions of
4702     * this view change.
4703     * <p>
4704     * <b>Note:</b> Some views handle scrolling independently from View and may
4705     * have their own separate listeners for scroll-type events. For example,
4706     * {@link android.widget.ListView ListView} allows clients to register an
4707     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
4708     * to listen for changes in list scroll position.
4709     *
4710     * @param l The listener to notify when the scroll X or Y position changes.
4711     * @see android.view.View#getScrollX()
4712     * @see android.view.View#getScrollY()
4713     */
4714    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4715        getListenerInfo().mOnScrollChangeListener = l;
4716    }
4717
4718    /**
4719     * Register a callback to be invoked when focus of this view changed.
4720     *
4721     * @param l The callback that will run.
4722     */
4723    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4724        getListenerInfo().mOnFocusChangeListener = l;
4725    }
4726
4727    /**
4728     * Add a listener that will be called when the bounds of the view change due to
4729     * layout processing.
4730     *
4731     * @param listener The listener that will be called when layout bounds change.
4732     */
4733    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4734        ListenerInfo li = getListenerInfo();
4735        if (li.mOnLayoutChangeListeners == null) {
4736            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4737        }
4738        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4739            li.mOnLayoutChangeListeners.add(listener);
4740        }
4741    }
4742
4743    /**
4744     * Remove a listener for layout changes.
4745     *
4746     * @param listener The listener for layout bounds change.
4747     */
4748    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4749        ListenerInfo li = mListenerInfo;
4750        if (li == null || li.mOnLayoutChangeListeners == null) {
4751            return;
4752        }
4753        li.mOnLayoutChangeListeners.remove(listener);
4754    }
4755
4756    /**
4757     * Add a listener for attach state changes.
4758     *
4759     * This listener will be called whenever this view is attached or detached
4760     * from a window. Remove the listener using
4761     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4762     *
4763     * @param listener Listener to attach
4764     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4765     */
4766    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4767        ListenerInfo li = getListenerInfo();
4768        if (li.mOnAttachStateChangeListeners == null) {
4769            li.mOnAttachStateChangeListeners
4770                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4771        }
4772        li.mOnAttachStateChangeListeners.add(listener);
4773    }
4774
4775    /**
4776     * Remove a listener for attach state changes. The listener will receive no further
4777     * notification of window attach/detach events.
4778     *
4779     * @param listener Listener to remove
4780     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4781     */
4782    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4783        ListenerInfo li = mListenerInfo;
4784        if (li == null || li.mOnAttachStateChangeListeners == null) {
4785            return;
4786        }
4787        li.mOnAttachStateChangeListeners.remove(listener);
4788    }
4789
4790    /**
4791     * Returns the focus-change callback registered for this view.
4792     *
4793     * @return The callback, or null if one is not registered.
4794     */
4795    public OnFocusChangeListener getOnFocusChangeListener() {
4796        ListenerInfo li = mListenerInfo;
4797        return li != null ? li.mOnFocusChangeListener : null;
4798    }
4799
4800    /**
4801     * Register a callback to be invoked when this view is clicked. If this view is not
4802     * clickable, it becomes clickable.
4803     *
4804     * @param l The callback that will run
4805     *
4806     * @see #setClickable(boolean)
4807     */
4808    public void setOnClickListener(@Nullable OnClickListener l) {
4809        if (!isClickable()) {
4810            setClickable(true);
4811        }
4812        getListenerInfo().mOnClickListener = l;
4813    }
4814
4815    /**
4816     * Return whether this view has an attached OnClickListener.  Returns
4817     * true if there is a listener, false if there is none.
4818     */
4819    public boolean hasOnClickListeners() {
4820        ListenerInfo li = mListenerInfo;
4821        return (li != null && li.mOnClickListener != null);
4822    }
4823
4824    /**
4825     * Register a callback to be invoked when this view is clicked and held. If this view is not
4826     * long clickable, it becomes long clickable.
4827     *
4828     * @param l The callback that will run
4829     *
4830     * @see #setLongClickable(boolean)
4831     */
4832    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
4833        if (!isLongClickable()) {
4834            setLongClickable(true);
4835        }
4836        getListenerInfo().mOnLongClickListener = l;
4837    }
4838
4839    /**
4840     * Register a callback to be invoked when the context menu for this view is
4841     * being built. If this view is not long clickable, it becomes long clickable.
4842     *
4843     * @param l The callback that will run
4844     *
4845     */
4846    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4847        if (!isLongClickable()) {
4848            setLongClickable(true);
4849        }
4850        getListenerInfo().mOnCreateContextMenuListener = l;
4851    }
4852
4853    /**
4854     * Call this view's OnClickListener, if it is defined.  Performs all normal
4855     * actions associated with clicking: reporting accessibility event, playing
4856     * a sound, etc.
4857     *
4858     * @return True there was an assigned OnClickListener that was called, false
4859     *         otherwise is returned.
4860     */
4861    public boolean performClick() {
4862        final boolean result;
4863        final ListenerInfo li = mListenerInfo;
4864        if (li != null && li.mOnClickListener != null) {
4865            playSoundEffect(SoundEffectConstants.CLICK);
4866            li.mOnClickListener.onClick(this);
4867            result = true;
4868        } else {
4869            result = false;
4870        }
4871
4872        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4873        return result;
4874    }
4875
4876    /**
4877     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4878     * this only calls the listener, and does not do any associated clicking
4879     * actions like reporting an accessibility event.
4880     *
4881     * @return True there was an assigned OnClickListener that was called, false
4882     *         otherwise is returned.
4883     */
4884    public boolean callOnClick() {
4885        ListenerInfo li = mListenerInfo;
4886        if (li != null && li.mOnClickListener != null) {
4887            li.mOnClickListener.onClick(this);
4888            return true;
4889        }
4890        return false;
4891    }
4892
4893    /**
4894     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4895     * OnLongClickListener did not consume the event.
4896     *
4897     * @return True if one of the above receivers consumed the event, false otherwise.
4898     */
4899    public boolean performLongClick() {
4900        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4901
4902        boolean handled = false;
4903        ListenerInfo li = mListenerInfo;
4904        if (li != null && li.mOnLongClickListener != null) {
4905            handled = li.mOnLongClickListener.onLongClick(View.this);
4906        }
4907        if (!handled) {
4908            handled = showContextMenu();
4909        }
4910        if (handled) {
4911            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4912        }
4913        return handled;
4914    }
4915
4916    /**
4917     * Performs button-related actions during a touch down event.
4918     *
4919     * @param event The event.
4920     * @return True if the down was consumed.
4921     *
4922     * @hide
4923     */
4924    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4925        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
4926            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4927            showContextMenu(event.getX(), event.getY(), event.getMetaState());
4928            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
4929            return true;
4930        }
4931        return false;
4932    }
4933
4934    /**
4935     * Bring up the context menu for this view.
4936     *
4937     * @return Whether a context menu was displayed.
4938     */
4939    public boolean showContextMenu() {
4940        return getParent().showContextMenuForChild(this);
4941    }
4942
4943    /**
4944     * Bring up the context menu for this view, referring to the item under the specified point.
4945     *
4946     * @param x The referenced x coordinate.
4947     * @param y The referenced y coordinate.
4948     * @param metaState The keyboard modifiers that were pressed.
4949     * @return Whether a context menu was displayed.
4950     *
4951     * @hide
4952     */
4953    public boolean showContextMenu(float x, float y, int metaState) {
4954        return showContextMenu();
4955    }
4956
4957    /**
4958     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
4959     *
4960     * @param callback Callback that will control the lifecycle of the action mode
4961     * @return The new action mode if it is started, null otherwise
4962     *
4963     * @see ActionMode
4964     * @see #startActionMode(android.view.ActionMode.Callback, int)
4965     */
4966    public ActionMode startActionMode(ActionMode.Callback callback) {
4967        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
4968    }
4969
4970    /**
4971     * Start an action mode with the given type.
4972     *
4973     * @param callback Callback that will control the lifecycle of the action mode
4974     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
4975     * @return The new action mode if it is started, null otherwise
4976     *
4977     * @see ActionMode
4978     */
4979    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
4980        ViewParent parent = getParent();
4981        if (parent == null) return null;
4982        try {
4983            return parent.startActionModeForChild(this, callback, type);
4984        } catch (AbstractMethodError ame) {
4985            // Older implementations of custom views might not implement this.
4986            return parent.startActionModeForChild(this, callback);
4987        }
4988    }
4989
4990    /**
4991     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
4992     * Context, creating a unique View identifier to retrieve the result.
4993     *
4994     * @param intent The Intent to be started.
4995     * @param requestCode The request code to use.
4996     * @hide
4997     */
4998    public void startActivityForResult(Intent intent, int requestCode) {
4999        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5000        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5001    }
5002
5003    /**
5004     * If this View corresponds to the calling who, dispatches the activity result.
5005     * @param who The identifier for the targeted View to receive the result.
5006     * @param requestCode The integer request code originally supplied to
5007     *                    startActivityForResult(), allowing you to identify who this
5008     *                    result came from.
5009     * @param resultCode The integer result code returned by the child activity
5010     *                   through its setResult().
5011     * @param data An Intent, which can return result data to the caller
5012     *               (various data can be attached to Intent "extras").
5013     * @return {@code true} if the activity result was dispatched.
5014     * @hide
5015     */
5016    public boolean dispatchActivityResult(
5017            String who, int requestCode, int resultCode, Intent data) {
5018        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5019            onActivityResult(requestCode, resultCode, data);
5020            mStartActivityRequestWho = null;
5021            return true;
5022        }
5023        return false;
5024    }
5025
5026    /**
5027     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5028     *
5029     * @param requestCode The integer request code originally supplied to
5030     *                    startActivityForResult(), allowing you to identify who this
5031     *                    result came from.
5032     * @param resultCode The integer result code returned by the child activity
5033     *                   through its setResult().
5034     * @param data An Intent, which can return result data to the caller
5035     *               (various data can be attached to Intent "extras").
5036     * @hide
5037     */
5038    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5039        // Do nothing.
5040    }
5041
5042    /**
5043     * Register a callback to be invoked when a hardware key is pressed in this view.
5044     * Key presses in software input methods will generally not trigger the methods of
5045     * this listener.
5046     * @param l the key listener to attach to this view
5047     */
5048    public void setOnKeyListener(OnKeyListener l) {
5049        getListenerInfo().mOnKeyListener = l;
5050    }
5051
5052    /**
5053     * Register a callback to be invoked when a touch event is sent to this view.
5054     * @param l the touch listener to attach to this view
5055     */
5056    public void setOnTouchListener(OnTouchListener l) {
5057        getListenerInfo().mOnTouchListener = l;
5058    }
5059
5060    /**
5061     * Register a callback to be invoked when a generic motion event is sent to this view.
5062     * @param l the generic motion listener to attach to this view
5063     */
5064    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5065        getListenerInfo().mOnGenericMotionListener = l;
5066    }
5067
5068    /**
5069     * Register a callback to be invoked when a hover event is sent to this view.
5070     * @param l the hover listener to attach to this view
5071     */
5072    public void setOnHoverListener(OnHoverListener l) {
5073        getListenerInfo().mOnHoverListener = l;
5074    }
5075
5076    /**
5077     * Register a drag event listener callback object for this View. The parameter is
5078     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5079     * View, the system calls the
5080     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5081     * @param l An implementation of {@link android.view.View.OnDragListener}.
5082     */
5083    public void setOnDragListener(OnDragListener l) {
5084        getListenerInfo().mOnDragListener = l;
5085    }
5086
5087    /**
5088     * Give this view focus. This will cause
5089     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5090     *
5091     * Note: this does not check whether this {@link View} should get focus, it just
5092     * gives it focus no matter what.  It should only be called internally by framework
5093     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5094     *
5095     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5096     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5097     *        focus moved when requestFocus() is called. It may not always
5098     *        apply, in which case use the default View.FOCUS_DOWN.
5099     * @param previouslyFocusedRect The rectangle of the view that had focus
5100     *        prior in this View's coordinate system.
5101     */
5102    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5103        if (DBG) {
5104            System.out.println(this + " requestFocus()");
5105        }
5106
5107        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5108            mPrivateFlags |= PFLAG_FOCUSED;
5109
5110            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5111
5112            if (mParent != null) {
5113                mParent.requestChildFocus(this, this);
5114            }
5115
5116            if (mAttachInfo != null) {
5117                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5118            }
5119
5120            onFocusChanged(true, direction, previouslyFocusedRect);
5121            refreshDrawableState();
5122        }
5123    }
5124
5125    /**
5126     * Populates <code>outRect</code> with the hotspot bounds. By default,
5127     * the hotspot bounds are identical to the screen bounds.
5128     *
5129     * @param outRect rect to populate with hotspot bounds
5130     * @hide Only for internal use by views and widgets.
5131     */
5132    public void getHotspotBounds(Rect outRect) {
5133        final Drawable background = getBackground();
5134        if (background != null) {
5135            background.getHotspotBounds(outRect);
5136        } else {
5137            getBoundsOnScreen(outRect);
5138        }
5139    }
5140
5141    /**
5142     * Request that a rectangle of this view be visible on the screen,
5143     * scrolling if necessary just enough.
5144     *
5145     * <p>A View should call this if it maintains some notion of which part
5146     * of its content is interesting.  For example, a text editing view
5147     * should call this when its cursor moves.
5148     *
5149     * @param rectangle The rectangle.
5150     * @return Whether any parent scrolled.
5151     */
5152    public boolean requestRectangleOnScreen(Rect rectangle) {
5153        return requestRectangleOnScreen(rectangle, false);
5154    }
5155
5156    /**
5157     * Request that a rectangle of this view be visible on the screen,
5158     * scrolling if necessary just enough.
5159     *
5160     * <p>A View should call this if it maintains some notion of which part
5161     * of its content is interesting.  For example, a text editing view
5162     * should call this when its cursor moves.
5163     *
5164     * <p>When <code>immediate</code> is set to true, scrolling will not be
5165     * animated.
5166     *
5167     * @param rectangle The rectangle.
5168     * @param immediate True to forbid animated scrolling, false otherwise
5169     * @return Whether any parent scrolled.
5170     */
5171    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5172        if (mParent == null) {
5173            return false;
5174        }
5175
5176        View child = this;
5177
5178        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5179        position.set(rectangle);
5180
5181        ViewParent parent = mParent;
5182        boolean scrolled = false;
5183        while (parent != null) {
5184            rectangle.set((int) position.left, (int) position.top,
5185                    (int) position.right, (int) position.bottom);
5186
5187            scrolled |= parent.requestChildRectangleOnScreen(child,
5188                    rectangle, immediate);
5189
5190            if (!child.hasIdentityMatrix()) {
5191                child.getMatrix().mapRect(position);
5192            }
5193
5194            position.offset(child.mLeft, child.mTop);
5195
5196            if (!(parent instanceof View)) {
5197                break;
5198            }
5199
5200            View parentView = (View) parent;
5201
5202            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5203
5204            child = parentView;
5205            parent = child.getParent();
5206        }
5207
5208        return scrolled;
5209    }
5210
5211    /**
5212     * Called when this view wants to give up focus. If focus is cleared
5213     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5214     * <p>
5215     * <strong>Note:</strong> When a View clears focus the framework is trying
5216     * to give focus to the first focusable View from the top. Hence, if this
5217     * View is the first from the top that can take focus, then all callbacks
5218     * related to clearing focus will be invoked after which the framework will
5219     * give focus to this view.
5220     * </p>
5221     */
5222    public void clearFocus() {
5223        if (DBG) {
5224            System.out.println(this + " clearFocus()");
5225        }
5226
5227        clearFocusInternal(null, true, true);
5228    }
5229
5230    /**
5231     * Clears focus from the view, optionally propagating the change up through
5232     * the parent hierarchy and requesting that the root view place new focus.
5233     *
5234     * @param propagate whether to propagate the change up through the parent
5235     *            hierarchy
5236     * @param refocus when propagate is true, specifies whether to request the
5237     *            root view place new focus
5238     */
5239    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5240        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5241            mPrivateFlags &= ~PFLAG_FOCUSED;
5242
5243            if (propagate && mParent != null) {
5244                mParent.clearChildFocus(this);
5245            }
5246
5247            onFocusChanged(false, 0, null);
5248            refreshDrawableState();
5249
5250            if (propagate && (!refocus || !rootViewRequestFocus())) {
5251                notifyGlobalFocusCleared(this);
5252            }
5253        }
5254    }
5255
5256    void notifyGlobalFocusCleared(View oldFocus) {
5257        if (oldFocus != null && mAttachInfo != null) {
5258            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5259        }
5260    }
5261
5262    boolean rootViewRequestFocus() {
5263        final View root = getRootView();
5264        return root != null && root.requestFocus();
5265    }
5266
5267    /**
5268     * Called internally by the view system when a new view is getting focus.
5269     * This is what clears the old focus.
5270     * <p>
5271     * <b>NOTE:</b> The parent view's focused child must be updated manually
5272     * after calling this method. Otherwise, the view hierarchy may be left in
5273     * an inconstent state.
5274     */
5275    void unFocus(View focused) {
5276        if (DBG) {
5277            System.out.println(this + " unFocus()");
5278        }
5279
5280        clearFocusInternal(focused, false, false);
5281    }
5282
5283    /**
5284     * Returns true if this view has focus itself, or is the ancestor of the
5285     * view that has focus.
5286     *
5287     * @return True if this view has or contains focus, false otherwise.
5288     */
5289    @ViewDebug.ExportedProperty(category = "focus")
5290    public boolean hasFocus() {
5291        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5292    }
5293
5294    /**
5295     * Returns true if this view is focusable or if it contains a reachable View
5296     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5297     * is a View whose parents do not block descendants focus.
5298     *
5299     * Only {@link #VISIBLE} views are considered focusable.
5300     *
5301     * @return True if the view is focusable or if the view contains a focusable
5302     *         View, false otherwise.
5303     *
5304     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5305     * @see ViewGroup#getTouchscreenBlocksFocus()
5306     */
5307    public boolean hasFocusable() {
5308        if (!isFocusableInTouchMode()) {
5309            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5310                final ViewGroup g = (ViewGroup) p;
5311                if (g.shouldBlockFocusForTouchscreen()) {
5312                    return false;
5313                }
5314            }
5315        }
5316        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5317    }
5318
5319    /**
5320     * Called by the view system when the focus state of this view changes.
5321     * When the focus change event is caused by directional navigation, direction
5322     * and previouslyFocusedRect provide insight into where the focus is coming from.
5323     * When overriding, be sure to call up through to the super class so that
5324     * the standard focus handling will occur.
5325     *
5326     * @param gainFocus True if the View has focus; false otherwise.
5327     * @param direction The direction focus has moved when requestFocus()
5328     *                  is called to give this view focus. Values are
5329     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5330     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5331     *                  It may not always apply, in which case use the default.
5332     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5333     *        system, of the previously focused view.  If applicable, this will be
5334     *        passed in as finer grained information about where the focus is coming
5335     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5336     */
5337    @CallSuper
5338    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5339            @Nullable Rect previouslyFocusedRect) {
5340        if (gainFocus) {
5341            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5342        } else {
5343            notifyViewAccessibilityStateChangedIfNeeded(
5344                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5345        }
5346
5347        InputMethodManager imm = InputMethodManager.peekInstance();
5348        if (!gainFocus) {
5349            if (isPressed()) {
5350                setPressed(false);
5351            }
5352            if (imm != null && mAttachInfo != null
5353                    && mAttachInfo.mHasWindowFocus) {
5354                imm.focusOut(this);
5355            }
5356            onFocusLost();
5357        } else if (imm != null && mAttachInfo != null
5358                && mAttachInfo.mHasWindowFocus) {
5359            imm.focusIn(this);
5360        }
5361
5362        invalidate(true);
5363        ListenerInfo li = mListenerInfo;
5364        if (li != null && li.mOnFocusChangeListener != null) {
5365            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5366        }
5367
5368        if (mAttachInfo != null) {
5369            mAttachInfo.mKeyDispatchState.reset(this);
5370        }
5371    }
5372
5373    /**
5374     * Sends an accessibility event of the given type. If accessibility is
5375     * not enabled this method has no effect. The default implementation calls
5376     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5377     * to populate information about the event source (this View), then calls
5378     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5379     * populate the text content of the event source including its descendants,
5380     * and last calls
5381     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5382     * on its parent to request sending of the event to interested parties.
5383     * <p>
5384     * If an {@link AccessibilityDelegate} has been specified via calling
5385     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5386     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5387     * responsible for handling this call.
5388     * </p>
5389     *
5390     * @param eventType The type of the event to send, as defined by several types from
5391     * {@link android.view.accessibility.AccessibilityEvent}, such as
5392     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5393     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5394     *
5395     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5396     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5397     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5398     * @see AccessibilityDelegate
5399     */
5400    public void sendAccessibilityEvent(int eventType) {
5401        if (mAccessibilityDelegate != null) {
5402            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5403        } else {
5404            sendAccessibilityEventInternal(eventType);
5405        }
5406    }
5407
5408    /**
5409     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5410     * {@link AccessibilityEvent} to make an announcement which is related to some
5411     * sort of a context change for which none of the events representing UI transitions
5412     * is a good fit. For example, announcing a new page in a book. If accessibility
5413     * is not enabled this method does nothing.
5414     *
5415     * @param text The announcement text.
5416     */
5417    public void announceForAccessibility(CharSequence text) {
5418        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5419            AccessibilityEvent event = AccessibilityEvent.obtain(
5420                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5421            onInitializeAccessibilityEvent(event);
5422            event.getText().add(text);
5423            event.setContentDescription(null);
5424            mParent.requestSendAccessibilityEvent(this, event);
5425        }
5426    }
5427
5428    /**
5429     * @see #sendAccessibilityEvent(int)
5430     *
5431     * Note: Called from the default {@link AccessibilityDelegate}.
5432     *
5433     * @hide
5434     */
5435    public void sendAccessibilityEventInternal(int eventType) {
5436        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5437            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5438        }
5439    }
5440
5441    /**
5442     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5443     * takes as an argument an empty {@link AccessibilityEvent} and does not
5444     * perform a check whether accessibility is enabled.
5445     * <p>
5446     * If an {@link AccessibilityDelegate} has been specified via calling
5447     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5448     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5449     * is responsible for handling this call.
5450     * </p>
5451     *
5452     * @param event The event to send.
5453     *
5454     * @see #sendAccessibilityEvent(int)
5455     */
5456    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5457        if (mAccessibilityDelegate != null) {
5458            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5459        } else {
5460            sendAccessibilityEventUncheckedInternal(event);
5461        }
5462    }
5463
5464    /**
5465     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5466     *
5467     * Note: Called from the default {@link AccessibilityDelegate}.
5468     *
5469     * @hide
5470     */
5471    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5472        if (!isShown()) {
5473            return;
5474        }
5475        onInitializeAccessibilityEvent(event);
5476        // Only a subset of accessibility events populates text content.
5477        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5478            dispatchPopulateAccessibilityEvent(event);
5479        }
5480        // In the beginning we called #isShown(), so we know that getParent() is not null.
5481        getParent().requestSendAccessibilityEvent(this, event);
5482    }
5483
5484    /**
5485     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5486     * to its children for adding their text content to the event. Note that the
5487     * event text is populated in a separate dispatch path since we add to the
5488     * event not only the text of the source but also the text of all its descendants.
5489     * A typical implementation will call
5490     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5491     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5492     * on each child. Override this method if custom population of the event text
5493     * content is required.
5494     * <p>
5495     * If an {@link AccessibilityDelegate} has been specified via calling
5496     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5497     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5498     * is responsible for handling this call.
5499     * </p>
5500     * <p>
5501     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5502     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5503     * </p>
5504     *
5505     * @param event The event.
5506     *
5507     * @return True if the event population was completed.
5508     */
5509    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5510        if (mAccessibilityDelegate != null) {
5511            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5512        } else {
5513            return dispatchPopulateAccessibilityEventInternal(event);
5514        }
5515    }
5516
5517    /**
5518     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5519     *
5520     * Note: Called from the default {@link AccessibilityDelegate}.
5521     *
5522     * @hide
5523     */
5524    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5525        onPopulateAccessibilityEvent(event);
5526        return false;
5527    }
5528
5529    /**
5530     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5531     * giving a chance to this View to populate the accessibility event with its
5532     * text content. While this method is free to modify event
5533     * attributes other than text content, doing so should normally be performed in
5534     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5535     * <p>
5536     * Example: Adding formatted date string to an accessibility event in addition
5537     *          to the text added by the super implementation:
5538     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5539     *     super.onPopulateAccessibilityEvent(event);
5540     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5541     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5542     *         mCurrentDate.getTimeInMillis(), flags);
5543     *     event.getText().add(selectedDateUtterance);
5544     * }</pre>
5545     * <p>
5546     * If an {@link AccessibilityDelegate} has been specified via calling
5547     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5548     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5549     * is responsible for handling this call.
5550     * </p>
5551     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5552     * information to the event, in case the default implementation has basic information to add.
5553     * </p>
5554     *
5555     * @param event The accessibility event which to populate.
5556     *
5557     * @see #sendAccessibilityEvent(int)
5558     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5559     */
5560    @CallSuper
5561    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5562        if (mAccessibilityDelegate != null) {
5563            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5564        } else {
5565            onPopulateAccessibilityEventInternal(event);
5566        }
5567    }
5568
5569    /**
5570     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5571     *
5572     * Note: Called from the default {@link AccessibilityDelegate}.
5573     *
5574     * @hide
5575     */
5576    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5577    }
5578
5579    /**
5580     * Initializes an {@link AccessibilityEvent} with information about
5581     * this View which is the event source. In other words, the source of
5582     * an accessibility event is the view whose state change triggered firing
5583     * the event.
5584     * <p>
5585     * Example: Setting the password property of an event in addition
5586     *          to properties set by the super implementation:
5587     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5588     *     super.onInitializeAccessibilityEvent(event);
5589     *     event.setPassword(true);
5590     * }</pre>
5591     * <p>
5592     * If an {@link AccessibilityDelegate} has been specified via calling
5593     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5594     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5595     * is responsible for handling this call.
5596     * </p>
5597     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5598     * information to the event, in case the default implementation has basic information to add.
5599     * </p>
5600     * @param event The event to initialize.
5601     *
5602     * @see #sendAccessibilityEvent(int)
5603     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5604     */
5605    @CallSuper
5606    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5607        if (mAccessibilityDelegate != null) {
5608            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5609        } else {
5610            onInitializeAccessibilityEventInternal(event);
5611        }
5612    }
5613
5614    /**
5615     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5616     *
5617     * Note: Called from the default {@link AccessibilityDelegate}.
5618     *
5619     * @hide
5620     */
5621    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5622        event.setSource(this);
5623        event.setClassName(getAccessibilityClassName());
5624        event.setPackageName(getContext().getPackageName());
5625        event.setEnabled(isEnabled());
5626        event.setContentDescription(mContentDescription);
5627
5628        switch (event.getEventType()) {
5629            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5630                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5631                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5632                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5633                event.setItemCount(focusablesTempList.size());
5634                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5635                if (mAttachInfo != null) {
5636                    focusablesTempList.clear();
5637                }
5638            } break;
5639            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5640                CharSequence text = getIterableTextForAccessibility();
5641                if (text != null && text.length() > 0) {
5642                    event.setFromIndex(getAccessibilitySelectionStart());
5643                    event.setToIndex(getAccessibilitySelectionEnd());
5644                    event.setItemCount(text.length());
5645                }
5646            } break;
5647        }
5648    }
5649
5650    /**
5651     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5652     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5653     * This method is responsible for obtaining an accessibility node info from a
5654     * pool of reusable instances and calling
5655     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5656     * initialize the former.
5657     * <p>
5658     * Note: The client is responsible for recycling the obtained instance by calling
5659     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5660     * </p>
5661     *
5662     * @return A populated {@link AccessibilityNodeInfo}.
5663     *
5664     * @see AccessibilityNodeInfo
5665     */
5666    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5667        if (mAccessibilityDelegate != null) {
5668            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5669        } else {
5670            return createAccessibilityNodeInfoInternal();
5671        }
5672    }
5673
5674    /**
5675     * @see #createAccessibilityNodeInfo()
5676     *
5677     * @hide
5678     */
5679    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5680        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5681        if (provider != null) {
5682            return provider.createAccessibilityNodeInfo(View.NO_ID);
5683        } else {
5684            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5685            onInitializeAccessibilityNodeInfo(info);
5686            return info;
5687        }
5688    }
5689
5690    /**
5691     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5692     * The base implementation sets:
5693     * <ul>
5694     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5695     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5696     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5697     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5698     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5699     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5700     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5701     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5702     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5703     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5704     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5705     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5706     * </ul>
5707     * <p>
5708     * Subclasses should override this method, call the super implementation,
5709     * and set additional attributes.
5710     * </p>
5711     * <p>
5712     * If an {@link AccessibilityDelegate} has been specified via calling
5713     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5714     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5715     * is responsible for handling this call.
5716     * </p>
5717     *
5718     * @param info The instance to initialize.
5719     */
5720    @CallSuper
5721    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5722        if (mAccessibilityDelegate != null) {
5723            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5724        } else {
5725            onInitializeAccessibilityNodeInfoInternal(info);
5726        }
5727    }
5728
5729    /**
5730     * Gets the location of this view in screen coordinates.
5731     *
5732     * @param outRect The output location
5733     * @hide
5734     */
5735    public void getBoundsOnScreen(Rect outRect) {
5736        getBoundsOnScreen(outRect, false);
5737    }
5738
5739    /**
5740     * Gets the location of this view in screen coordinates.
5741     *
5742     * @param outRect The output location
5743     * @param clipToParent Whether to clip child bounds to the parent ones.
5744     * @hide
5745     */
5746    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
5747        if (mAttachInfo == null) {
5748            return;
5749        }
5750
5751        RectF position = mAttachInfo.mTmpTransformRect;
5752        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5753
5754        if (!hasIdentityMatrix()) {
5755            getMatrix().mapRect(position);
5756        }
5757
5758        position.offset(mLeft, mTop);
5759
5760        ViewParent parent = mParent;
5761        while (parent instanceof View) {
5762            View parentView = (View) parent;
5763
5764            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5765
5766            if (clipToParent) {
5767                position.left = Math.max(position.left, 0);
5768                position.top = Math.max(position.top, 0);
5769                position.right = Math.min(position.right, parentView.getWidth());
5770                position.bottom = Math.min(position.bottom, parentView.getHeight());
5771            }
5772
5773            if (!parentView.hasIdentityMatrix()) {
5774                parentView.getMatrix().mapRect(position);
5775            }
5776
5777            position.offset(parentView.mLeft, parentView.mTop);
5778
5779            parent = parentView.mParent;
5780        }
5781
5782        if (parent instanceof ViewRootImpl) {
5783            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5784            position.offset(0, -viewRootImpl.mCurScrollY);
5785        }
5786
5787        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5788
5789        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5790                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5791    }
5792
5793    /**
5794     * Return the class name of this object to be used for accessibility purposes.
5795     * Subclasses should only override this if they are implementing something that
5796     * should be seen as a completely new class of view when used by accessibility,
5797     * unrelated to the class it is deriving from.  This is used to fill in
5798     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
5799     */
5800    public CharSequence getAccessibilityClassName() {
5801        return View.class.getName();
5802    }
5803
5804    /**
5805     * Called when assist structure is being retrieved from a view as part of
5806     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
5807     * @param structure Fill in with structured view data.  The default implementation
5808     * fills in all data that can be inferred from the view itself.
5809     */
5810    public void onProvideAssistStructure(ViewAssistStructure structure) {
5811        final int id = mID;
5812        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
5813                && (id&0x0000ffff) != 0) {
5814            String pkg, type, entry;
5815            try {
5816                final Resources res = getResources();
5817                entry = res.getResourceEntryName(id);
5818                type = res.getResourceTypeName(id);
5819                pkg = res.getResourcePackageName(id);
5820            } catch (Resources.NotFoundException e) {
5821                entry = type = pkg = null;
5822            }
5823            structure.setId(id, pkg, type, entry);
5824        } else {
5825            structure.setId(id, null, null, null);
5826        }
5827        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
5828        structure.setVisibility(getVisibility());
5829        structure.setEnabled(isEnabled());
5830        if (isClickable()) {
5831            structure.setClickable(true);
5832        }
5833        if (isFocusable()) {
5834            structure.setFocusable(true);
5835        }
5836        if (isFocused()) {
5837            structure.setFocused(true);
5838        }
5839        if (isAccessibilityFocused()) {
5840            structure.setAccessibilityFocused(true);
5841        }
5842        if (isSelected()) {
5843            structure.setSelected(true);
5844        }
5845        if (isActivated()) {
5846            structure.setActivated(true);
5847        }
5848        if (isLongClickable()) {
5849            structure.setLongClickable(true);
5850        }
5851        if (this instanceof Checkable) {
5852            structure.setCheckable(true);
5853            if (((Checkable)this).isChecked()) {
5854                structure.setChecked(true);
5855            }
5856        }
5857        structure.setClassName(getAccessibilityClassName().toString());
5858        structure.setContentDescription(getContentDescription());
5859    }
5860
5861    /**
5862     * Called when assist structure is being retrieved from a view as part of
5863     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
5864     * generate additional virtual structure under this view.  The defaullt implementation
5865     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
5866     * view's virtual accessibility nodes, if any.  You can override this for a more
5867     * optimal implementation providing this data.
5868     */
5869    public void onProvideVirtualAssistStructure(ViewAssistStructure structure) {
5870        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5871        if (provider != null) {
5872            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
5873            Log.i("View", "Provider of " + this + ": children=" + info.getChildCount());
5874            structure.setChildCount(1);
5875            ViewAssistStructure root = structure.newChild(0);
5876            populateVirtualAssistStructure(root, provider, info);
5877            info.recycle();
5878        }
5879    }
5880
5881    private void populateVirtualAssistStructure(ViewAssistStructure structure,
5882            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
5883        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
5884                null, null, null);
5885        Rect rect = structure.getTempRect();
5886        info.getBoundsInParent(rect);
5887        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
5888        structure.setVisibility(VISIBLE);
5889        structure.setEnabled(info.isEnabled());
5890        if (info.isClickable()) {
5891            structure.setClickable(true);
5892        }
5893        if (info.isFocusable()) {
5894            structure.setFocusable(true);
5895        }
5896        if (info.isFocused()) {
5897            structure.setFocused(true);
5898        }
5899        if (info.isAccessibilityFocused()) {
5900            structure.setAccessibilityFocused(true);
5901        }
5902        if (info.isSelected()) {
5903            structure.setSelected(true);
5904        }
5905        if (info.isLongClickable()) {
5906            structure.setLongClickable(true);
5907        }
5908        if (info.isCheckable()) {
5909            structure.setCheckable(true);
5910            if (info.isChecked()) {
5911                structure.setChecked(true);
5912            }
5913        }
5914        CharSequence cname = info.getClassName();
5915        structure.setClassName(cname != null ? cname.toString() : null);
5916        structure.setContentDescription(info.getContentDescription());
5917        Log.i("View", "vassist " + cname + " @ " + rect.toShortString()
5918                + " text=" + info.getText() + " cd=" + info.getContentDescription());
5919        if (info.getText() != null || info.getError() != null) {
5920            structure.setText(info.getText(), info.getTextSelectionStart(),
5921                    info.getTextSelectionEnd());
5922        }
5923        final int NCHILDREN = info.getChildCount();
5924        if (NCHILDREN > 0) {
5925            structure.setChildCount(NCHILDREN);
5926            for (int i=0; i<NCHILDREN; i++) {
5927                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
5928                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
5929                ViewAssistStructure child = structure.newChild(i);
5930                populateVirtualAssistStructure(child, provider, cinfo);
5931                cinfo.recycle();
5932            }
5933        }
5934    }
5935
5936    /**
5937     * Dispatch creation of {@link ViewAssistStructure} down the hierarchy.  The default
5938     * implementation calls {@link #onProvideAssistStructure} and
5939     * {@link #onProvideVirtualAssistStructure}.
5940     */
5941    public void dispatchProvideAssistStructure(ViewAssistStructure structure) {
5942        if (!isAssistBlocked()) {
5943            onProvideAssistStructure(structure);
5944            onProvideVirtualAssistStructure(structure);
5945        } else {
5946            structure.setClassName(getAccessibilityClassName().toString());
5947            structure.setAssistBlocked(true);
5948        }
5949    }
5950
5951    /**
5952     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5953     *
5954     * Note: Called from the default {@link AccessibilityDelegate}.
5955     *
5956     * @hide
5957     */
5958    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5959        Rect bounds = mAttachInfo.mTmpInvalRect;
5960
5961        getDrawingRect(bounds);
5962        info.setBoundsInParent(bounds);
5963
5964        getBoundsOnScreen(bounds, true);
5965        info.setBoundsInScreen(bounds);
5966
5967        ViewParent parent = getParentForAccessibility();
5968        if (parent instanceof View) {
5969            info.setParent((View) parent);
5970        }
5971
5972        if (mID != View.NO_ID) {
5973            View rootView = getRootView();
5974            if (rootView == null) {
5975                rootView = this;
5976            }
5977
5978            View label = rootView.findLabelForView(this, mID);
5979            if (label != null) {
5980                info.setLabeledBy(label);
5981            }
5982
5983            if ((mAttachInfo.mAccessibilityFetchFlags
5984                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5985                    && Resources.resourceHasPackage(mID)) {
5986                try {
5987                    String viewId = getResources().getResourceName(mID);
5988                    info.setViewIdResourceName(viewId);
5989                } catch (Resources.NotFoundException nfe) {
5990                    /* ignore */
5991                }
5992            }
5993        }
5994
5995        if (mLabelForId != View.NO_ID) {
5996            View rootView = getRootView();
5997            if (rootView == null) {
5998                rootView = this;
5999            }
6000            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6001            if (labeled != null) {
6002                info.setLabelFor(labeled);
6003            }
6004        }
6005
6006        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6007            View rootView = getRootView();
6008            if (rootView == null) {
6009                rootView = this;
6010            }
6011            View next = rootView.findViewInsideOutShouldExist(this,
6012                    mAccessibilityTraversalBeforeId);
6013            if (next != null) {
6014                info.setTraversalBefore(next);
6015            }
6016        }
6017
6018        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6019            View rootView = getRootView();
6020            if (rootView == null) {
6021                rootView = this;
6022            }
6023            View next = rootView.findViewInsideOutShouldExist(this,
6024                    mAccessibilityTraversalAfterId);
6025            if (next != null) {
6026                info.setTraversalAfter(next);
6027            }
6028        }
6029
6030        info.setVisibleToUser(isVisibleToUser());
6031
6032        info.setPackageName(mContext.getPackageName());
6033        info.setClassName(getAccessibilityClassName());
6034        info.setContentDescription(getContentDescription());
6035
6036        info.setEnabled(isEnabled());
6037        info.setClickable(isClickable());
6038        info.setFocusable(isFocusable());
6039        info.setFocused(isFocused());
6040        info.setAccessibilityFocused(isAccessibilityFocused());
6041        info.setSelected(isSelected());
6042        info.setLongClickable(isLongClickable());
6043        info.setLiveRegion(getAccessibilityLiveRegion());
6044
6045        // TODO: These make sense only if we are in an AdapterView but all
6046        // views can be selected. Maybe from accessibility perspective
6047        // we should report as selectable view in an AdapterView.
6048        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6049        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6050
6051        if (isFocusable()) {
6052            if (isFocused()) {
6053                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6054            } else {
6055                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6056            }
6057        }
6058
6059        if (!isAccessibilityFocused()) {
6060            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6061        } else {
6062            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6063        }
6064
6065        if (isClickable() && isEnabled()) {
6066            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6067        }
6068
6069        if (isLongClickable() && isEnabled()) {
6070            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6071        }
6072
6073        CharSequence text = getIterableTextForAccessibility();
6074        if (text != null && text.length() > 0) {
6075            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6076
6077            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6078            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6079            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6080            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6081                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6082                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6083        }
6084
6085        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6086    }
6087
6088    private View findLabelForView(View view, int labeledId) {
6089        if (mMatchLabelForPredicate == null) {
6090            mMatchLabelForPredicate = new MatchLabelForPredicate();
6091        }
6092        mMatchLabelForPredicate.mLabeledId = labeledId;
6093        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6094    }
6095
6096    /**
6097     * Computes whether this view is visible to the user. Such a view is
6098     * attached, visible, all its predecessors are visible, it is not clipped
6099     * entirely by its predecessors, and has an alpha greater than zero.
6100     *
6101     * @return Whether the view is visible on the screen.
6102     *
6103     * @hide
6104     */
6105    protected boolean isVisibleToUser() {
6106        return isVisibleToUser(null);
6107    }
6108
6109    /**
6110     * Computes whether the given portion of this view is visible to the user.
6111     * Such a view is attached, visible, all its predecessors are visible,
6112     * has an alpha greater than zero, and the specified portion is not
6113     * clipped entirely by its predecessors.
6114     *
6115     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6116     *                    <code>null</code>, and the entire view will be tested in this case.
6117     *                    When <code>true</code> is returned by the function, the actual visible
6118     *                    region will be stored in this parameter; that is, if boundInView is fully
6119     *                    contained within the view, no modification will be made, otherwise regions
6120     *                    outside of the visible area of the view will be clipped.
6121     *
6122     * @return Whether the specified portion of the view is visible on the screen.
6123     *
6124     * @hide
6125     */
6126    protected boolean isVisibleToUser(Rect boundInView) {
6127        if (mAttachInfo != null) {
6128            // Attached to invisible window means this view is not visible.
6129            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6130                return false;
6131            }
6132            // An invisible predecessor or one with alpha zero means
6133            // that this view is not visible to the user.
6134            Object current = this;
6135            while (current instanceof View) {
6136                View view = (View) current;
6137                // We have attach info so this view is attached and there is no
6138                // need to check whether we reach to ViewRootImpl on the way up.
6139                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6140                        view.getVisibility() != VISIBLE) {
6141                    return false;
6142                }
6143                current = view.mParent;
6144            }
6145            // Check if the view is entirely covered by its predecessors.
6146            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6147            Point offset = mAttachInfo.mPoint;
6148            if (!getGlobalVisibleRect(visibleRect, offset)) {
6149                return false;
6150            }
6151            // Check if the visible portion intersects the rectangle of interest.
6152            if (boundInView != null) {
6153                visibleRect.offset(-offset.x, -offset.y);
6154                return boundInView.intersect(visibleRect);
6155            }
6156            return true;
6157        }
6158        return false;
6159    }
6160
6161    /**
6162     * Returns the delegate for implementing accessibility support via
6163     * composition. For more details see {@link AccessibilityDelegate}.
6164     *
6165     * @return The delegate, or null if none set.
6166     *
6167     * @hide
6168     */
6169    public AccessibilityDelegate getAccessibilityDelegate() {
6170        return mAccessibilityDelegate;
6171    }
6172
6173    /**
6174     * Sets a delegate for implementing accessibility support via composition as
6175     * opposed to inheritance. The delegate's primary use is for implementing
6176     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6177     *
6178     * @param delegate The delegate instance.
6179     *
6180     * @see AccessibilityDelegate
6181     */
6182    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6183        mAccessibilityDelegate = delegate;
6184    }
6185
6186    /**
6187     * Gets the provider for managing a virtual view hierarchy rooted at this View
6188     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6189     * that explore the window content.
6190     * <p>
6191     * If this method returns an instance, this instance is responsible for managing
6192     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6193     * View including the one representing the View itself. Similarly the returned
6194     * instance is responsible for performing accessibility actions on any virtual
6195     * view or the root view itself.
6196     * </p>
6197     * <p>
6198     * If an {@link AccessibilityDelegate} has been specified via calling
6199     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6200     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6201     * is responsible for handling this call.
6202     * </p>
6203     *
6204     * @return The provider.
6205     *
6206     * @see AccessibilityNodeProvider
6207     */
6208    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6209        if (mAccessibilityDelegate != null) {
6210            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6211        } else {
6212            return null;
6213        }
6214    }
6215
6216    /**
6217     * Gets the unique identifier of this view on the screen for accessibility purposes.
6218     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6219     *
6220     * @return The view accessibility id.
6221     *
6222     * @hide
6223     */
6224    public int getAccessibilityViewId() {
6225        if (mAccessibilityViewId == NO_ID) {
6226            mAccessibilityViewId = sNextAccessibilityViewId++;
6227        }
6228        return mAccessibilityViewId;
6229    }
6230
6231    /**
6232     * Gets the unique identifier of the window in which this View reseides.
6233     *
6234     * @return The window accessibility id.
6235     *
6236     * @hide
6237     */
6238    public int getAccessibilityWindowId() {
6239        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6240                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6241    }
6242
6243    /**
6244     * Gets the {@link View} description. It briefly describes the view and is
6245     * primarily used for accessibility support. Set this property to enable
6246     * better accessibility support for your application. This is especially
6247     * true for views that do not have textual representation (For example,
6248     * ImageButton).
6249     *
6250     * @return The content description.
6251     *
6252     * @attr ref android.R.styleable#View_contentDescription
6253     */
6254    @ViewDebug.ExportedProperty(category = "accessibility")
6255    public CharSequence getContentDescription() {
6256        return mContentDescription;
6257    }
6258
6259    /**
6260     * Sets the {@link View} description. It briefly describes the view and is
6261     * primarily used for accessibility support. Set this property to enable
6262     * better accessibility support for your application. This is especially
6263     * true for views that do not have textual representation (For example,
6264     * ImageButton).
6265     *
6266     * @param contentDescription The content description.
6267     *
6268     * @attr ref android.R.styleable#View_contentDescription
6269     */
6270    @RemotableViewMethod
6271    public void setContentDescription(CharSequence contentDescription) {
6272        if (mContentDescription == null) {
6273            if (contentDescription == null) {
6274                return;
6275            }
6276        } else if (mContentDescription.equals(contentDescription)) {
6277            return;
6278        }
6279        mContentDescription = contentDescription;
6280        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6281        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6282            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6283            notifySubtreeAccessibilityStateChangedIfNeeded();
6284        } else {
6285            notifyViewAccessibilityStateChangedIfNeeded(
6286                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6287        }
6288    }
6289
6290    /**
6291     * Sets the id of a view before which this one is visited in accessibility traversal.
6292     * A screen-reader must visit the content of this view before the content of the one
6293     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6294     * will traverse the entire content of B before traversing the entire content of A,
6295     * regardles of what traversal strategy it is using.
6296     * <p>
6297     * Views that do not have specified before/after relationships are traversed in order
6298     * determined by the screen-reader.
6299     * </p>
6300     * <p>
6301     * Setting that this view is before a view that is not important for accessibility
6302     * or if this view is not important for accessibility will have no effect as the
6303     * screen-reader is not aware of unimportant views.
6304     * </p>
6305     *
6306     * @param beforeId The id of a view this one precedes in accessibility traversal.
6307     *
6308     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6309     *
6310     * @see #setImportantForAccessibility(int)
6311     */
6312    @RemotableViewMethod
6313    public void setAccessibilityTraversalBefore(int beforeId) {
6314        if (mAccessibilityTraversalBeforeId == beforeId) {
6315            return;
6316        }
6317        mAccessibilityTraversalBeforeId = beforeId;
6318        notifyViewAccessibilityStateChangedIfNeeded(
6319                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6320    }
6321
6322    /**
6323     * Gets the id of a view before which this one is visited in accessibility traversal.
6324     *
6325     * @return The id of a view this one precedes in accessibility traversal if
6326     *         specified, otherwise {@link #NO_ID}.
6327     *
6328     * @see #setAccessibilityTraversalBefore(int)
6329     */
6330    public int getAccessibilityTraversalBefore() {
6331        return mAccessibilityTraversalBeforeId;
6332    }
6333
6334    /**
6335     * Sets the id of a view after which this one is visited in accessibility traversal.
6336     * A screen-reader must visit the content of the other view before the content of this
6337     * one. For example, if view B is set to be after view A, then a screen-reader
6338     * will traverse the entire content of A before traversing the entire content of B,
6339     * regardles of what traversal strategy it is using.
6340     * <p>
6341     * Views that do not have specified before/after relationships are traversed in order
6342     * determined by the screen-reader.
6343     * </p>
6344     * <p>
6345     * Setting that this view is after a view that is not important for accessibility
6346     * or if this view is not important for accessibility will have no effect as the
6347     * screen-reader is not aware of unimportant views.
6348     * </p>
6349     *
6350     * @param afterId The id of a view this one succedees in accessibility traversal.
6351     *
6352     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6353     *
6354     * @see #setImportantForAccessibility(int)
6355     */
6356    @RemotableViewMethod
6357    public void setAccessibilityTraversalAfter(int afterId) {
6358        if (mAccessibilityTraversalAfterId == afterId) {
6359            return;
6360        }
6361        mAccessibilityTraversalAfterId = afterId;
6362        notifyViewAccessibilityStateChangedIfNeeded(
6363                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6364    }
6365
6366    /**
6367     * Gets the id of a view after which this one is visited in accessibility traversal.
6368     *
6369     * @return The id of a view this one succeedes in accessibility traversal if
6370     *         specified, otherwise {@link #NO_ID}.
6371     *
6372     * @see #setAccessibilityTraversalAfter(int)
6373     */
6374    public int getAccessibilityTraversalAfter() {
6375        return mAccessibilityTraversalAfterId;
6376    }
6377
6378    /**
6379     * Gets the id of a view for which this view serves as a label for
6380     * accessibility purposes.
6381     *
6382     * @return The labeled view id.
6383     */
6384    @ViewDebug.ExportedProperty(category = "accessibility")
6385    public int getLabelFor() {
6386        return mLabelForId;
6387    }
6388
6389    /**
6390     * Sets the id of a view for which this view serves as a label for
6391     * accessibility purposes.
6392     *
6393     * @param id The labeled view id.
6394     */
6395    @RemotableViewMethod
6396    public void setLabelFor(@IdRes int id) {
6397        if (mLabelForId == id) {
6398            return;
6399        }
6400        mLabelForId = id;
6401        if (mLabelForId != View.NO_ID
6402                && mID == View.NO_ID) {
6403            mID = generateViewId();
6404        }
6405        notifyViewAccessibilityStateChangedIfNeeded(
6406                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6407    }
6408
6409    /**
6410     * Invoked whenever this view loses focus, either by losing window focus or by losing
6411     * focus within its window. This method can be used to clear any state tied to the
6412     * focus. For instance, if a button is held pressed with the trackball and the window
6413     * loses focus, this method can be used to cancel the press.
6414     *
6415     * Subclasses of View overriding this method should always call super.onFocusLost().
6416     *
6417     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6418     * @see #onWindowFocusChanged(boolean)
6419     *
6420     * @hide pending API council approval
6421     */
6422    @CallSuper
6423    protected void onFocusLost() {
6424        resetPressedState();
6425    }
6426
6427    private void resetPressedState() {
6428        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6429            return;
6430        }
6431
6432        if (isPressed()) {
6433            setPressed(false);
6434
6435            if (!mHasPerformedLongPress) {
6436                removeLongPressCallback();
6437            }
6438        }
6439    }
6440
6441    /**
6442     * Returns true if this view has focus
6443     *
6444     * @return True if this view has focus, false otherwise.
6445     */
6446    @ViewDebug.ExportedProperty(category = "focus")
6447    public boolean isFocused() {
6448        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6449    }
6450
6451    /**
6452     * Find the view in the hierarchy rooted at this view that currently has
6453     * focus.
6454     *
6455     * @return The view that currently has focus, or null if no focused view can
6456     *         be found.
6457     */
6458    public View findFocus() {
6459        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6460    }
6461
6462    /**
6463     * Indicates whether this view is one of the set of scrollable containers in
6464     * its window.
6465     *
6466     * @return whether this view is one of the set of scrollable containers in
6467     * its window
6468     *
6469     * @attr ref android.R.styleable#View_isScrollContainer
6470     */
6471    public boolean isScrollContainer() {
6472        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6473    }
6474
6475    /**
6476     * Change whether this view is one of the set of scrollable containers in
6477     * its window.  This will be used to determine whether the window can
6478     * resize or must pan when a soft input area is open -- scrollable
6479     * containers allow the window to use resize mode since the container
6480     * will appropriately shrink.
6481     *
6482     * @attr ref android.R.styleable#View_isScrollContainer
6483     */
6484    public void setScrollContainer(boolean isScrollContainer) {
6485        if (isScrollContainer) {
6486            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6487                mAttachInfo.mScrollContainers.add(this);
6488                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6489            }
6490            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6491        } else {
6492            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6493                mAttachInfo.mScrollContainers.remove(this);
6494            }
6495            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6496        }
6497    }
6498
6499    /**
6500     * Returns the quality of the drawing cache.
6501     *
6502     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6503     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6504     *
6505     * @see #setDrawingCacheQuality(int)
6506     * @see #setDrawingCacheEnabled(boolean)
6507     * @see #isDrawingCacheEnabled()
6508     *
6509     * @attr ref android.R.styleable#View_drawingCacheQuality
6510     */
6511    @DrawingCacheQuality
6512    public int getDrawingCacheQuality() {
6513        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6514    }
6515
6516    /**
6517     * Set the drawing cache quality of this view. This value is used only when the
6518     * drawing cache is enabled
6519     *
6520     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6521     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6522     *
6523     * @see #getDrawingCacheQuality()
6524     * @see #setDrawingCacheEnabled(boolean)
6525     * @see #isDrawingCacheEnabled()
6526     *
6527     * @attr ref android.R.styleable#View_drawingCacheQuality
6528     */
6529    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6530        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6531    }
6532
6533    /**
6534     * Returns whether the screen should remain on, corresponding to the current
6535     * value of {@link #KEEP_SCREEN_ON}.
6536     *
6537     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6538     *
6539     * @see #setKeepScreenOn(boolean)
6540     *
6541     * @attr ref android.R.styleable#View_keepScreenOn
6542     */
6543    public boolean getKeepScreenOn() {
6544        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6545    }
6546
6547    /**
6548     * Controls whether the screen should remain on, modifying the
6549     * value of {@link #KEEP_SCREEN_ON}.
6550     *
6551     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6552     *
6553     * @see #getKeepScreenOn()
6554     *
6555     * @attr ref android.R.styleable#View_keepScreenOn
6556     */
6557    public void setKeepScreenOn(boolean keepScreenOn) {
6558        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6559    }
6560
6561    /**
6562     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6563     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6564     *
6565     * @attr ref android.R.styleable#View_nextFocusLeft
6566     */
6567    public int getNextFocusLeftId() {
6568        return mNextFocusLeftId;
6569    }
6570
6571    /**
6572     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6573     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6574     * decide automatically.
6575     *
6576     * @attr ref android.R.styleable#View_nextFocusLeft
6577     */
6578    public void setNextFocusLeftId(int nextFocusLeftId) {
6579        mNextFocusLeftId = nextFocusLeftId;
6580    }
6581
6582    /**
6583     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6584     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6585     *
6586     * @attr ref android.R.styleable#View_nextFocusRight
6587     */
6588    public int getNextFocusRightId() {
6589        return mNextFocusRightId;
6590    }
6591
6592    /**
6593     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6594     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6595     * decide automatically.
6596     *
6597     * @attr ref android.R.styleable#View_nextFocusRight
6598     */
6599    public void setNextFocusRightId(int nextFocusRightId) {
6600        mNextFocusRightId = nextFocusRightId;
6601    }
6602
6603    /**
6604     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6605     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6606     *
6607     * @attr ref android.R.styleable#View_nextFocusUp
6608     */
6609    public int getNextFocusUpId() {
6610        return mNextFocusUpId;
6611    }
6612
6613    /**
6614     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6615     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6616     * decide automatically.
6617     *
6618     * @attr ref android.R.styleable#View_nextFocusUp
6619     */
6620    public void setNextFocusUpId(int nextFocusUpId) {
6621        mNextFocusUpId = nextFocusUpId;
6622    }
6623
6624    /**
6625     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6626     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6627     *
6628     * @attr ref android.R.styleable#View_nextFocusDown
6629     */
6630    public int getNextFocusDownId() {
6631        return mNextFocusDownId;
6632    }
6633
6634    /**
6635     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6636     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6637     * decide automatically.
6638     *
6639     * @attr ref android.R.styleable#View_nextFocusDown
6640     */
6641    public void setNextFocusDownId(int nextFocusDownId) {
6642        mNextFocusDownId = nextFocusDownId;
6643    }
6644
6645    /**
6646     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6647     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6648     *
6649     * @attr ref android.R.styleable#View_nextFocusForward
6650     */
6651    public int getNextFocusForwardId() {
6652        return mNextFocusForwardId;
6653    }
6654
6655    /**
6656     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6657     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6658     * decide automatically.
6659     *
6660     * @attr ref android.R.styleable#View_nextFocusForward
6661     */
6662    public void setNextFocusForwardId(int nextFocusForwardId) {
6663        mNextFocusForwardId = nextFocusForwardId;
6664    }
6665
6666    /**
6667     * Returns the visibility of this view and all of its ancestors
6668     *
6669     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6670     */
6671    public boolean isShown() {
6672        View current = this;
6673        //noinspection ConstantConditions
6674        do {
6675            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6676                return false;
6677            }
6678            ViewParent parent = current.mParent;
6679            if (parent == null) {
6680                return false; // We are not attached to the view root
6681            }
6682            if (!(parent instanceof View)) {
6683                return true;
6684            }
6685            current = (View) parent;
6686        } while (current != null);
6687
6688        return false;
6689    }
6690
6691    /**
6692     * Called by the view hierarchy when the content insets for a window have
6693     * changed, to allow it to adjust its content to fit within those windows.
6694     * The content insets tell you the space that the status bar, input method,
6695     * and other system windows infringe on the application's window.
6696     *
6697     * <p>You do not normally need to deal with this function, since the default
6698     * window decoration given to applications takes care of applying it to the
6699     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6700     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6701     * and your content can be placed under those system elements.  You can then
6702     * use this method within your view hierarchy if you have parts of your UI
6703     * which you would like to ensure are not being covered.
6704     *
6705     * <p>The default implementation of this method simply applies the content
6706     * insets to the view's padding, consuming that content (modifying the
6707     * insets to be 0), and returning true.  This behavior is off by default, but can
6708     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6709     *
6710     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6711     * insets object is propagated down the hierarchy, so any changes made to it will
6712     * be seen by all following views (including potentially ones above in
6713     * the hierarchy since this is a depth-first traversal).  The first view
6714     * that returns true will abort the entire traversal.
6715     *
6716     * <p>The default implementation works well for a situation where it is
6717     * used with a container that covers the entire window, allowing it to
6718     * apply the appropriate insets to its content on all edges.  If you need
6719     * a more complicated layout (such as two different views fitting system
6720     * windows, one on the top of the window, and one on the bottom),
6721     * you can override the method and handle the insets however you would like.
6722     * Note that the insets provided by the framework are always relative to the
6723     * far edges of the window, not accounting for the location of the called view
6724     * within that window.  (In fact when this method is called you do not yet know
6725     * where the layout will place the view, as it is done before layout happens.)
6726     *
6727     * <p>Note: unlike many View methods, there is no dispatch phase to this
6728     * call.  If you are overriding it in a ViewGroup and want to allow the
6729     * call to continue to your children, you must be sure to call the super
6730     * implementation.
6731     *
6732     * <p>Here is a sample layout that makes use of fitting system windows
6733     * to have controls for a video view placed inside of the window decorations
6734     * that it hides and shows.  This can be used with code like the second
6735     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6736     *
6737     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6738     *
6739     * @param insets Current content insets of the window.  Prior to
6740     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6741     * the insets or else you and Android will be unhappy.
6742     *
6743     * @return {@code true} if this view applied the insets and it should not
6744     * continue propagating further down the hierarchy, {@code false} otherwise.
6745     * @see #getFitsSystemWindows()
6746     * @see #setFitsSystemWindows(boolean)
6747     * @see #setSystemUiVisibility(int)
6748     *
6749     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6750     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6751     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6752     * to implement handling their own insets.
6753     */
6754    protected boolean fitSystemWindows(Rect insets) {
6755        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6756            if (insets == null) {
6757                // Null insets by definition have already been consumed.
6758                // This call cannot apply insets since there are none to apply,
6759                // so return false.
6760                return false;
6761            }
6762            // If we're not in the process of dispatching the newer apply insets call,
6763            // that means we're not in the compatibility path. Dispatch into the newer
6764            // apply insets path and take things from there.
6765            try {
6766                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6767                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6768            } finally {
6769                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6770            }
6771        } else {
6772            // We're being called from the newer apply insets path.
6773            // Perform the standard fallback behavior.
6774            return fitSystemWindowsInt(insets);
6775        }
6776    }
6777
6778    private boolean fitSystemWindowsInt(Rect insets) {
6779        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6780            mUserPaddingStart = UNDEFINED_PADDING;
6781            mUserPaddingEnd = UNDEFINED_PADDING;
6782            Rect localInsets = sThreadLocal.get();
6783            if (localInsets == null) {
6784                localInsets = new Rect();
6785                sThreadLocal.set(localInsets);
6786            }
6787            boolean res = computeFitSystemWindows(insets, localInsets);
6788            mUserPaddingLeftInitial = localInsets.left;
6789            mUserPaddingRightInitial = localInsets.right;
6790            internalSetPadding(localInsets.left, localInsets.top,
6791                    localInsets.right, localInsets.bottom);
6792            return res;
6793        }
6794        return false;
6795    }
6796
6797    /**
6798     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6799     *
6800     * <p>This method should be overridden by views that wish to apply a policy different from or
6801     * in addition to the default behavior. Clients that wish to force a view subtree
6802     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6803     *
6804     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6805     * it will be called during dispatch instead of this method. The listener may optionally
6806     * call this method from its own implementation if it wishes to apply the view's default
6807     * insets policy in addition to its own.</p>
6808     *
6809     * <p>Implementations of this method should either return the insets parameter unchanged
6810     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6811     * that this view applied itself. This allows new inset types added in future platform
6812     * versions to pass through existing implementations unchanged without being erroneously
6813     * consumed.</p>
6814     *
6815     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6816     * property is set then the view will consume the system window insets and apply them
6817     * as padding for the view.</p>
6818     *
6819     * @param insets Insets to apply
6820     * @return The supplied insets with any applied insets consumed
6821     */
6822    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6823        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6824            // We weren't called from within a direct call to fitSystemWindows,
6825            // call into it as a fallback in case we're in a class that overrides it
6826            // and has logic to perform.
6827            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6828                return insets.consumeSystemWindowInsets();
6829            }
6830        } else {
6831            // We were called from within a direct call to fitSystemWindows.
6832            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6833                return insets.consumeSystemWindowInsets();
6834            }
6835        }
6836        return insets;
6837    }
6838
6839    /**
6840     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6841     * window insets to this view. The listener's
6842     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6843     * method will be called instead of the view's
6844     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6845     *
6846     * @param listener Listener to set
6847     *
6848     * @see #onApplyWindowInsets(WindowInsets)
6849     */
6850    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6851        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6852    }
6853
6854    /**
6855     * Request to apply the given window insets to this view or another view in its subtree.
6856     *
6857     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6858     * obscured by window decorations or overlays. This can include the status and navigation bars,
6859     * action bars, input methods and more. New inset categories may be added in the future.
6860     * The method returns the insets provided minus any that were applied by this view or its
6861     * children.</p>
6862     *
6863     * <p>Clients wishing to provide custom behavior should override the
6864     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6865     * {@link OnApplyWindowInsetsListener} via the
6866     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6867     * method.</p>
6868     *
6869     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6870     * </p>
6871     *
6872     * @param insets Insets to apply
6873     * @return The provided insets minus the insets that were consumed
6874     */
6875    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6876        try {
6877            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6878            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6879                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6880            } else {
6881                return onApplyWindowInsets(insets);
6882            }
6883        } finally {
6884            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6885        }
6886    }
6887
6888    /**
6889     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
6890     * only available if the view is attached.
6891     *
6892     * @return WindowInsets from the top of the view hierarchy or null if View is detached
6893     */
6894    public WindowInsets getRootWindowInsets() {
6895        if (mAttachInfo != null) {
6896            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
6897        }
6898        return null;
6899    }
6900
6901    /**
6902     * @hide Compute the insets that should be consumed by this view and the ones
6903     * that should propagate to those under it.
6904     */
6905    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6906        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6907                || mAttachInfo == null
6908                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6909                        && !mAttachInfo.mOverscanRequested)) {
6910            outLocalInsets.set(inoutInsets);
6911            inoutInsets.set(0, 0, 0, 0);
6912            return true;
6913        } else {
6914            // The application wants to take care of fitting system window for
6915            // the content...  however we still need to take care of any overscan here.
6916            final Rect overscan = mAttachInfo.mOverscanInsets;
6917            outLocalInsets.set(overscan);
6918            inoutInsets.left -= overscan.left;
6919            inoutInsets.top -= overscan.top;
6920            inoutInsets.right -= overscan.right;
6921            inoutInsets.bottom -= overscan.bottom;
6922            return false;
6923        }
6924    }
6925
6926    /**
6927     * Compute insets that should be consumed by this view and the ones that should propagate
6928     * to those under it.
6929     *
6930     * @param in Insets currently being processed by this View, likely received as a parameter
6931     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6932     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6933     *                       by this view
6934     * @return Insets that should be passed along to views under this one
6935     */
6936    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6937        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6938                || mAttachInfo == null
6939                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6940            outLocalInsets.set(in.getSystemWindowInsets());
6941            return in.consumeSystemWindowInsets();
6942        } else {
6943            outLocalInsets.set(0, 0, 0, 0);
6944            return in;
6945        }
6946    }
6947
6948    /**
6949     * Sets whether or not this view should account for system screen decorations
6950     * such as the status bar and inset its content; that is, controlling whether
6951     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6952     * executed.  See that method for more details.
6953     *
6954     * <p>Note that if you are providing your own implementation of
6955     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6956     * flag to true -- your implementation will be overriding the default
6957     * implementation that checks this flag.
6958     *
6959     * @param fitSystemWindows If true, then the default implementation of
6960     * {@link #fitSystemWindows(Rect)} will be executed.
6961     *
6962     * @attr ref android.R.styleable#View_fitsSystemWindows
6963     * @see #getFitsSystemWindows()
6964     * @see #fitSystemWindows(Rect)
6965     * @see #setSystemUiVisibility(int)
6966     */
6967    public void setFitsSystemWindows(boolean fitSystemWindows) {
6968        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6969    }
6970
6971    /**
6972     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6973     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6974     * will be executed.
6975     *
6976     * @return {@code true} if the default implementation of
6977     * {@link #fitSystemWindows(Rect)} will be executed.
6978     *
6979     * @attr ref android.R.styleable#View_fitsSystemWindows
6980     * @see #setFitsSystemWindows(boolean)
6981     * @see #fitSystemWindows(Rect)
6982     * @see #setSystemUiVisibility(int)
6983     */
6984    @ViewDebug.ExportedProperty
6985    public boolean getFitsSystemWindows() {
6986        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6987    }
6988
6989    /** @hide */
6990    public boolean fitsSystemWindows() {
6991        return getFitsSystemWindows();
6992    }
6993
6994    /**
6995     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6996     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6997     */
6998    public void requestFitSystemWindows() {
6999        if (mParent != null) {
7000            mParent.requestFitSystemWindows();
7001        }
7002    }
7003
7004    /**
7005     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7006     */
7007    public void requestApplyInsets() {
7008        requestFitSystemWindows();
7009    }
7010
7011    /**
7012     * For use by PhoneWindow to make its own system window fitting optional.
7013     * @hide
7014     */
7015    public void makeOptionalFitsSystemWindows() {
7016        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7017    }
7018
7019    /**
7020     * Returns the visibility status for this view.
7021     *
7022     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7023     * @attr ref android.R.styleable#View_visibility
7024     */
7025    @ViewDebug.ExportedProperty(mapping = {
7026        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7027        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7028        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7029    })
7030    @Visibility
7031    public int getVisibility() {
7032        return mViewFlags & VISIBILITY_MASK;
7033    }
7034
7035    /**
7036     * Set the enabled state of this view.
7037     *
7038     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7039     * @attr ref android.R.styleable#View_visibility
7040     */
7041    @RemotableViewMethod
7042    public void setVisibility(@Visibility int visibility) {
7043        setFlags(visibility, VISIBILITY_MASK);
7044    }
7045
7046    /**
7047     * Returns the enabled status for this view. The interpretation of the
7048     * enabled state varies by subclass.
7049     *
7050     * @return True if this view is enabled, false otherwise.
7051     */
7052    @ViewDebug.ExportedProperty
7053    public boolean isEnabled() {
7054        return (mViewFlags & ENABLED_MASK) == ENABLED;
7055    }
7056
7057    /**
7058     * Set the enabled state of this view. The interpretation of the enabled
7059     * state varies by subclass.
7060     *
7061     * @param enabled True if this view is enabled, false otherwise.
7062     */
7063    @RemotableViewMethod
7064    public void setEnabled(boolean enabled) {
7065        if (enabled == isEnabled()) return;
7066
7067        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7068
7069        /*
7070         * The View most likely has to change its appearance, so refresh
7071         * the drawable state.
7072         */
7073        refreshDrawableState();
7074
7075        // Invalidate too, since the default behavior for views is to be
7076        // be drawn at 50% alpha rather than to change the drawable.
7077        invalidate(true);
7078
7079        if (!enabled) {
7080            cancelPendingInputEvents();
7081        }
7082    }
7083
7084    /**
7085     * Set whether this view can receive the focus.
7086     *
7087     * Setting this to false will also ensure that this view is not focusable
7088     * in touch mode.
7089     *
7090     * @param focusable If true, this view can receive the focus.
7091     *
7092     * @see #setFocusableInTouchMode(boolean)
7093     * @attr ref android.R.styleable#View_focusable
7094     */
7095    public void setFocusable(boolean focusable) {
7096        if (!focusable) {
7097            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7098        }
7099        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7100    }
7101
7102    /**
7103     * Set whether this view can receive focus while in touch mode.
7104     *
7105     * Setting this to true will also ensure that this view is focusable.
7106     *
7107     * @param focusableInTouchMode If true, this view can receive the focus while
7108     *   in touch mode.
7109     *
7110     * @see #setFocusable(boolean)
7111     * @attr ref android.R.styleable#View_focusableInTouchMode
7112     */
7113    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7114        // Focusable in touch mode should always be set before the focusable flag
7115        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7116        // which, in touch mode, will not successfully request focus on this view
7117        // because the focusable in touch mode flag is not set
7118        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7119        if (focusableInTouchMode) {
7120            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7121        }
7122    }
7123
7124    /**
7125     * Set whether this view should have sound effects enabled for events such as
7126     * clicking and touching.
7127     *
7128     * <p>You may wish to disable sound effects for a view if you already play sounds,
7129     * for instance, a dial key that plays dtmf tones.
7130     *
7131     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7132     * @see #isSoundEffectsEnabled()
7133     * @see #playSoundEffect(int)
7134     * @attr ref android.R.styleable#View_soundEffectsEnabled
7135     */
7136    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7137        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7138    }
7139
7140    /**
7141     * @return whether this view should have sound effects enabled for events such as
7142     *     clicking and touching.
7143     *
7144     * @see #setSoundEffectsEnabled(boolean)
7145     * @see #playSoundEffect(int)
7146     * @attr ref android.R.styleable#View_soundEffectsEnabled
7147     */
7148    @ViewDebug.ExportedProperty
7149    public boolean isSoundEffectsEnabled() {
7150        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7151    }
7152
7153    /**
7154     * Set whether this view should have haptic feedback for events such as
7155     * long presses.
7156     *
7157     * <p>You may wish to disable haptic feedback if your view already controls
7158     * its own haptic feedback.
7159     *
7160     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7161     * @see #isHapticFeedbackEnabled()
7162     * @see #performHapticFeedback(int)
7163     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7164     */
7165    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7166        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7167    }
7168
7169    /**
7170     * @return whether this view should have haptic feedback enabled for events
7171     * long presses.
7172     *
7173     * @see #setHapticFeedbackEnabled(boolean)
7174     * @see #performHapticFeedback(int)
7175     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7176     */
7177    @ViewDebug.ExportedProperty
7178    public boolean isHapticFeedbackEnabled() {
7179        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7180    }
7181
7182    /**
7183     * Returns the layout direction for this view.
7184     *
7185     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7186     *   {@link #LAYOUT_DIRECTION_RTL},
7187     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7188     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7189     *
7190     * @attr ref android.R.styleable#View_layoutDirection
7191     *
7192     * @hide
7193     */
7194    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7195        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7196        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7197        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7198        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7199    })
7200    @LayoutDir
7201    public int getRawLayoutDirection() {
7202        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7203    }
7204
7205    /**
7206     * Set the layout direction for this view. This will propagate a reset of layout direction
7207     * resolution to the view's children and resolve layout direction for this view.
7208     *
7209     * @param layoutDirection the layout direction to set. Should be one of:
7210     *
7211     * {@link #LAYOUT_DIRECTION_LTR},
7212     * {@link #LAYOUT_DIRECTION_RTL},
7213     * {@link #LAYOUT_DIRECTION_INHERIT},
7214     * {@link #LAYOUT_DIRECTION_LOCALE}.
7215     *
7216     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7217     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7218     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7219     *
7220     * @attr ref android.R.styleable#View_layoutDirection
7221     */
7222    @RemotableViewMethod
7223    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7224        if (getRawLayoutDirection() != layoutDirection) {
7225            // Reset the current layout direction and the resolved one
7226            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7227            resetRtlProperties();
7228            // Set the new layout direction (filtered)
7229            mPrivateFlags2 |=
7230                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7231            // We need to resolve all RTL properties as they all depend on layout direction
7232            resolveRtlPropertiesIfNeeded();
7233            requestLayout();
7234            invalidate(true);
7235        }
7236    }
7237
7238    /**
7239     * Returns the resolved layout direction for this view.
7240     *
7241     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7242     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7243     *
7244     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7245     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7246     *
7247     * @attr ref android.R.styleable#View_layoutDirection
7248     */
7249    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7250        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7251        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7252    })
7253    @ResolvedLayoutDir
7254    public int getLayoutDirection() {
7255        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7256        if (targetSdkVersion < JELLY_BEAN_MR1) {
7257            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7258            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7259        }
7260        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7261                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7262    }
7263
7264    /**
7265     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7266     * layout attribute and/or the inherited value from the parent
7267     *
7268     * @return true if the layout is right-to-left.
7269     *
7270     * @hide
7271     */
7272    @ViewDebug.ExportedProperty(category = "layout")
7273    public boolean isLayoutRtl() {
7274        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7275    }
7276
7277    /**
7278     * Indicates whether the view is currently tracking transient state that the
7279     * app should not need to concern itself with saving and restoring, but that
7280     * the framework should take special note to preserve when possible.
7281     *
7282     * <p>A view with transient state cannot be trivially rebound from an external
7283     * data source, such as an adapter binding item views in a list. This may be
7284     * because the view is performing an animation, tracking user selection
7285     * of content, or similar.</p>
7286     *
7287     * @return true if the view has transient state
7288     */
7289    @ViewDebug.ExportedProperty(category = "layout")
7290    public boolean hasTransientState() {
7291        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7292    }
7293
7294    /**
7295     * Set whether this view is currently tracking transient state that the
7296     * framework should attempt to preserve when possible. This flag is reference counted,
7297     * so every call to setHasTransientState(true) should be paired with a later call
7298     * to setHasTransientState(false).
7299     *
7300     * <p>A view with transient state cannot be trivially rebound from an external
7301     * data source, such as an adapter binding item views in a list. This may be
7302     * because the view is performing an animation, tracking user selection
7303     * of content, or similar.</p>
7304     *
7305     * @param hasTransientState true if this view has transient state
7306     */
7307    public void setHasTransientState(boolean hasTransientState) {
7308        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7309                mTransientStateCount - 1;
7310        if (mTransientStateCount < 0) {
7311            mTransientStateCount = 0;
7312            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7313                    "unmatched pair of setHasTransientState calls");
7314        } else if ((hasTransientState && mTransientStateCount == 1) ||
7315                (!hasTransientState && mTransientStateCount == 0)) {
7316            // update flag if we've just incremented up from 0 or decremented down to 0
7317            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7318                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7319            if (mParent != null) {
7320                try {
7321                    mParent.childHasTransientStateChanged(this, hasTransientState);
7322                } catch (AbstractMethodError e) {
7323                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7324                            " does not fully implement ViewParent", e);
7325                }
7326            }
7327        }
7328    }
7329
7330    /**
7331     * Returns true if this view is currently attached to a window.
7332     */
7333    public boolean isAttachedToWindow() {
7334        return mAttachInfo != null;
7335    }
7336
7337    /**
7338     * Returns true if this view has been through at least one layout since it
7339     * was last attached to or detached from a window.
7340     */
7341    public boolean isLaidOut() {
7342        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7343    }
7344
7345    /**
7346     * If this view doesn't do any drawing on its own, set this flag to
7347     * allow further optimizations. By default, this flag is not set on
7348     * View, but could be set on some View subclasses such as ViewGroup.
7349     *
7350     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7351     * you should clear this flag.
7352     *
7353     * @param willNotDraw whether or not this View draw on its own
7354     */
7355    public void setWillNotDraw(boolean willNotDraw) {
7356        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7357    }
7358
7359    /**
7360     * Returns whether or not this View draws on its own.
7361     *
7362     * @return true if this view has nothing to draw, false otherwise
7363     */
7364    @ViewDebug.ExportedProperty(category = "drawing")
7365    public boolean willNotDraw() {
7366        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7367    }
7368
7369    /**
7370     * When a View's drawing cache is enabled, drawing is redirected to an
7371     * offscreen bitmap. Some views, like an ImageView, must be able to
7372     * bypass this mechanism if they already draw a single bitmap, to avoid
7373     * unnecessary usage of the memory.
7374     *
7375     * @param willNotCacheDrawing true if this view does not cache its
7376     *        drawing, false otherwise
7377     */
7378    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7379        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7380    }
7381
7382    /**
7383     * Returns whether or not this View can cache its drawing or not.
7384     *
7385     * @return true if this view does not cache its drawing, false otherwise
7386     */
7387    @ViewDebug.ExportedProperty(category = "drawing")
7388    public boolean willNotCacheDrawing() {
7389        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7390    }
7391
7392    /**
7393     * Indicates whether this view reacts to click events or not.
7394     *
7395     * @return true if the view is clickable, false otherwise
7396     *
7397     * @see #setClickable(boolean)
7398     * @attr ref android.R.styleable#View_clickable
7399     */
7400    @ViewDebug.ExportedProperty
7401    public boolean isClickable() {
7402        return (mViewFlags & CLICKABLE) == CLICKABLE;
7403    }
7404
7405    /**
7406     * Enables or disables click events for this view. When a view
7407     * is clickable it will change its state to "pressed" on every click.
7408     * Subclasses should set the view clickable to visually react to
7409     * user's clicks.
7410     *
7411     * @param clickable true to make the view clickable, false otherwise
7412     *
7413     * @see #isClickable()
7414     * @attr ref android.R.styleable#View_clickable
7415     */
7416    public void setClickable(boolean clickable) {
7417        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7418    }
7419
7420    /**
7421     * Indicates whether this view reacts to long click events or not.
7422     *
7423     * @return true if the view is long clickable, false otherwise
7424     *
7425     * @see #setLongClickable(boolean)
7426     * @attr ref android.R.styleable#View_longClickable
7427     */
7428    public boolean isLongClickable() {
7429        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7430    }
7431
7432    /**
7433     * Enables or disables long click events for this view. When a view is long
7434     * clickable it reacts to the user holding down the button for a longer
7435     * duration than a tap. This event can either launch the listener or a
7436     * context menu.
7437     *
7438     * @param longClickable true to make the view long clickable, false otherwise
7439     * @see #isLongClickable()
7440     * @attr ref android.R.styleable#View_longClickable
7441     */
7442    public void setLongClickable(boolean longClickable) {
7443        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7444    }
7445
7446    /**
7447     * Sets the pressed state for this view and provides a touch coordinate for
7448     * animation hinting.
7449     *
7450     * @param pressed Pass true to set the View's internal state to "pressed",
7451     *            or false to reverts the View's internal state from a
7452     *            previously set "pressed" state.
7453     * @param x The x coordinate of the touch that caused the press
7454     * @param y The y coordinate of the touch that caused the press
7455     */
7456    private void setPressed(boolean pressed, float x, float y) {
7457        if (pressed) {
7458            drawableHotspotChanged(x, y);
7459        }
7460
7461        setPressed(pressed);
7462    }
7463
7464    /**
7465     * Sets the pressed state for this view.
7466     *
7467     * @see #isClickable()
7468     * @see #setClickable(boolean)
7469     *
7470     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7471     *        the View's internal state from a previously set "pressed" state.
7472     */
7473    public void setPressed(boolean pressed) {
7474        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7475
7476        if (pressed) {
7477            mPrivateFlags |= PFLAG_PRESSED;
7478        } else {
7479            mPrivateFlags &= ~PFLAG_PRESSED;
7480        }
7481
7482        if (needsRefresh) {
7483            refreshDrawableState();
7484        }
7485        dispatchSetPressed(pressed);
7486    }
7487
7488    /**
7489     * Dispatch setPressed to all of this View's children.
7490     *
7491     * @see #setPressed(boolean)
7492     *
7493     * @param pressed The new pressed state
7494     */
7495    protected void dispatchSetPressed(boolean pressed) {
7496    }
7497
7498    /**
7499     * Indicates whether the view is currently in pressed state. Unless
7500     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7501     * the pressed state.
7502     *
7503     * @see #setPressed(boolean)
7504     * @see #isClickable()
7505     * @see #setClickable(boolean)
7506     *
7507     * @return true if the view is currently pressed, false otherwise
7508     */
7509    @ViewDebug.ExportedProperty
7510    public boolean isPressed() {
7511        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7512    }
7513
7514    /**
7515     * Indicates whether this view will participate in data collection through
7516     * {@link android.view.ViewAssistStructure}.  If true, it will not provide any data
7517     * for itself or its children.  If false, the normal data collection will be allowed.
7518     *
7519     * @return Returns false if assist data collection is not blocked, else true.
7520     *
7521     * @see #setAssistBlocked(boolean)
7522     * @attr ref android.R.styleable#View_assistBlocked
7523     */
7524    public boolean isAssistBlocked() {
7525        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
7526    }
7527
7528    /**
7529     * Controls whether assist data collection from this view and its children is enabled
7530     * (that is, whether {@link #onProvideAssistStructure} and
7531     * {@link #onProvideVirtualAssistStructure} will be called).  The default value is false,
7532     * allowing normal assist collection.  Setting this to false will disable assist collection.
7533     *
7534     * @param enabled Set to true to <em>disable</em> assist data collection, or false
7535     * (the default) to allow it.
7536     *
7537     * @see #isAssistBlocked()
7538     * @see #onProvideAssistStructure
7539     * @see #onProvideVirtualAssistStructure
7540     * @attr ref android.R.styleable#View_assistBlocked
7541     */
7542    public void setAssistBlocked(boolean enabled) {
7543        if (enabled) {
7544            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
7545        } else {
7546            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
7547        }
7548    }
7549
7550    /**
7551     * Indicates whether this view will save its state (that is,
7552     * whether its {@link #onSaveInstanceState} method will be called).
7553     *
7554     * @return Returns true if the view state saving is enabled, else false.
7555     *
7556     * @see #setSaveEnabled(boolean)
7557     * @attr ref android.R.styleable#View_saveEnabled
7558     */
7559    public boolean isSaveEnabled() {
7560        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7561    }
7562
7563    /**
7564     * Controls whether the saving of this view's state is
7565     * enabled (that is, whether its {@link #onSaveInstanceState} method
7566     * will be called).  Note that even if freezing is enabled, the
7567     * view still must have an id assigned to it (via {@link #setId(int)})
7568     * for its state to be saved.  This flag can only disable the
7569     * saving of this view; any child views may still have their state saved.
7570     *
7571     * @param enabled Set to false to <em>disable</em> state saving, or true
7572     * (the default) to allow it.
7573     *
7574     * @see #isSaveEnabled()
7575     * @see #setId(int)
7576     * @see #onSaveInstanceState()
7577     * @attr ref android.R.styleable#View_saveEnabled
7578     */
7579    public void setSaveEnabled(boolean enabled) {
7580        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7581    }
7582
7583    /**
7584     * Gets whether the framework should discard touches when the view's
7585     * window is obscured by another visible window.
7586     * Refer to the {@link View} security documentation for more details.
7587     *
7588     * @return True if touch filtering is enabled.
7589     *
7590     * @see #setFilterTouchesWhenObscured(boolean)
7591     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7592     */
7593    @ViewDebug.ExportedProperty
7594    public boolean getFilterTouchesWhenObscured() {
7595        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7596    }
7597
7598    /**
7599     * Sets whether the framework should discard touches when the view's
7600     * window is obscured by another visible window.
7601     * Refer to the {@link View} security documentation for more details.
7602     *
7603     * @param enabled True if touch filtering should be enabled.
7604     *
7605     * @see #getFilterTouchesWhenObscured
7606     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7607     */
7608    public void setFilterTouchesWhenObscured(boolean enabled) {
7609        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7610                FILTER_TOUCHES_WHEN_OBSCURED);
7611    }
7612
7613    /**
7614     * Indicates whether the entire hierarchy under this view will save its
7615     * state when a state saving traversal occurs from its parent.  The default
7616     * is true; if false, these views will not be saved unless
7617     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7618     *
7619     * @return Returns true if the view state saving from parent is enabled, else false.
7620     *
7621     * @see #setSaveFromParentEnabled(boolean)
7622     */
7623    public boolean isSaveFromParentEnabled() {
7624        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7625    }
7626
7627    /**
7628     * Controls whether the entire hierarchy under this view will save its
7629     * state when a state saving traversal occurs from its parent.  The default
7630     * is true; if false, these views will not be saved unless
7631     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7632     *
7633     * @param enabled Set to false to <em>disable</em> state saving, or true
7634     * (the default) to allow it.
7635     *
7636     * @see #isSaveFromParentEnabled()
7637     * @see #setId(int)
7638     * @see #onSaveInstanceState()
7639     */
7640    public void setSaveFromParentEnabled(boolean enabled) {
7641        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7642    }
7643
7644
7645    /**
7646     * Returns whether this View is able to take focus.
7647     *
7648     * @return True if this view can take focus, or false otherwise.
7649     * @attr ref android.R.styleable#View_focusable
7650     */
7651    @ViewDebug.ExportedProperty(category = "focus")
7652    public final boolean isFocusable() {
7653        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7654    }
7655
7656    /**
7657     * When a view is focusable, it may not want to take focus when in touch mode.
7658     * For example, a button would like focus when the user is navigating via a D-pad
7659     * so that the user can click on it, but once the user starts touching the screen,
7660     * the button shouldn't take focus
7661     * @return Whether the view is focusable in touch mode.
7662     * @attr ref android.R.styleable#View_focusableInTouchMode
7663     */
7664    @ViewDebug.ExportedProperty
7665    public final boolean isFocusableInTouchMode() {
7666        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7667    }
7668
7669    /**
7670     * Find the nearest view in the specified direction that can take focus.
7671     * This does not actually give focus to that view.
7672     *
7673     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7674     *
7675     * @return The nearest focusable in the specified direction, or null if none
7676     *         can be found.
7677     */
7678    public View focusSearch(@FocusRealDirection int direction) {
7679        if (mParent != null) {
7680            return mParent.focusSearch(this, direction);
7681        } else {
7682            return null;
7683        }
7684    }
7685
7686    /**
7687     * This method is the last chance for the focused view and its ancestors to
7688     * respond to an arrow key. This is called when the focused view did not
7689     * consume the key internally, nor could the view system find a new view in
7690     * the requested direction to give focus to.
7691     *
7692     * @param focused The currently focused view.
7693     * @param direction The direction focus wants to move. One of FOCUS_UP,
7694     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7695     * @return True if the this view consumed this unhandled move.
7696     */
7697    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7698        return false;
7699    }
7700
7701    /**
7702     * If a user manually specified the next view id for a particular direction,
7703     * use the root to look up the view.
7704     * @param root The root view of the hierarchy containing this view.
7705     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7706     * or FOCUS_BACKWARD.
7707     * @return The user specified next view, or null if there is none.
7708     */
7709    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7710        switch (direction) {
7711            case FOCUS_LEFT:
7712                if (mNextFocusLeftId == View.NO_ID) return null;
7713                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7714            case FOCUS_RIGHT:
7715                if (mNextFocusRightId == View.NO_ID) return null;
7716                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7717            case FOCUS_UP:
7718                if (mNextFocusUpId == View.NO_ID) return null;
7719                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7720            case FOCUS_DOWN:
7721                if (mNextFocusDownId == View.NO_ID) return null;
7722                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7723            case FOCUS_FORWARD:
7724                if (mNextFocusForwardId == View.NO_ID) return null;
7725                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7726            case FOCUS_BACKWARD: {
7727                if (mID == View.NO_ID) return null;
7728                final int id = mID;
7729                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7730                    @Override
7731                    public boolean apply(View t) {
7732                        return t.mNextFocusForwardId == id;
7733                    }
7734                });
7735            }
7736        }
7737        return null;
7738    }
7739
7740    private View findViewInsideOutShouldExist(View root, int id) {
7741        if (mMatchIdPredicate == null) {
7742            mMatchIdPredicate = new MatchIdPredicate();
7743        }
7744        mMatchIdPredicate.mId = id;
7745        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7746        if (result == null) {
7747            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7748        }
7749        return result;
7750    }
7751
7752    /**
7753     * Find and return all focusable views that are descendants of this view,
7754     * possibly including this view if it is focusable itself.
7755     *
7756     * @param direction The direction of the focus
7757     * @return A list of focusable views
7758     */
7759    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7760        ArrayList<View> result = new ArrayList<View>(24);
7761        addFocusables(result, direction);
7762        return result;
7763    }
7764
7765    /**
7766     * Add any focusable views that are descendants of this view (possibly
7767     * including this view if it is focusable itself) to views.  If we are in touch mode,
7768     * only add views that are also focusable in touch mode.
7769     *
7770     * @param views Focusable views found so far
7771     * @param direction The direction of the focus
7772     */
7773    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7774        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7775    }
7776
7777    /**
7778     * Adds any focusable views that are descendants of this view (possibly
7779     * including this view if it is focusable itself) to views. This method
7780     * adds all focusable views regardless if we are in touch mode or
7781     * only views focusable in touch mode if we are in touch mode or
7782     * only views that can take accessibility focus if accessibility is enabled
7783     * depending on the focusable mode parameter.
7784     *
7785     * @param views Focusable views found so far or null if all we are interested is
7786     *        the number of focusables.
7787     * @param direction The direction of the focus.
7788     * @param focusableMode The type of focusables to be added.
7789     *
7790     * @see #FOCUSABLES_ALL
7791     * @see #FOCUSABLES_TOUCH_MODE
7792     */
7793    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7794            @FocusableMode int focusableMode) {
7795        if (views == null) {
7796            return;
7797        }
7798        if (!isFocusable()) {
7799            return;
7800        }
7801        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7802                && isInTouchMode() && !isFocusableInTouchMode()) {
7803            return;
7804        }
7805        views.add(this);
7806    }
7807
7808    /**
7809     * Finds the Views that contain given text. The containment is case insensitive.
7810     * The search is performed by either the text that the View renders or the content
7811     * description that describes the view for accessibility purposes and the view does
7812     * not render or both. Clients can specify how the search is to be performed via
7813     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7814     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7815     *
7816     * @param outViews The output list of matching Views.
7817     * @param searched The text to match against.
7818     *
7819     * @see #FIND_VIEWS_WITH_TEXT
7820     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7821     * @see #setContentDescription(CharSequence)
7822     */
7823    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7824            @FindViewFlags int flags) {
7825        if (getAccessibilityNodeProvider() != null) {
7826            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7827                outViews.add(this);
7828            }
7829        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7830                && (searched != null && searched.length() > 0)
7831                && (mContentDescription != null && mContentDescription.length() > 0)) {
7832            String searchedLowerCase = searched.toString().toLowerCase();
7833            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7834            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7835                outViews.add(this);
7836            }
7837        }
7838    }
7839
7840    /**
7841     * Find and return all touchable views that are descendants of this view,
7842     * possibly including this view if it is touchable itself.
7843     *
7844     * @return A list of touchable views
7845     */
7846    public ArrayList<View> getTouchables() {
7847        ArrayList<View> result = new ArrayList<View>();
7848        addTouchables(result);
7849        return result;
7850    }
7851
7852    /**
7853     * Add any touchable views that are descendants of this view (possibly
7854     * including this view if it is touchable itself) to views.
7855     *
7856     * @param views Touchable views found so far
7857     */
7858    public void addTouchables(ArrayList<View> views) {
7859        final int viewFlags = mViewFlags;
7860
7861        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7862                && (viewFlags & ENABLED_MASK) == ENABLED) {
7863            views.add(this);
7864        }
7865    }
7866
7867    /**
7868     * Returns whether this View is accessibility focused.
7869     *
7870     * @return True if this View is accessibility focused.
7871     */
7872    public boolean isAccessibilityFocused() {
7873        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7874    }
7875
7876    /**
7877     * Call this to try to give accessibility focus to this view.
7878     *
7879     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7880     * returns false or the view is no visible or the view already has accessibility
7881     * focus.
7882     *
7883     * See also {@link #focusSearch(int)}, which is what you call to say that you
7884     * have focus, and you want your parent to look for the next one.
7885     *
7886     * @return Whether this view actually took accessibility focus.
7887     *
7888     * @hide
7889     */
7890    public boolean requestAccessibilityFocus() {
7891        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7892        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7893            return false;
7894        }
7895        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7896            return false;
7897        }
7898        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7899            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7900            ViewRootImpl viewRootImpl = getViewRootImpl();
7901            if (viewRootImpl != null) {
7902                viewRootImpl.setAccessibilityFocus(this, null);
7903            }
7904            invalidate();
7905            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7906            return true;
7907        }
7908        return false;
7909    }
7910
7911    /**
7912     * Call this to try to clear accessibility focus of this view.
7913     *
7914     * See also {@link #focusSearch(int)}, which is what you call to say that you
7915     * have focus, and you want your parent to look for the next one.
7916     *
7917     * @hide
7918     */
7919    public void clearAccessibilityFocus() {
7920        clearAccessibilityFocusNoCallbacks();
7921        // Clear the global reference of accessibility focus if this
7922        // view or any of its descendants had accessibility focus.
7923        ViewRootImpl viewRootImpl = getViewRootImpl();
7924        if (viewRootImpl != null) {
7925            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7926            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7927                viewRootImpl.setAccessibilityFocus(null, null);
7928            }
7929        }
7930    }
7931
7932    private void sendAccessibilityHoverEvent(int eventType) {
7933        // Since we are not delivering to a client accessibility events from not
7934        // important views (unless the clinet request that) we need to fire the
7935        // event from the deepest view exposed to the client. As a consequence if
7936        // the user crosses a not exposed view the client will see enter and exit
7937        // of the exposed predecessor followed by and enter and exit of that same
7938        // predecessor when entering and exiting the not exposed descendant. This
7939        // is fine since the client has a clear idea which view is hovered at the
7940        // price of a couple more events being sent. This is a simple and
7941        // working solution.
7942        View source = this;
7943        while (true) {
7944            if (source.includeForAccessibility()) {
7945                source.sendAccessibilityEvent(eventType);
7946                return;
7947            }
7948            ViewParent parent = source.getParent();
7949            if (parent instanceof View) {
7950                source = (View) parent;
7951            } else {
7952                return;
7953            }
7954        }
7955    }
7956
7957    /**
7958     * Clears accessibility focus without calling any callback methods
7959     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7960     * is used for clearing accessibility focus when giving this focus to
7961     * another view.
7962     */
7963    void clearAccessibilityFocusNoCallbacks() {
7964        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7965            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7966            invalidate();
7967            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7968        }
7969    }
7970
7971    /**
7972     * Call this to try to give focus to a specific view or to one of its
7973     * descendants.
7974     *
7975     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7976     * false), or if it is focusable and it is not focusable in touch mode
7977     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7978     *
7979     * See also {@link #focusSearch(int)}, which is what you call to say that you
7980     * have focus, and you want your parent to look for the next one.
7981     *
7982     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7983     * {@link #FOCUS_DOWN} and <code>null</code>.
7984     *
7985     * @return Whether this view or one of its descendants actually took focus.
7986     */
7987    public final boolean requestFocus() {
7988        return requestFocus(View.FOCUS_DOWN);
7989    }
7990
7991    /**
7992     * Call this to try to give focus to a specific view or to one of its
7993     * descendants and give it a hint about what direction focus is heading.
7994     *
7995     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7996     * false), or if it is focusable and it is not focusable in touch mode
7997     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7998     *
7999     * See also {@link #focusSearch(int)}, which is what you call to say that you
8000     * have focus, and you want your parent to look for the next one.
8001     *
8002     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8003     * <code>null</code> set for the previously focused rectangle.
8004     *
8005     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8006     * @return Whether this view or one of its descendants actually took focus.
8007     */
8008    public final boolean requestFocus(int direction) {
8009        return requestFocus(direction, null);
8010    }
8011
8012    /**
8013     * Call this to try to give focus to a specific view or to one of its descendants
8014     * and give it hints about the direction and a specific rectangle that the focus
8015     * is coming from.  The rectangle can help give larger views a finer grained hint
8016     * about where focus is coming from, and therefore, where to show selection, or
8017     * forward focus change internally.
8018     *
8019     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8020     * false), or if it is focusable and it is not focusable in touch mode
8021     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8022     *
8023     * A View will not take focus if it is not visible.
8024     *
8025     * A View will not take focus if one of its parents has
8026     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8027     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8028     *
8029     * See also {@link #focusSearch(int)}, which is what you call to say that you
8030     * have focus, and you want your parent to look for the next one.
8031     *
8032     * You may wish to override this method if your custom {@link View} has an internal
8033     * {@link View} that it wishes to forward the request to.
8034     *
8035     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8036     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8037     *        to give a finer grained hint about where focus is coming from.  May be null
8038     *        if there is no hint.
8039     * @return Whether this view or one of its descendants actually took focus.
8040     */
8041    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8042        return requestFocusNoSearch(direction, previouslyFocusedRect);
8043    }
8044
8045    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8046        // need to be focusable
8047        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
8048                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8049            return false;
8050        }
8051
8052        // need to be focusable in touch mode if in touch mode
8053        if (isInTouchMode() &&
8054            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
8055               return false;
8056        }
8057
8058        // need to not have any parents blocking us
8059        if (hasAncestorThatBlocksDescendantFocus()) {
8060            return false;
8061        }
8062
8063        handleFocusGainInternal(direction, previouslyFocusedRect);
8064        return true;
8065    }
8066
8067    /**
8068     * Call this to try to give focus to a specific view or to one of its descendants. This is a
8069     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
8070     * touch mode to request focus when they are touched.
8071     *
8072     * @return Whether this view or one of its descendants actually took focus.
8073     *
8074     * @see #isInTouchMode()
8075     *
8076     */
8077    public final boolean requestFocusFromTouch() {
8078        // Leave touch mode if we need to
8079        if (isInTouchMode()) {
8080            ViewRootImpl viewRoot = getViewRootImpl();
8081            if (viewRoot != null) {
8082                viewRoot.ensureTouchMode(false);
8083            }
8084        }
8085        return requestFocus(View.FOCUS_DOWN);
8086    }
8087
8088    /**
8089     * @return Whether any ancestor of this view blocks descendant focus.
8090     */
8091    private boolean hasAncestorThatBlocksDescendantFocus() {
8092        final boolean focusableInTouchMode = isFocusableInTouchMode();
8093        ViewParent ancestor = mParent;
8094        while (ancestor instanceof ViewGroup) {
8095            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8096            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8097                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8098                return true;
8099            } else {
8100                ancestor = vgAncestor.getParent();
8101            }
8102        }
8103        return false;
8104    }
8105
8106    /**
8107     * Gets the mode for determining whether this View is important for accessibility
8108     * which is if it fires accessibility events and if it is reported to
8109     * accessibility services that query the screen.
8110     *
8111     * @return The mode for determining whether a View is important for accessibility.
8112     *
8113     * @attr ref android.R.styleable#View_importantForAccessibility
8114     *
8115     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8116     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8117     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8118     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8119     */
8120    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8121            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8122            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8123            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8124            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8125                    to = "noHideDescendants")
8126        })
8127    public int getImportantForAccessibility() {
8128        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8129                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8130    }
8131
8132    /**
8133     * Sets the live region mode for this view. This indicates to accessibility
8134     * services whether they should automatically notify the user about changes
8135     * to the view's content description or text, or to the content descriptions
8136     * or text of the view's children (where applicable).
8137     * <p>
8138     * For example, in a login screen with a TextView that displays an "incorrect
8139     * password" notification, that view should be marked as a live region with
8140     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8141     * <p>
8142     * To disable change notifications for this view, use
8143     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8144     * mode for most views.
8145     * <p>
8146     * To indicate that the user should be notified of changes, use
8147     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8148     * <p>
8149     * If the view's changes should interrupt ongoing speech and notify the user
8150     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8151     *
8152     * @param mode The live region mode for this view, one of:
8153     *        <ul>
8154     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8155     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8156     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8157     *        </ul>
8158     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8159     */
8160    public void setAccessibilityLiveRegion(int mode) {
8161        if (mode != getAccessibilityLiveRegion()) {
8162            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8163            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8164                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8165            notifyViewAccessibilityStateChangedIfNeeded(
8166                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8167        }
8168    }
8169
8170    /**
8171     * Gets the live region mode for this View.
8172     *
8173     * @return The live region mode for the view.
8174     *
8175     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8176     *
8177     * @see #setAccessibilityLiveRegion(int)
8178     */
8179    public int getAccessibilityLiveRegion() {
8180        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8181                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8182    }
8183
8184    /**
8185     * Sets how to determine whether this view is important for accessibility
8186     * which is if it fires accessibility events and if it is reported to
8187     * accessibility services that query the screen.
8188     *
8189     * @param mode How to determine whether this view is important for accessibility.
8190     *
8191     * @attr ref android.R.styleable#View_importantForAccessibility
8192     *
8193     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8194     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8195     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8196     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8197     */
8198    public void setImportantForAccessibility(int mode) {
8199        final int oldMode = getImportantForAccessibility();
8200        if (mode != oldMode) {
8201            // If we're moving between AUTO and another state, we might not need
8202            // to send a subtree changed notification. We'll store the computed
8203            // importance, since we'll need to check it later to make sure.
8204            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8205                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8206            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8207            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8208            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8209                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8210            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8211                notifySubtreeAccessibilityStateChangedIfNeeded();
8212            } else {
8213                notifyViewAccessibilityStateChangedIfNeeded(
8214                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8215            }
8216        }
8217    }
8218
8219    /**
8220     * Computes whether this view should be exposed for accessibility. In
8221     * general, views that are interactive or provide information are exposed
8222     * while views that serve only as containers are hidden.
8223     * <p>
8224     * If an ancestor of this view has importance
8225     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8226     * returns <code>false</code>.
8227     * <p>
8228     * Otherwise, the value is computed according to the view's
8229     * {@link #getImportantForAccessibility()} value:
8230     * <ol>
8231     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8232     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8233     * </code>
8234     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8235     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8236     * view satisfies any of the following:
8237     * <ul>
8238     * <li>Is actionable, e.g. {@link #isClickable()},
8239     * {@link #isLongClickable()}, or {@link #isFocusable()}
8240     * <li>Has an {@link AccessibilityDelegate}
8241     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8242     * {@link OnKeyListener}, etc.
8243     * <li>Is an accessibility live region, e.g.
8244     * {@link #getAccessibilityLiveRegion()} is not
8245     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8246     * </ul>
8247     * </ol>
8248     *
8249     * @return Whether the view is exposed for accessibility.
8250     * @see #setImportantForAccessibility(int)
8251     * @see #getImportantForAccessibility()
8252     */
8253    public boolean isImportantForAccessibility() {
8254        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8255                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8256        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8257                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8258            return false;
8259        }
8260
8261        // Check parent mode to ensure we're not hidden.
8262        ViewParent parent = mParent;
8263        while (parent instanceof View) {
8264            if (((View) parent).getImportantForAccessibility()
8265                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8266                return false;
8267            }
8268            parent = parent.getParent();
8269        }
8270
8271        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8272                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8273                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8274    }
8275
8276    /**
8277     * Gets the parent for accessibility purposes. Note that the parent for
8278     * accessibility is not necessary the immediate parent. It is the first
8279     * predecessor that is important for accessibility.
8280     *
8281     * @return The parent for accessibility purposes.
8282     */
8283    public ViewParent getParentForAccessibility() {
8284        if (mParent instanceof View) {
8285            View parentView = (View) mParent;
8286            if (parentView.includeForAccessibility()) {
8287                return mParent;
8288            } else {
8289                return mParent.getParentForAccessibility();
8290            }
8291        }
8292        return null;
8293    }
8294
8295    /**
8296     * Adds the children of a given View for accessibility. Since some Views are
8297     * not important for accessibility the children for accessibility are not
8298     * necessarily direct children of the view, rather they are the first level of
8299     * descendants important for accessibility.
8300     *
8301     * @param children The list of children for accessibility.
8302     */
8303    public void addChildrenForAccessibility(ArrayList<View> children) {
8304
8305    }
8306
8307    /**
8308     * Whether to regard this view for accessibility. A view is regarded for
8309     * accessibility if it is important for accessibility or the querying
8310     * accessibility service has explicitly requested that view not
8311     * important for accessibility are regarded.
8312     *
8313     * @return Whether to regard the view for accessibility.
8314     *
8315     * @hide
8316     */
8317    public boolean includeForAccessibility() {
8318        if (mAttachInfo != null) {
8319            return (mAttachInfo.mAccessibilityFetchFlags
8320                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8321                    || isImportantForAccessibility();
8322        }
8323        return false;
8324    }
8325
8326    /**
8327     * Returns whether the View is considered actionable from
8328     * accessibility perspective. Such view are important for
8329     * accessibility.
8330     *
8331     * @return True if the view is actionable for accessibility.
8332     *
8333     * @hide
8334     */
8335    public boolean isActionableForAccessibility() {
8336        return (isClickable() || isLongClickable() || isFocusable());
8337    }
8338
8339    /**
8340     * Returns whether the View has registered callbacks which makes it
8341     * important for accessibility.
8342     *
8343     * @return True if the view is actionable for accessibility.
8344     */
8345    private boolean hasListenersForAccessibility() {
8346        ListenerInfo info = getListenerInfo();
8347        return mTouchDelegate != null || info.mOnKeyListener != null
8348                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8349                || info.mOnHoverListener != null || info.mOnDragListener != null;
8350    }
8351
8352    /**
8353     * Notifies that the accessibility state of this view changed. The change
8354     * is local to this view and does not represent structural changes such
8355     * as children and parent. For example, the view became focusable. The
8356     * notification is at at most once every
8357     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8358     * to avoid unnecessary load to the system. Also once a view has a pending
8359     * notification this method is a NOP until the notification has been sent.
8360     *
8361     * @hide
8362     */
8363    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8364        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8365            return;
8366        }
8367        if (mSendViewStateChangedAccessibilityEvent == null) {
8368            mSendViewStateChangedAccessibilityEvent =
8369                    new SendViewStateChangedAccessibilityEvent();
8370        }
8371        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8372    }
8373
8374    /**
8375     * Notifies that the accessibility state of this view changed. The change
8376     * is *not* local to this view and does represent structural changes such
8377     * as children and parent. For example, the view size changed. The
8378     * notification is at at most once every
8379     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8380     * to avoid unnecessary load to the system. Also once a view has a pending
8381     * notification this method is a NOP until the notification has been sent.
8382     *
8383     * @hide
8384     */
8385    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8386        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8387            return;
8388        }
8389        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8390            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8391            if (mParent != null) {
8392                try {
8393                    mParent.notifySubtreeAccessibilityStateChanged(
8394                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8395                } catch (AbstractMethodError e) {
8396                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8397                            " does not fully implement ViewParent", e);
8398                }
8399            }
8400        }
8401    }
8402
8403    /**
8404     * Reset the flag indicating the accessibility state of the subtree rooted
8405     * at this view changed.
8406     */
8407    void resetSubtreeAccessibilityStateChanged() {
8408        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8409    }
8410
8411    /**
8412     * Report an accessibility action to this view's parents for delegated processing.
8413     *
8414     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8415     * call this method to delegate an accessibility action to a supporting parent. If the parent
8416     * returns true from its
8417     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8418     * method this method will return true to signify that the action was consumed.</p>
8419     *
8420     * <p>This method is useful for implementing nested scrolling child views. If
8421     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8422     * a custom view implementation may invoke this method to allow a parent to consume the
8423     * scroll first. If this method returns true the custom view should skip its own scrolling
8424     * behavior.</p>
8425     *
8426     * @param action Accessibility action to delegate
8427     * @param arguments Optional action arguments
8428     * @return true if the action was consumed by a parent
8429     */
8430    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8431        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8432            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8433                return true;
8434            }
8435        }
8436        return false;
8437    }
8438
8439    /**
8440     * Performs the specified accessibility action on the view. For
8441     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8442     * <p>
8443     * If an {@link AccessibilityDelegate} has been specified via calling
8444     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8445     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8446     * is responsible for handling this call.
8447     * </p>
8448     *
8449     * <p>The default implementation will delegate
8450     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8451     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8452     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8453     *
8454     * @param action The action to perform.
8455     * @param arguments Optional action arguments.
8456     * @return Whether the action was performed.
8457     */
8458    public boolean performAccessibilityAction(int action, Bundle arguments) {
8459      if (mAccessibilityDelegate != null) {
8460          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8461      } else {
8462          return performAccessibilityActionInternal(action, arguments);
8463      }
8464    }
8465
8466   /**
8467    * @see #performAccessibilityAction(int, Bundle)
8468    *
8469    * Note: Called from the default {@link AccessibilityDelegate}.
8470    *
8471    * @hide
8472    */
8473    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8474        if (isNestedScrollingEnabled()
8475                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8476                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
8477            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8478                return true;
8479            }
8480        }
8481
8482        switch (action) {
8483            case AccessibilityNodeInfo.ACTION_CLICK: {
8484                if (isClickable()) {
8485                    performClick();
8486                    return true;
8487                }
8488            } break;
8489            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8490                if (isLongClickable()) {
8491                    performLongClick();
8492                    return true;
8493                }
8494            } break;
8495            case AccessibilityNodeInfo.ACTION_FOCUS: {
8496                if (!hasFocus()) {
8497                    // Get out of touch mode since accessibility
8498                    // wants to move focus around.
8499                    getViewRootImpl().ensureTouchMode(false);
8500                    return requestFocus();
8501                }
8502            } break;
8503            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8504                if (hasFocus()) {
8505                    clearFocus();
8506                    return !isFocused();
8507                }
8508            } break;
8509            case AccessibilityNodeInfo.ACTION_SELECT: {
8510                if (!isSelected()) {
8511                    setSelected(true);
8512                    return isSelected();
8513                }
8514            } break;
8515            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8516                if (isSelected()) {
8517                    setSelected(false);
8518                    return !isSelected();
8519                }
8520            } break;
8521            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8522                if (!isAccessibilityFocused()) {
8523                    return requestAccessibilityFocus();
8524                }
8525            } break;
8526            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8527                if (isAccessibilityFocused()) {
8528                    clearAccessibilityFocus();
8529                    return true;
8530                }
8531            } break;
8532            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8533                if (arguments != null) {
8534                    final int granularity = arguments.getInt(
8535                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8536                    final boolean extendSelection = arguments.getBoolean(
8537                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8538                    return traverseAtGranularity(granularity, true, extendSelection);
8539                }
8540            } break;
8541            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8542                if (arguments != null) {
8543                    final int granularity = arguments.getInt(
8544                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8545                    final boolean extendSelection = arguments.getBoolean(
8546                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8547                    return traverseAtGranularity(granularity, false, extendSelection);
8548                }
8549            } break;
8550            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8551                CharSequence text = getIterableTextForAccessibility();
8552                if (text == null) {
8553                    return false;
8554                }
8555                final int start = (arguments != null) ? arguments.getInt(
8556                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8557                final int end = (arguments != null) ? arguments.getInt(
8558                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8559                // Only cursor position can be specified (selection length == 0)
8560                if ((getAccessibilitySelectionStart() != start
8561                        || getAccessibilitySelectionEnd() != end)
8562                        && (start == end)) {
8563                    setAccessibilitySelection(start, end);
8564                    notifyViewAccessibilityStateChangedIfNeeded(
8565                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8566                    return true;
8567                }
8568            } break;
8569            case R.id.accessibilityActionShowOnScreen: {
8570                if (mAttachInfo != null) {
8571                    final Rect r = mAttachInfo.mTmpInvalRect;
8572                    getDrawingRect(r);
8573                    return requestRectangleOnScreen(r, true);
8574                }
8575            } break;
8576        }
8577        return false;
8578    }
8579
8580    private boolean traverseAtGranularity(int granularity, boolean forward,
8581            boolean extendSelection) {
8582        CharSequence text = getIterableTextForAccessibility();
8583        if (text == null || text.length() == 0) {
8584            return false;
8585        }
8586        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8587        if (iterator == null) {
8588            return false;
8589        }
8590        int current = getAccessibilitySelectionEnd();
8591        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8592            current = forward ? 0 : text.length();
8593        }
8594        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8595        if (range == null) {
8596            return false;
8597        }
8598        final int segmentStart = range[0];
8599        final int segmentEnd = range[1];
8600        int selectionStart;
8601        int selectionEnd;
8602        if (extendSelection && isAccessibilitySelectionExtendable()) {
8603            selectionStart = getAccessibilitySelectionStart();
8604            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8605                selectionStart = forward ? segmentStart : segmentEnd;
8606            }
8607            selectionEnd = forward ? segmentEnd : segmentStart;
8608        } else {
8609            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8610        }
8611        setAccessibilitySelection(selectionStart, selectionEnd);
8612        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8613                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8614        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8615        return true;
8616    }
8617
8618    /**
8619     * Gets the text reported for accessibility purposes.
8620     *
8621     * @return The accessibility text.
8622     *
8623     * @hide
8624     */
8625    public CharSequence getIterableTextForAccessibility() {
8626        return getContentDescription();
8627    }
8628
8629    /**
8630     * Gets whether accessibility selection can be extended.
8631     *
8632     * @return If selection is extensible.
8633     *
8634     * @hide
8635     */
8636    public boolean isAccessibilitySelectionExtendable() {
8637        return false;
8638    }
8639
8640    /**
8641     * @hide
8642     */
8643    public int getAccessibilitySelectionStart() {
8644        return mAccessibilityCursorPosition;
8645    }
8646
8647    /**
8648     * @hide
8649     */
8650    public int getAccessibilitySelectionEnd() {
8651        return getAccessibilitySelectionStart();
8652    }
8653
8654    /**
8655     * @hide
8656     */
8657    public void setAccessibilitySelection(int start, int end) {
8658        if (start ==  end && end == mAccessibilityCursorPosition) {
8659            return;
8660        }
8661        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8662            mAccessibilityCursorPosition = start;
8663        } else {
8664            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8665        }
8666        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8667    }
8668
8669    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8670            int fromIndex, int toIndex) {
8671        if (mParent == null) {
8672            return;
8673        }
8674        AccessibilityEvent event = AccessibilityEvent.obtain(
8675                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8676        onInitializeAccessibilityEvent(event);
8677        onPopulateAccessibilityEvent(event);
8678        event.setFromIndex(fromIndex);
8679        event.setToIndex(toIndex);
8680        event.setAction(action);
8681        event.setMovementGranularity(granularity);
8682        mParent.requestSendAccessibilityEvent(this, event);
8683    }
8684
8685    /**
8686     * @hide
8687     */
8688    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8689        switch (granularity) {
8690            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8691                CharSequence text = getIterableTextForAccessibility();
8692                if (text != null && text.length() > 0) {
8693                    CharacterTextSegmentIterator iterator =
8694                        CharacterTextSegmentIterator.getInstance(
8695                                mContext.getResources().getConfiguration().locale);
8696                    iterator.initialize(text.toString());
8697                    return iterator;
8698                }
8699            } break;
8700            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8701                CharSequence text = getIterableTextForAccessibility();
8702                if (text != null && text.length() > 0) {
8703                    WordTextSegmentIterator iterator =
8704                        WordTextSegmentIterator.getInstance(
8705                                mContext.getResources().getConfiguration().locale);
8706                    iterator.initialize(text.toString());
8707                    return iterator;
8708                }
8709            } break;
8710            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8711                CharSequence text = getIterableTextForAccessibility();
8712                if (text != null && text.length() > 0) {
8713                    ParagraphTextSegmentIterator iterator =
8714                        ParagraphTextSegmentIterator.getInstance();
8715                    iterator.initialize(text.toString());
8716                    return iterator;
8717                }
8718            } break;
8719        }
8720        return null;
8721    }
8722
8723    /**
8724     * @hide
8725     */
8726    public void dispatchStartTemporaryDetach() {
8727        onStartTemporaryDetach();
8728    }
8729
8730    /**
8731     * This is called when a container is going to temporarily detach a child, with
8732     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8733     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8734     * {@link #onDetachedFromWindow()} when the container is done.
8735     */
8736    public void onStartTemporaryDetach() {
8737        removeUnsetPressCallback();
8738        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8739    }
8740
8741    /**
8742     * @hide
8743     */
8744    public void dispatchFinishTemporaryDetach() {
8745        onFinishTemporaryDetach();
8746    }
8747
8748    /**
8749     * Called after {@link #onStartTemporaryDetach} when the container is done
8750     * changing the view.
8751     */
8752    public void onFinishTemporaryDetach() {
8753    }
8754
8755    /**
8756     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8757     * for this view's window.  Returns null if the view is not currently attached
8758     * to the window.  Normally you will not need to use this directly, but
8759     * just use the standard high-level event callbacks like
8760     * {@link #onKeyDown(int, KeyEvent)}.
8761     */
8762    public KeyEvent.DispatcherState getKeyDispatcherState() {
8763        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8764    }
8765
8766    /**
8767     * Dispatch a key event before it is processed by any input method
8768     * associated with the view hierarchy.  This can be used to intercept
8769     * key events in special situations before the IME consumes them; a
8770     * typical example would be handling the BACK key to update the application's
8771     * UI instead of allowing the IME to see it and close itself.
8772     *
8773     * @param event The key event to be dispatched.
8774     * @return True if the event was handled, false otherwise.
8775     */
8776    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8777        return onKeyPreIme(event.getKeyCode(), event);
8778    }
8779
8780    /**
8781     * Dispatch a key event to the next view on the focus path. This path runs
8782     * from the top of the view tree down to the currently focused view. If this
8783     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8784     * the next node down the focus path. This method also fires any key
8785     * listeners.
8786     *
8787     * @param event The key event to be dispatched.
8788     * @return True if the event was handled, false otherwise.
8789     */
8790    public boolean dispatchKeyEvent(KeyEvent event) {
8791        if (mInputEventConsistencyVerifier != null) {
8792            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8793        }
8794
8795        // Give any attached key listener a first crack at the event.
8796        //noinspection SimplifiableIfStatement
8797        ListenerInfo li = mListenerInfo;
8798        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8799                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8800            return true;
8801        }
8802
8803        if (event.dispatch(this, mAttachInfo != null
8804                ? mAttachInfo.mKeyDispatchState : null, this)) {
8805            return true;
8806        }
8807
8808        if (mInputEventConsistencyVerifier != null) {
8809            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8810        }
8811        return false;
8812    }
8813
8814    /**
8815     * Dispatches a key shortcut event.
8816     *
8817     * @param event The key event to be dispatched.
8818     * @return True if the event was handled by the view, false otherwise.
8819     */
8820    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8821        return onKeyShortcut(event.getKeyCode(), event);
8822    }
8823
8824    /**
8825     * Pass the touch screen motion event down to the target view, or this
8826     * view if it is the target.
8827     *
8828     * @param event The motion event to be dispatched.
8829     * @return True if the event was handled by the view, false otherwise.
8830     */
8831    public boolean dispatchTouchEvent(MotionEvent event) {
8832        // If the event should be handled by accessibility focus first.
8833        if (event.isTargetAccessibilityFocus()) {
8834            // We don't have focus or no virtual descendant has it, do not handle the event.
8835            if (!isAccessibilityFocusedViewOrHost()) {
8836                return false;
8837            }
8838            // We have focus and got the event, then use normal event dispatch.
8839            event.setTargetAccessibilityFocus(false);
8840        }
8841
8842        boolean result = false;
8843
8844        if (mInputEventConsistencyVerifier != null) {
8845            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8846        }
8847
8848        final int actionMasked = event.getActionMasked();
8849        if (actionMasked == MotionEvent.ACTION_DOWN) {
8850            // Defensive cleanup for new gesture
8851            stopNestedScroll();
8852        }
8853
8854        if (onFilterTouchEventForSecurity(event)) {
8855            //noinspection SimplifiableIfStatement
8856            ListenerInfo li = mListenerInfo;
8857            if (li != null && li.mOnTouchListener != null
8858                    && (mViewFlags & ENABLED_MASK) == ENABLED
8859                    && li.mOnTouchListener.onTouch(this, event)) {
8860                result = true;
8861            }
8862
8863            if (!result && onTouchEvent(event)) {
8864                result = true;
8865            }
8866        }
8867
8868        if (!result && mInputEventConsistencyVerifier != null) {
8869            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8870        }
8871
8872        // Clean up after nested scrolls if this is the end of a gesture;
8873        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8874        // of the gesture.
8875        if (actionMasked == MotionEvent.ACTION_UP ||
8876                actionMasked == MotionEvent.ACTION_CANCEL ||
8877                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8878            stopNestedScroll();
8879        }
8880
8881        return result;
8882    }
8883
8884    boolean isAccessibilityFocusedViewOrHost() {
8885        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
8886                .getAccessibilityFocusedHost() == this);
8887    }
8888
8889    /**
8890     * Filter the touch event to apply security policies.
8891     *
8892     * @param event The motion event to be filtered.
8893     * @return True if the event should be dispatched, false if the event should be dropped.
8894     *
8895     * @see #getFilterTouchesWhenObscured
8896     */
8897    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8898        //noinspection RedundantIfStatement
8899        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8900                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8901            // Window is obscured, drop this touch.
8902            return false;
8903        }
8904        return true;
8905    }
8906
8907    /**
8908     * Pass a trackball motion event down to the focused view.
8909     *
8910     * @param event The motion event to be dispatched.
8911     * @return True if the event was handled by the view, false otherwise.
8912     */
8913    public boolean dispatchTrackballEvent(MotionEvent event) {
8914        if (mInputEventConsistencyVerifier != null) {
8915            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8916        }
8917
8918        return onTrackballEvent(event);
8919    }
8920
8921    /**
8922     * Dispatch a generic motion event.
8923     * <p>
8924     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8925     * are delivered to the view under the pointer.  All other generic motion events are
8926     * delivered to the focused view.  Hover events are handled specially and are delivered
8927     * to {@link #onHoverEvent(MotionEvent)}.
8928     * </p>
8929     *
8930     * @param event The motion event to be dispatched.
8931     * @return True if the event was handled by the view, false otherwise.
8932     */
8933    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8934        if (mInputEventConsistencyVerifier != null) {
8935            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8936        }
8937
8938        final int source = event.getSource();
8939        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8940            final int action = event.getAction();
8941            if (action == MotionEvent.ACTION_HOVER_ENTER
8942                    || action == MotionEvent.ACTION_HOVER_MOVE
8943                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8944                if (dispatchHoverEvent(event)) {
8945                    return true;
8946                }
8947            } else if (dispatchGenericPointerEvent(event)) {
8948                return true;
8949            }
8950        } else if (dispatchGenericFocusedEvent(event)) {
8951            return true;
8952        }
8953
8954        if (dispatchGenericMotionEventInternal(event)) {
8955            return true;
8956        }
8957
8958        if (mInputEventConsistencyVerifier != null) {
8959            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8960        }
8961        return false;
8962    }
8963
8964    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8965        //noinspection SimplifiableIfStatement
8966        ListenerInfo li = mListenerInfo;
8967        if (li != null && li.mOnGenericMotionListener != null
8968                && (mViewFlags & ENABLED_MASK) == ENABLED
8969                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8970            return true;
8971        }
8972
8973        if (onGenericMotionEvent(event)) {
8974            return true;
8975        }
8976
8977        if (mInputEventConsistencyVerifier != null) {
8978            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8979        }
8980        return false;
8981    }
8982
8983    /**
8984     * Dispatch a hover event.
8985     * <p>
8986     * Do not call this method directly.
8987     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8988     * </p>
8989     *
8990     * @param event The motion event to be dispatched.
8991     * @return True if the event was handled by the view, false otherwise.
8992     */
8993    protected boolean dispatchHoverEvent(MotionEvent event) {
8994        ListenerInfo li = mListenerInfo;
8995        //noinspection SimplifiableIfStatement
8996        if (li != null && li.mOnHoverListener != null
8997                && (mViewFlags & ENABLED_MASK) == ENABLED
8998                && li.mOnHoverListener.onHover(this, event)) {
8999            return true;
9000        }
9001
9002        return onHoverEvent(event);
9003    }
9004
9005    /**
9006     * Returns true if the view has a child to which it has recently sent
9007     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
9008     * it does not have a hovered child, then it must be the innermost hovered view.
9009     * @hide
9010     */
9011    protected boolean hasHoveredChild() {
9012        return false;
9013    }
9014
9015    /**
9016     * Dispatch a generic motion event to the view under the first pointer.
9017     * <p>
9018     * Do not call this method directly.
9019     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9020     * </p>
9021     *
9022     * @param event The motion event to be dispatched.
9023     * @return True if the event was handled by the view, false otherwise.
9024     */
9025    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
9026        return false;
9027    }
9028
9029    /**
9030     * Dispatch a generic motion event to the currently focused view.
9031     * <p>
9032     * Do not call this method directly.
9033     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9034     * </p>
9035     *
9036     * @param event The motion event to be dispatched.
9037     * @return True if the event was handled by the view, false otherwise.
9038     */
9039    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
9040        return false;
9041    }
9042
9043    /**
9044     * Dispatch a pointer event.
9045     * <p>
9046     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
9047     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
9048     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
9049     * and should not be expected to handle other pointing device features.
9050     * </p>
9051     *
9052     * @param event The motion event to be dispatched.
9053     * @return True if the event was handled by the view, false otherwise.
9054     * @hide
9055     */
9056    public final boolean dispatchPointerEvent(MotionEvent event) {
9057        if (event.isTouchEvent()) {
9058            return dispatchTouchEvent(event);
9059        } else {
9060            return dispatchGenericMotionEvent(event);
9061        }
9062    }
9063
9064    /**
9065     * Called when the window containing this view gains or loses window focus.
9066     * ViewGroups should override to route to their children.
9067     *
9068     * @param hasFocus True if the window containing this view now has focus,
9069     *        false otherwise.
9070     */
9071    public void dispatchWindowFocusChanged(boolean hasFocus) {
9072        onWindowFocusChanged(hasFocus);
9073    }
9074
9075    /**
9076     * Called when the window containing this view gains or loses focus.  Note
9077     * that this is separate from view focus: to receive key events, both
9078     * your view and its window must have focus.  If a window is displayed
9079     * on top of yours that takes input focus, then your own window will lose
9080     * focus but the view focus will remain unchanged.
9081     *
9082     * @param hasWindowFocus True if the window containing this view now has
9083     *        focus, false otherwise.
9084     */
9085    public void onWindowFocusChanged(boolean hasWindowFocus) {
9086        InputMethodManager imm = InputMethodManager.peekInstance();
9087        if (!hasWindowFocus) {
9088            if (isPressed()) {
9089                setPressed(false);
9090            }
9091            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9092                imm.focusOut(this);
9093            }
9094            removeLongPressCallback();
9095            removeTapCallback();
9096            onFocusLost();
9097        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9098            imm.focusIn(this);
9099        }
9100        refreshDrawableState();
9101    }
9102
9103    /**
9104     * Returns true if this view is in a window that currently has window focus.
9105     * Note that this is not the same as the view itself having focus.
9106     *
9107     * @return True if this view is in a window that currently has window focus.
9108     */
9109    public boolean hasWindowFocus() {
9110        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9111    }
9112
9113    /**
9114     * Dispatch a view visibility change down the view hierarchy.
9115     * ViewGroups should override to route to their children.
9116     * @param changedView The view whose visibility changed. Could be 'this' or
9117     * an ancestor view.
9118     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9119     * {@link #INVISIBLE} or {@link #GONE}.
9120     */
9121    protected void dispatchVisibilityChanged(@NonNull View changedView,
9122            @Visibility int visibility) {
9123        onVisibilityChanged(changedView, visibility);
9124    }
9125
9126    /**
9127     * Called when the visibility of the view or an ancestor of the view has
9128     * changed.
9129     *
9130     * @param changedView The view whose visibility changed. May be
9131     *                    {@code this} or an ancestor view.
9132     * @param visibility The new visibility, one of {@link #VISIBLE},
9133     *                   {@link #INVISIBLE} or {@link #GONE}.
9134     */
9135    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9136        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9137        if (visible) {
9138            if (mAttachInfo != null) {
9139                initialAwakenScrollBars();
9140            } else {
9141                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
9142            }
9143        }
9144
9145        final Drawable dr = mBackground;
9146        if (dr != null && visible != dr.isVisible()) {
9147            dr.setVisible(visible, false);
9148        }
9149        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9150        if (fg != null && visible != fg.isVisible()) {
9151            fg.setVisible(visible, false);
9152        }
9153    }
9154
9155    /**
9156     * Dispatch a hint about whether this view is displayed. For instance, when
9157     * a View moves out of the screen, it might receives a display hint indicating
9158     * the view is not displayed. Applications should not <em>rely</em> on this hint
9159     * as there is no guarantee that they will receive one.
9160     *
9161     * @param hint A hint about whether or not this view is displayed:
9162     * {@link #VISIBLE} or {@link #INVISIBLE}.
9163     */
9164    public void dispatchDisplayHint(@Visibility int hint) {
9165        onDisplayHint(hint);
9166    }
9167
9168    /**
9169     * Gives this view a hint about whether is displayed or not. For instance, when
9170     * a View moves out of the screen, it might receives a display hint indicating
9171     * the view is not displayed. Applications should not <em>rely</em> on this hint
9172     * as there is no guarantee that they will receive one.
9173     *
9174     * @param hint A hint about whether or not this view is displayed:
9175     * {@link #VISIBLE} or {@link #INVISIBLE}.
9176     */
9177    protected void onDisplayHint(@Visibility int hint) {
9178    }
9179
9180    /**
9181     * Dispatch a window visibility change down the view hierarchy.
9182     * ViewGroups should override to route to their children.
9183     *
9184     * @param visibility The new visibility of the window.
9185     *
9186     * @see #onWindowVisibilityChanged(int)
9187     */
9188    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9189        onWindowVisibilityChanged(visibility);
9190    }
9191
9192    /**
9193     * Called when the window containing has change its visibility
9194     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9195     * that this tells you whether or not your window is being made visible
9196     * to the window manager; this does <em>not</em> tell you whether or not
9197     * your window is obscured by other windows on the screen, even if it
9198     * is itself visible.
9199     *
9200     * @param visibility The new visibility of the window.
9201     */
9202    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9203        if (visibility == VISIBLE) {
9204            initialAwakenScrollBars();
9205        }
9206    }
9207
9208    /**
9209     * Returns the current visibility of the window this view is attached to
9210     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9211     *
9212     * @return Returns the current visibility of the view's window.
9213     */
9214    @Visibility
9215    public int getWindowVisibility() {
9216        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9217    }
9218
9219    /**
9220     * Retrieve the overall visible display size in which the window this view is
9221     * attached to has been positioned in.  This takes into account screen
9222     * decorations above the window, for both cases where the window itself
9223     * is being position inside of them or the window is being placed under
9224     * then and covered insets are used for the window to position its content
9225     * inside.  In effect, this tells you the available area where content can
9226     * be placed and remain visible to users.
9227     *
9228     * <p>This function requires an IPC back to the window manager to retrieve
9229     * the requested information, so should not be used in performance critical
9230     * code like drawing.
9231     *
9232     * @param outRect Filled in with the visible display frame.  If the view
9233     * is not attached to a window, this is simply the raw display size.
9234     */
9235    public void getWindowVisibleDisplayFrame(Rect outRect) {
9236        if (mAttachInfo != null) {
9237            try {
9238                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9239            } catch (RemoteException e) {
9240                return;
9241            }
9242            // XXX This is really broken, and probably all needs to be done
9243            // in the window manager, and we need to know more about whether
9244            // we want the area behind or in front of the IME.
9245            final Rect insets = mAttachInfo.mVisibleInsets;
9246            outRect.left += insets.left;
9247            outRect.top += insets.top;
9248            outRect.right -= insets.right;
9249            outRect.bottom -= insets.bottom;
9250            return;
9251        }
9252        // The view is not attached to a display so we don't have a context.
9253        // Make a best guess about the display size.
9254        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9255        d.getRectSize(outRect);
9256    }
9257
9258    /**
9259     * Dispatch a notification about a resource configuration change down
9260     * the view hierarchy.
9261     * ViewGroups should override to route to their children.
9262     *
9263     * @param newConfig The new resource configuration.
9264     *
9265     * @see #onConfigurationChanged(android.content.res.Configuration)
9266     */
9267    public void dispatchConfigurationChanged(Configuration newConfig) {
9268        onConfigurationChanged(newConfig);
9269    }
9270
9271    /**
9272     * Called when the current configuration of the resources being used
9273     * by the application have changed.  You can use this to decide when
9274     * to reload resources that can changed based on orientation and other
9275     * configuration characteristics.  You only need to use this if you are
9276     * not relying on the normal {@link android.app.Activity} mechanism of
9277     * recreating the activity instance upon a configuration change.
9278     *
9279     * @param newConfig The new resource configuration.
9280     */
9281    protected void onConfigurationChanged(Configuration newConfig) {
9282    }
9283
9284    /**
9285     * Private function to aggregate all per-view attributes in to the view
9286     * root.
9287     */
9288    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9289        performCollectViewAttributes(attachInfo, visibility);
9290    }
9291
9292    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9293        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9294            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9295                attachInfo.mKeepScreenOn = true;
9296            }
9297            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9298            ListenerInfo li = mListenerInfo;
9299            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9300                attachInfo.mHasSystemUiListeners = true;
9301            }
9302        }
9303    }
9304
9305    void needGlobalAttributesUpdate(boolean force) {
9306        final AttachInfo ai = mAttachInfo;
9307        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9308            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9309                    || ai.mHasSystemUiListeners) {
9310                ai.mRecomputeGlobalAttributes = true;
9311            }
9312        }
9313    }
9314
9315    /**
9316     * Returns whether the device is currently in touch mode.  Touch mode is entered
9317     * once the user begins interacting with the device by touch, and affects various
9318     * things like whether focus is always visible to the user.
9319     *
9320     * @return Whether the device is in touch mode.
9321     */
9322    @ViewDebug.ExportedProperty
9323    public boolean isInTouchMode() {
9324        if (mAttachInfo != null) {
9325            return mAttachInfo.mInTouchMode;
9326        } else {
9327            return ViewRootImpl.isInTouchMode();
9328        }
9329    }
9330
9331    /**
9332     * Returns the context the view is running in, through which it can
9333     * access the current theme, resources, etc.
9334     *
9335     * @return The view's Context.
9336     */
9337    @ViewDebug.CapturedViewProperty
9338    public final Context getContext() {
9339        return mContext;
9340    }
9341
9342    /**
9343     * Handle a key event before it is processed by any input method
9344     * associated with the view hierarchy.  This can be used to intercept
9345     * key events in special situations before the IME consumes them; a
9346     * typical example would be handling the BACK key to update the application's
9347     * UI instead of allowing the IME to see it and close itself.
9348     *
9349     * @param keyCode The value in event.getKeyCode().
9350     * @param event Description of the key event.
9351     * @return If you handled the event, return true. If you want to allow the
9352     *         event to be handled by the next receiver, return false.
9353     */
9354    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9355        return false;
9356    }
9357
9358    /**
9359     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9360     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9361     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9362     * is released, if the view is enabled and clickable.
9363     *
9364     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9365     * although some may elect to do so in some situations. Do not rely on this to
9366     * catch software key presses.
9367     *
9368     * @param keyCode A key code that represents the button pressed, from
9369     *                {@link android.view.KeyEvent}.
9370     * @param event   The KeyEvent object that defines the button action.
9371     */
9372    public boolean onKeyDown(int keyCode, KeyEvent event) {
9373        boolean result = false;
9374
9375        if (KeyEvent.isConfirmKey(keyCode)) {
9376            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9377                return true;
9378            }
9379            // Long clickable items don't necessarily have to be clickable
9380            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9381                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9382                    (event.getRepeatCount() == 0)) {
9383                setPressed(true);
9384                checkForLongClick(0);
9385                return true;
9386            }
9387        }
9388        return result;
9389    }
9390
9391    /**
9392     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9393     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9394     * the event).
9395     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9396     * although some may elect to do so in some situations. Do not rely on this to
9397     * catch software key presses.
9398     */
9399    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9400        return false;
9401    }
9402
9403    /**
9404     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9405     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9406     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9407     * {@link KeyEvent#KEYCODE_ENTER} is released.
9408     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9409     * although some may elect to do so in some situations. Do not rely on this to
9410     * catch software key presses.
9411     *
9412     * @param keyCode A key code that represents the button pressed, from
9413     *                {@link android.view.KeyEvent}.
9414     * @param event   The KeyEvent object that defines the button action.
9415     */
9416    public boolean onKeyUp(int keyCode, KeyEvent event) {
9417        if (KeyEvent.isConfirmKey(keyCode)) {
9418            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9419                return true;
9420            }
9421            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9422                setPressed(false);
9423
9424                if (!mHasPerformedLongPress) {
9425                    // This is a tap, so remove the longpress check
9426                    removeLongPressCallback();
9427                    return performClick();
9428                }
9429            }
9430        }
9431        return false;
9432    }
9433
9434    /**
9435     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9436     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9437     * the event).
9438     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9439     * although some may elect to do so in some situations. Do not rely on this to
9440     * catch software key presses.
9441     *
9442     * @param keyCode     A key code that represents the button pressed, from
9443     *                    {@link android.view.KeyEvent}.
9444     * @param repeatCount The number of times the action was made.
9445     * @param event       The KeyEvent object that defines the button action.
9446     */
9447    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9448        return false;
9449    }
9450
9451    /**
9452     * Called on the focused view when a key shortcut event is not handled.
9453     * Override this method to implement local key shortcuts for the View.
9454     * Key shortcuts can also be implemented by setting the
9455     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9456     *
9457     * @param keyCode The value in event.getKeyCode().
9458     * @param event Description of the key event.
9459     * @return If you handled the event, return true. If you want to allow the
9460     *         event to be handled by the next receiver, return false.
9461     */
9462    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9463        return false;
9464    }
9465
9466    /**
9467     * Check whether the called view is a text editor, in which case it
9468     * would make sense to automatically display a soft input window for
9469     * it.  Subclasses should override this if they implement
9470     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9471     * a call on that method would return a non-null InputConnection, and
9472     * they are really a first-class editor that the user would normally
9473     * start typing on when the go into a window containing your view.
9474     *
9475     * <p>The default implementation always returns false.  This does
9476     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9477     * will not be called or the user can not otherwise perform edits on your
9478     * view; it is just a hint to the system that this is not the primary
9479     * purpose of this view.
9480     *
9481     * @return Returns true if this view is a text editor, else false.
9482     */
9483    public boolean onCheckIsTextEditor() {
9484        return false;
9485    }
9486
9487    /**
9488     * Create a new InputConnection for an InputMethod to interact
9489     * with the view.  The default implementation returns null, since it doesn't
9490     * support input methods.  You can override this to implement such support.
9491     * This is only needed for views that take focus and text input.
9492     *
9493     * <p>When implementing this, you probably also want to implement
9494     * {@link #onCheckIsTextEditor()} to indicate you will return a
9495     * non-null InputConnection.</p>
9496     *
9497     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9498     * object correctly and in its entirety, so that the connected IME can rely
9499     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9500     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9501     * must be filled in with the correct cursor position for IMEs to work correctly
9502     * with your application.</p>
9503     *
9504     * @param outAttrs Fill in with attribute information about the connection.
9505     */
9506    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9507        return null;
9508    }
9509
9510    /**
9511     * Called by the {@link android.view.inputmethod.InputMethodManager}
9512     * when a view who is not the current
9513     * input connection target is trying to make a call on the manager.  The
9514     * default implementation returns false; you can override this to return
9515     * true for certain views if you are performing InputConnection proxying
9516     * to them.
9517     * @param view The View that is making the InputMethodManager call.
9518     * @return Return true to allow the call, false to reject.
9519     */
9520    public boolean checkInputConnectionProxy(View view) {
9521        return false;
9522    }
9523
9524    /**
9525     * Show the context menu for this view. It is not safe to hold on to the
9526     * menu after returning from this method.
9527     *
9528     * You should normally not overload this method. Overload
9529     * {@link #onCreateContextMenu(ContextMenu)} or define an
9530     * {@link OnCreateContextMenuListener} to add items to the context menu.
9531     *
9532     * @param menu The context menu to populate
9533     */
9534    public void createContextMenu(ContextMenu menu) {
9535        ContextMenuInfo menuInfo = getContextMenuInfo();
9536
9537        // Sets the current menu info so all items added to menu will have
9538        // my extra info set.
9539        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9540
9541        onCreateContextMenu(menu);
9542        ListenerInfo li = mListenerInfo;
9543        if (li != null && li.mOnCreateContextMenuListener != null) {
9544            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9545        }
9546
9547        // Clear the extra information so subsequent items that aren't mine don't
9548        // have my extra info.
9549        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9550
9551        if (mParent != null) {
9552            mParent.createContextMenu(menu);
9553        }
9554    }
9555
9556    /**
9557     * Views should implement this if they have extra information to associate
9558     * with the context menu. The return result is supplied as a parameter to
9559     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9560     * callback.
9561     *
9562     * @return Extra information about the item for which the context menu
9563     *         should be shown. This information will vary across different
9564     *         subclasses of View.
9565     */
9566    protected ContextMenuInfo getContextMenuInfo() {
9567        return null;
9568    }
9569
9570    /**
9571     * Views should implement this if the view itself is going to add items to
9572     * the context menu.
9573     *
9574     * @param menu the context menu to populate
9575     */
9576    protected void onCreateContextMenu(ContextMenu menu) {
9577    }
9578
9579    /**
9580     * Implement this method to handle trackball motion events.  The
9581     * <em>relative</em> movement of the trackball since the last event
9582     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9583     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9584     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9585     * they will often be fractional values, representing the more fine-grained
9586     * movement information available from a trackball).
9587     *
9588     * @param event The motion event.
9589     * @return True if the event was handled, false otherwise.
9590     */
9591    public boolean onTrackballEvent(MotionEvent event) {
9592        return false;
9593    }
9594
9595    /**
9596     * Implement this method to handle generic motion events.
9597     * <p>
9598     * Generic motion events describe joystick movements, mouse hovers, track pad
9599     * touches, scroll wheel movements and other input events.  The
9600     * {@link MotionEvent#getSource() source} of the motion event specifies
9601     * the class of input that was received.  Implementations of this method
9602     * must examine the bits in the source before processing the event.
9603     * The following code example shows how this is done.
9604     * </p><p>
9605     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9606     * are delivered to the view under the pointer.  All other generic motion events are
9607     * delivered to the focused view.
9608     * </p>
9609     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9610     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9611     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9612     *             // process the joystick movement...
9613     *             return true;
9614     *         }
9615     *     }
9616     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9617     *         switch (event.getAction()) {
9618     *             case MotionEvent.ACTION_HOVER_MOVE:
9619     *                 // process the mouse hover movement...
9620     *                 return true;
9621     *             case MotionEvent.ACTION_SCROLL:
9622     *                 // process the scroll wheel movement...
9623     *                 return true;
9624     *         }
9625     *     }
9626     *     return super.onGenericMotionEvent(event);
9627     * }</pre>
9628     *
9629     * @param event The generic motion event being processed.
9630     * @return True if the event was handled, false otherwise.
9631     */
9632    public boolean onGenericMotionEvent(MotionEvent event) {
9633        return false;
9634    }
9635
9636    /**
9637     * Implement this method to handle hover events.
9638     * <p>
9639     * This method is called whenever a pointer is hovering into, over, or out of the
9640     * bounds of a view and the view is not currently being touched.
9641     * Hover events are represented as pointer events with action
9642     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9643     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9644     * </p>
9645     * <ul>
9646     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9647     * when the pointer enters the bounds of the view.</li>
9648     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9649     * when the pointer has already entered the bounds of the view and has moved.</li>
9650     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9651     * when the pointer has exited the bounds of the view or when the pointer is
9652     * about to go down due to a button click, tap, or similar user action that
9653     * causes the view to be touched.</li>
9654     * </ul>
9655     * <p>
9656     * The view should implement this method to return true to indicate that it is
9657     * handling the hover event, such as by changing its drawable state.
9658     * </p><p>
9659     * The default implementation calls {@link #setHovered} to update the hovered state
9660     * of the view when a hover enter or hover exit event is received, if the view
9661     * is enabled and is clickable.  The default implementation also sends hover
9662     * accessibility events.
9663     * </p>
9664     *
9665     * @param event The motion event that describes the hover.
9666     * @return True if the view handled the hover event.
9667     *
9668     * @see #isHovered
9669     * @see #setHovered
9670     * @see #onHoverChanged
9671     */
9672    public boolean onHoverEvent(MotionEvent event) {
9673        // The root view may receive hover (or touch) events that are outside the bounds of
9674        // the window.  This code ensures that we only send accessibility events for
9675        // hovers that are actually within the bounds of the root view.
9676        final int action = event.getActionMasked();
9677        if (!mSendingHoverAccessibilityEvents) {
9678            if ((action == MotionEvent.ACTION_HOVER_ENTER
9679                    || action == MotionEvent.ACTION_HOVER_MOVE)
9680                    && !hasHoveredChild()
9681                    && pointInView(event.getX(), event.getY())) {
9682                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9683                mSendingHoverAccessibilityEvents = true;
9684            }
9685        } else {
9686            if (action == MotionEvent.ACTION_HOVER_EXIT
9687                    || (action == MotionEvent.ACTION_MOVE
9688                            && !pointInView(event.getX(), event.getY()))) {
9689                mSendingHoverAccessibilityEvents = false;
9690                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9691            }
9692        }
9693
9694        if (isHoverable()) {
9695            switch (action) {
9696                case MotionEvent.ACTION_HOVER_ENTER:
9697                    setHovered(true);
9698                    break;
9699                case MotionEvent.ACTION_HOVER_EXIT:
9700                    setHovered(false);
9701                    break;
9702            }
9703
9704            // Dispatch the event to onGenericMotionEvent before returning true.
9705            // This is to provide compatibility with existing applications that
9706            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9707            // break because of the new default handling for hoverable views
9708            // in onHoverEvent.
9709            // Note that onGenericMotionEvent will be called by default when
9710            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9711            dispatchGenericMotionEventInternal(event);
9712            // The event was already handled by calling setHovered(), so always
9713            // return true.
9714            return true;
9715        }
9716
9717        return false;
9718    }
9719
9720    /**
9721     * Returns true if the view should handle {@link #onHoverEvent}
9722     * by calling {@link #setHovered} to change its hovered state.
9723     *
9724     * @return True if the view is hoverable.
9725     */
9726    private boolean isHoverable() {
9727        final int viewFlags = mViewFlags;
9728        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9729            return false;
9730        }
9731
9732        return (viewFlags & CLICKABLE) == CLICKABLE
9733                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9734    }
9735
9736    /**
9737     * Returns true if the view is currently hovered.
9738     *
9739     * @return True if the view is currently hovered.
9740     *
9741     * @see #setHovered
9742     * @see #onHoverChanged
9743     */
9744    @ViewDebug.ExportedProperty
9745    public boolean isHovered() {
9746        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9747    }
9748
9749    /**
9750     * Sets whether the view is currently hovered.
9751     * <p>
9752     * Calling this method also changes the drawable state of the view.  This
9753     * enables the view to react to hover by using different drawable resources
9754     * to change its appearance.
9755     * </p><p>
9756     * The {@link #onHoverChanged} method is called when the hovered state changes.
9757     * </p>
9758     *
9759     * @param hovered True if the view is hovered.
9760     *
9761     * @see #isHovered
9762     * @see #onHoverChanged
9763     */
9764    public void setHovered(boolean hovered) {
9765        if (hovered) {
9766            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9767                mPrivateFlags |= PFLAG_HOVERED;
9768                refreshDrawableState();
9769                onHoverChanged(true);
9770            }
9771        } else {
9772            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9773                mPrivateFlags &= ~PFLAG_HOVERED;
9774                refreshDrawableState();
9775                onHoverChanged(false);
9776            }
9777        }
9778    }
9779
9780    /**
9781     * Implement this method to handle hover state changes.
9782     * <p>
9783     * This method is called whenever the hover state changes as a result of a
9784     * call to {@link #setHovered}.
9785     * </p>
9786     *
9787     * @param hovered The current hover state, as returned by {@link #isHovered}.
9788     *
9789     * @see #isHovered
9790     * @see #setHovered
9791     */
9792    public void onHoverChanged(boolean hovered) {
9793    }
9794
9795    /**
9796     * Implement this method to handle touch screen motion events.
9797     * <p>
9798     * If this method is used to detect click actions, it is recommended that
9799     * the actions be performed by implementing and calling
9800     * {@link #performClick()}. This will ensure consistent system behavior,
9801     * including:
9802     * <ul>
9803     * <li>obeying click sound preferences
9804     * <li>dispatching OnClickListener calls
9805     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9806     * accessibility features are enabled
9807     * </ul>
9808     *
9809     * @param event The motion event.
9810     * @return True if the event was handled, false otherwise.
9811     */
9812    public boolean onTouchEvent(MotionEvent event) {
9813        final float x = event.getX();
9814        final float y = event.getY();
9815        final int viewFlags = mViewFlags;
9816
9817        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9818            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9819                setPressed(false);
9820            }
9821            // A disabled view that is clickable still consumes the touch
9822            // events, it just doesn't respond to them.
9823            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9824                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9825        }
9826
9827        if (mTouchDelegate != null) {
9828            if (mTouchDelegate.onTouchEvent(event)) {
9829                return true;
9830            }
9831        }
9832
9833        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9834                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9835            switch (event.getAction()) {
9836                case MotionEvent.ACTION_UP:
9837                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9838                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9839                        // take focus if we don't have it already and we should in
9840                        // touch mode.
9841                        boolean focusTaken = false;
9842                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9843                            focusTaken = requestFocus();
9844                        }
9845
9846                        if (prepressed) {
9847                            // The button is being released before we actually
9848                            // showed it as pressed.  Make it show the pressed
9849                            // state now (before scheduling the click) to ensure
9850                            // the user sees it.
9851                            setPressed(true, x, y);
9852                       }
9853
9854                        if (!mHasPerformedLongPress) {
9855                            // This is a tap, so remove the longpress check
9856                            removeLongPressCallback();
9857
9858                            // Only perform take click actions if we were in the pressed state
9859                            if (!focusTaken) {
9860                                // Use a Runnable and post this rather than calling
9861                                // performClick directly. This lets other visual state
9862                                // of the view update before click actions start.
9863                                if (mPerformClick == null) {
9864                                    mPerformClick = new PerformClick();
9865                                }
9866                                if (!post(mPerformClick)) {
9867                                    performClick();
9868                                }
9869                            }
9870                        }
9871
9872                        if (mUnsetPressedState == null) {
9873                            mUnsetPressedState = new UnsetPressedState();
9874                        }
9875
9876                        if (prepressed) {
9877                            postDelayed(mUnsetPressedState,
9878                                    ViewConfiguration.getPressedStateDuration());
9879                        } else if (!post(mUnsetPressedState)) {
9880                            // If the post failed, unpress right now
9881                            mUnsetPressedState.run();
9882                        }
9883
9884                        removeTapCallback();
9885                    }
9886                    break;
9887
9888                case MotionEvent.ACTION_DOWN:
9889                    mHasPerformedLongPress = false;
9890
9891                    if (performButtonActionOnTouchDown(event)) {
9892                        break;
9893                    }
9894
9895                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9896                    boolean isInScrollingContainer = isInScrollingContainer();
9897
9898                    // For views inside a scrolling container, delay the pressed feedback for
9899                    // a short period in case this is a scroll.
9900                    if (isInScrollingContainer) {
9901                        mPrivateFlags |= PFLAG_PREPRESSED;
9902                        if (mPendingCheckForTap == null) {
9903                            mPendingCheckForTap = new CheckForTap();
9904                        }
9905                        mPendingCheckForTap.x = event.getX();
9906                        mPendingCheckForTap.y = event.getY();
9907                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9908                    } else {
9909                        // Not inside a scrolling container, so show the feedback right away
9910                        setPressed(true, x, y);
9911                        checkForLongClick(0);
9912                    }
9913                    break;
9914
9915                case MotionEvent.ACTION_CANCEL:
9916                    setPressed(false);
9917                    removeTapCallback();
9918                    removeLongPressCallback();
9919                    break;
9920
9921                case MotionEvent.ACTION_MOVE:
9922                    drawableHotspotChanged(x, y);
9923
9924                    // Be lenient about moving outside of buttons
9925                    if (!pointInView(x, y, mTouchSlop)) {
9926                        // Outside button
9927                        removeTapCallback();
9928                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9929                            // Remove any future long press/tap checks
9930                            removeLongPressCallback();
9931
9932                            setPressed(false);
9933                        }
9934                    }
9935                    break;
9936            }
9937
9938            return true;
9939        }
9940
9941        return false;
9942    }
9943
9944    /**
9945     * @hide
9946     */
9947    public boolean isInScrollingContainer() {
9948        ViewParent p = getParent();
9949        while (p != null && p instanceof ViewGroup) {
9950            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9951                return true;
9952            }
9953            p = p.getParent();
9954        }
9955        return false;
9956    }
9957
9958    /**
9959     * Remove the longpress detection timer.
9960     */
9961    private void removeLongPressCallback() {
9962        if (mPendingCheckForLongPress != null) {
9963          removeCallbacks(mPendingCheckForLongPress);
9964        }
9965    }
9966
9967    /**
9968     * Remove the pending click action
9969     */
9970    private void removePerformClickCallback() {
9971        if (mPerformClick != null) {
9972            removeCallbacks(mPerformClick);
9973        }
9974    }
9975
9976    /**
9977     * Remove the prepress detection timer.
9978     */
9979    private void removeUnsetPressCallback() {
9980        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9981            setPressed(false);
9982            removeCallbacks(mUnsetPressedState);
9983        }
9984    }
9985
9986    /**
9987     * Remove the tap detection timer.
9988     */
9989    private void removeTapCallback() {
9990        if (mPendingCheckForTap != null) {
9991            mPrivateFlags &= ~PFLAG_PREPRESSED;
9992            removeCallbacks(mPendingCheckForTap);
9993        }
9994    }
9995
9996    /**
9997     * Cancels a pending long press.  Your subclass can use this if you
9998     * want the context menu to come up if the user presses and holds
9999     * at the same place, but you don't want it to come up if they press
10000     * and then move around enough to cause scrolling.
10001     */
10002    public void cancelLongPress() {
10003        removeLongPressCallback();
10004
10005        /*
10006         * The prepressed state handled by the tap callback is a display
10007         * construct, but the tap callback will post a long press callback
10008         * less its own timeout. Remove it here.
10009         */
10010        removeTapCallback();
10011    }
10012
10013    /**
10014     * Remove the pending callback for sending a
10015     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
10016     */
10017    private void removeSendViewScrolledAccessibilityEventCallback() {
10018        if (mSendViewScrolledAccessibilityEvent != null) {
10019            removeCallbacks(mSendViewScrolledAccessibilityEvent);
10020            mSendViewScrolledAccessibilityEvent.mIsPending = false;
10021        }
10022    }
10023
10024    /**
10025     * Sets the TouchDelegate for this View.
10026     */
10027    public void setTouchDelegate(TouchDelegate delegate) {
10028        mTouchDelegate = delegate;
10029    }
10030
10031    /**
10032     * Gets the TouchDelegate for this View.
10033     */
10034    public TouchDelegate getTouchDelegate() {
10035        return mTouchDelegate;
10036    }
10037
10038    /**
10039     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
10040     *
10041     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
10042     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
10043     * available. This method should only be called for touch events.
10044     *
10045     * <p class="note">This api is not intended for most applications. Buffered dispatch
10046     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
10047     * streams will not improve your input latency. Side effects include: increased latency,
10048     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
10049     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
10050     * you.</p>
10051     */
10052    public final void requestUnbufferedDispatch(MotionEvent event) {
10053        final int action = event.getAction();
10054        if (mAttachInfo == null
10055                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
10056                || !event.isTouchEvent()) {
10057            return;
10058        }
10059        mAttachInfo.mUnbufferedDispatchRequested = true;
10060    }
10061
10062    /**
10063     * Set flags controlling behavior of this view.
10064     *
10065     * @param flags Constant indicating the value which should be set
10066     * @param mask Constant indicating the bit range that should be changed
10067     */
10068    void setFlags(int flags, int mask) {
10069        final boolean accessibilityEnabled =
10070                AccessibilityManager.getInstance(mContext).isEnabled();
10071        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
10072
10073        int old = mViewFlags;
10074        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
10075
10076        int changed = mViewFlags ^ old;
10077        if (changed == 0) {
10078            return;
10079        }
10080        int privateFlags = mPrivateFlags;
10081
10082        /* Check if the FOCUSABLE bit has changed */
10083        if (((changed & FOCUSABLE_MASK) != 0) &&
10084                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
10085            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
10086                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
10087                /* Give up focus if we are no longer focusable */
10088                clearFocus();
10089            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10090                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10091                /*
10092                 * Tell the view system that we are now available to take focus
10093                 * if no one else already has it.
10094                 */
10095                if (mParent != null) mParent.focusableViewAvailable(this);
10096            }
10097        }
10098
10099        final int newVisibility = flags & VISIBILITY_MASK;
10100        if (newVisibility == VISIBLE) {
10101            if ((changed & VISIBILITY_MASK) != 0) {
10102                /*
10103                 * If this view is becoming visible, invalidate it in case it changed while
10104                 * it was not visible. Marking it drawn ensures that the invalidation will
10105                 * go through.
10106                 */
10107                mPrivateFlags |= PFLAG_DRAWN;
10108                invalidate(true);
10109
10110                needGlobalAttributesUpdate(true);
10111
10112                // a view becoming visible is worth notifying the parent
10113                // about in case nothing has focus.  even if this specific view
10114                // isn't focusable, it may contain something that is, so let
10115                // the root view try to give this focus if nothing else does.
10116                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10117                    mParent.focusableViewAvailable(this);
10118                }
10119            }
10120        }
10121
10122        /* Check if the GONE bit has changed */
10123        if ((changed & GONE) != 0) {
10124            needGlobalAttributesUpdate(false);
10125            requestLayout();
10126
10127            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10128                if (hasFocus()) clearFocus();
10129                clearAccessibilityFocus();
10130                destroyDrawingCache();
10131                if (mParent instanceof View) {
10132                    // GONE views noop invalidation, so invalidate the parent
10133                    ((View) mParent).invalidate(true);
10134                }
10135                // Mark the view drawn to ensure that it gets invalidated properly the next
10136                // time it is visible and gets invalidated
10137                mPrivateFlags |= PFLAG_DRAWN;
10138            }
10139            if (mAttachInfo != null) {
10140                mAttachInfo.mViewVisibilityChanged = true;
10141            }
10142        }
10143
10144        /* Check if the VISIBLE bit has changed */
10145        if ((changed & INVISIBLE) != 0) {
10146            needGlobalAttributesUpdate(false);
10147            /*
10148             * If this view is becoming invisible, set the DRAWN flag so that
10149             * the next invalidate() will not be skipped.
10150             */
10151            mPrivateFlags |= PFLAG_DRAWN;
10152
10153            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10154                // root view becoming invisible shouldn't clear focus and accessibility focus
10155                if (getRootView() != this) {
10156                    if (hasFocus()) clearFocus();
10157                    clearAccessibilityFocus();
10158                }
10159            }
10160            if (mAttachInfo != null) {
10161                mAttachInfo.mViewVisibilityChanged = true;
10162            }
10163        }
10164
10165        if ((changed & VISIBILITY_MASK) != 0) {
10166            // If the view is invisible, cleanup its display list to free up resources
10167            if (newVisibility != VISIBLE && mAttachInfo != null) {
10168                cleanupDraw();
10169            }
10170
10171            if (mParent instanceof ViewGroup) {
10172                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10173                        (changed & VISIBILITY_MASK), newVisibility);
10174                ((View) mParent).invalidate(true);
10175            } else if (mParent != null) {
10176                mParent.invalidateChild(this, null);
10177            }
10178            dispatchVisibilityChanged(this, newVisibility);
10179
10180            notifySubtreeAccessibilityStateChangedIfNeeded();
10181        }
10182
10183        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10184            destroyDrawingCache();
10185        }
10186
10187        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10188            destroyDrawingCache();
10189            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10190            invalidateParentCaches();
10191        }
10192
10193        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10194            destroyDrawingCache();
10195            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10196        }
10197
10198        if ((changed & DRAW_MASK) != 0) {
10199            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10200                if (mBackground != null) {
10201                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10202                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
10203                } else {
10204                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10205                }
10206            } else {
10207                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10208            }
10209            requestLayout();
10210            invalidate(true);
10211        }
10212
10213        if ((changed & KEEP_SCREEN_ON) != 0) {
10214            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10215                mParent.recomputeViewAttributes(this);
10216            }
10217        }
10218
10219        if (accessibilityEnabled) {
10220            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10221                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
10222                if (oldIncludeForAccessibility != includeForAccessibility()) {
10223                    notifySubtreeAccessibilityStateChangedIfNeeded();
10224                } else {
10225                    notifyViewAccessibilityStateChangedIfNeeded(
10226                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10227                }
10228            } else if ((changed & ENABLED_MASK) != 0) {
10229                notifyViewAccessibilityStateChangedIfNeeded(
10230                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10231            }
10232        }
10233    }
10234
10235    /**
10236     * Change the view's z order in the tree, so it's on top of other sibling
10237     * views. This ordering change may affect layout, if the parent container
10238     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10239     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10240     * method should be followed by calls to {@link #requestLayout()} and
10241     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10242     * with the new child ordering.
10243     *
10244     * @see ViewGroup#bringChildToFront(View)
10245     */
10246    public void bringToFront() {
10247        if (mParent != null) {
10248            mParent.bringChildToFront(this);
10249        }
10250    }
10251
10252    /**
10253     * This is called in response to an internal scroll in this view (i.e., the
10254     * view scrolled its own contents). This is typically as a result of
10255     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10256     * called.
10257     *
10258     * @param l Current horizontal scroll origin.
10259     * @param t Current vertical scroll origin.
10260     * @param oldl Previous horizontal scroll origin.
10261     * @param oldt Previous vertical scroll origin.
10262     */
10263    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10264        notifySubtreeAccessibilityStateChangedIfNeeded();
10265
10266        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10267            postSendViewScrolledAccessibilityEventCallback();
10268        }
10269
10270        mBackgroundSizeChanged = true;
10271        if (mForegroundInfo != null) {
10272            mForegroundInfo.mBoundsChanged = true;
10273        }
10274
10275        final AttachInfo ai = mAttachInfo;
10276        if (ai != null) {
10277            ai.mViewScrollChanged = true;
10278        }
10279
10280        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10281            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10282        }
10283    }
10284
10285    /**
10286     * Interface definition for a callback to be invoked when the scroll
10287     * X or Y positions of a view change.
10288     * <p>
10289     * <b>Note:</b> Some views handle scrolling independently from View and may
10290     * have their own separate listeners for scroll-type events. For example,
10291     * {@link android.widget.ListView ListView} allows clients to register an
10292     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10293     * to listen for changes in list scroll position.
10294     *
10295     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10296     */
10297    public interface OnScrollChangeListener {
10298        /**
10299         * Called when the scroll position of a view changes.
10300         *
10301         * @param v The view whose scroll position has changed.
10302         * @param scrollX Current horizontal scroll origin.
10303         * @param scrollY Current vertical scroll origin.
10304         * @param oldScrollX Previous horizontal scroll origin.
10305         * @param oldScrollY Previous vertical scroll origin.
10306         */
10307        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10308    }
10309
10310    /**
10311     * Interface definition for a callback to be invoked when the layout bounds of a view
10312     * changes due to layout processing.
10313     */
10314    public interface OnLayoutChangeListener {
10315        /**
10316         * Called when the layout bounds of a view changes due to layout processing.
10317         *
10318         * @param v The view whose bounds have changed.
10319         * @param left The new value of the view's left property.
10320         * @param top The new value of the view's top property.
10321         * @param right The new value of the view's right property.
10322         * @param bottom The new value of the view's bottom property.
10323         * @param oldLeft The previous value of the view's left property.
10324         * @param oldTop The previous value of the view's top property.
10325         * @param oldRight The previous value of the view's right property.
10326         * @param oldBottom The previous value of the view's bottom property.
10327         */
10328        void onLayoutChange(View v, int left, int top, int right, int bottom,
10329            int oldLeft, int oldTop, int oldRight, int oldBottom);
10330    }
10331
10332    /**
10333     * This is called during layout when the size of this view has changed. If
10334     * you were just added to the view hierarchy, you're called with the old
10335     * values of 0.
10336     *
10337     * @param w Current width of this view.
10338     * @param h Current height of this view.
10339     * @param oldw Old width of this view.
10340     * @param oldh Old height of this view.
10341     */
10342    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10343    }
10344
10345    /**
10346     * Called by draw to draw the child views. This may be overridden
10347     * by derived classes to gain control just before its children are drawn
10348     * (but after its own view has been drawn).
10349     * @param canvas the canvas on which to draw the view
10350     */
10351    protected void dispatchDraw(Canvas canvas) {
10352
10353    }
10354
10355    /**
10356     * Gets the parent of this view. Note that the parent is a
10357     * ViewParent and not necessarily a View.
10358     *
10359     * @return Parent of this view.
10360     */
10361    public final ViewParent getParent() {
10362        return mParent;
10363    }
10364
10365    /**
10366     * Set the horizontal scrolled position of your view. This will cause a call to
10367     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10368     * invalidated.
10369     * @param value the x position to scroll to
10370     */
10371    public void setScrollX(int value) {
10372        scrollTo(value, mScrollY);
10373    }
10374
10375    /**
10376     * Set the vertical scrolled position of your view. This will cause a call to
10377     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10378     * invalidated.
10379     * @param value the y position to scroll to
10380     */
10381    public void setScrollY(int value) {
10382        scrollTo(mScrollX, value);
10383    }
10384
10385    /**
10386     * Return the scrolled left position of this view. This is the left edge of
10387     * the displayed part of your view. You do not need to draw any pixels
10388     * farther left, since those are outside of the frame of your view on
10389     * screen.
10390     *
10391     * @return The left edge of the displayed part of your view, in pixels.
10392     */
10393    public final int getScrollX() {
10394        return mScrollX;
10395    }
10396
10397    /**
10398     * Return the scrolled top position of this view. This is the top edge of
10399     * the displayed part of your view. You do not need to draw any pixels above
10400     * it, since those are outside of the frame of your view on screen.
10401     *
10402     * @return The top edge of the displayed part of your view, in pixels.
10403     */
10404    public final int getScrollY() {
10405        return mScrollY;
10406    }
10407
10408    /**
10409     * Return the width of the your view.
10410     *
10411     * @return The width of your view, in pixels.
10412     */
10413    @ViewDebug.ExportedProperty(category = "layout")
10414    public final int getWidth() {
10415        return mRight - mLeft;
10416    }
10417
10418    /**
10419     * Return the height of your view.
10420     *
10421     * @return The height of your view, in pixels.
10422     */
10423    @ViewDebug.ExportedProperty(category = "layout")
10424    public final int getHeight() {
10425        return mBottom - mTop;
10426    }
10427
10428    /**
10429     * Return the visible drawing bounds of your view. Fills in the output
10430     * rectangle with the values from getScrollX(), getScrollY(),
10431     * getWidth(), and getHeight(). These bounds do not account for any
10432     * transformation properties currently set on the view, such as
10433     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10434     *
10435     * @param outRect The (scrolled) drawing bounds of the view.
10436     */
10437    public void getDrawingRect(Rect outRect) {
10438        outRect.left = mScrollX;
10439        outRect.top = mScrollY;
10440        outRect.right = mScrollX + (mRight - mLeft);
10441        outRect.bottom = mScrollY + (mBottom - mTop);
10442    }
10443
10444    /**
10445     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10446     * raw width component (that is the result is masked by
10447     * {@link #MEASURED_SIZE_MASK}).
10448     *
10449     * @return The raw measured width of this view.
10450     */
10451    public final int getMeasuredWidth() {
10452        return mMeasuredWidth & MEASURED_SIZE_MASK;
10453    }
10454
10455    /**
10456     * Return the full width measurement information for this view as computed
10457     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10458     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10459     * This should be used during measurement and layout calculations only. Use
10460     * {@link #getWidth()} to see how wide a view is after layout.
10461     *
10462     * @return The measured width of this view as a bit mask.
10463     */
10464    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10465            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10466                    name = "MEASURED_STATE_TOO_SMALL"),
10467    })
10468    public final int getMeasuredWidthAndState() {
10469        return mMeasuredWidth;
10470    }
10471
10472    /**
10473     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10474     * raw width component (that is the result is masked by
10475     * {@link #MEASURED_SIZE_MASK}).
10476     *
10477     * @return The raw measured height of this view.
10478     */
10479    public final int getMeasuredHeight() {
10480        return mMeasuredHeight & MEASURED_SIZE_MASK;
10481    }
10482
10483    /**
10484     * Return the full height measurement information for this view as computed
10485     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10486     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10487     * This should be used during measurement and layout calculations only. Use
10488     * {@link #getHeight()} to see how wide a view is after layout.
10489     *
10490     * @return The measured width of this view as a bit mask.
10491     */
10492    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10493            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10494                    name = "MEASURED_STATE_TOO_SMALL"),
10495    })
10496    public final int getMeasuredHeightAndState() {
10497        return mMeasuredHeight;
10498    }
10499
10500    /**
10501     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10502     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10503     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10504     * and the height component is at the shifted bits
10505     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10506     */
10507    public final int getMeasuredState() {
10508        return (mMeasuredWidth&MEASURED_STATE_MASK)
10509                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10510                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10511    }
10512
10513    /**
10514     * The transform matrix of this view, which is calculated based on the current
10515     * rotation, scale, and pivot properties.
10516     *
10517     * @see #getRotation()
10518     * @see #getScaleX()
10519     * @see #getScaleY()
10520     * @see #getPivotX()
10521     * @see #getPivotY()
10522     * @return The current transform matrix for the view
10523     */
10524    public Matrix getMatrix() {
10525        ensureTransformationInfo();
10526        final Matrix matrix = mTransformationInfo.mMatrix;
10527        mRenderNode.getMatrix(matrix);
10528        return matrix;
10529    }
10530
10531    /**
10532     * Returns true if the transform matrix is the identity matrix.
10533     * Recomputes the matrix if necessary.
10534     *
10535     * @return True if the transform matrix is the identity matrix, false otherwise.
10536     */
10537    final boolean hasIdentityMatrix() {
10538        return mRenderNode.hasIdentityMatrix();
10539    }
10540
10541    void ensureTransformationInfo() {
10542        if (mTransformationInfo == null) {
10543            mTransformationInfo = new TransformationInfo();
10544        }
10545    }
10546
10547   /**
10548     * Utility method to retrieve the inverse of the current mMatrix property.
10549     * We cache the matrix to avoid recalculating it when transform properties
10550     * have not changed.
10551     *
10552     * @return The inverse of the current matrix of this view.
10553     * @hide
10554     */
10555    public final Matrix getInverseMatrix() {
10556        ensureTransformationInfo();
10557        if (mTransformationInfo.mInverseMatrix == null) {
10558            mTransformationInfo.mInverseMatrix = new Matrix();
10559        }
10560        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10561        mRenderNode.getInverseMatrix(matrix);
10562        return matrix;
10563    }
10564
10565    /**
10566     * Gets the distance along the Z axis from the camera to this view.
10567     *
10568     * @see #setCameraDistance(float)
10569     *
10570     * @return The distance along the Z axis.
10571     */
10572    public float getCameraDistance() {
10573        final float dpi = mResources.getDisplayMetrics().densityDpi;
10574        return -(mRenderNode.getCameraDistance() * dpi);
10575    }
10576
10577    /**
10578     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10579     * views are drawn) from the camera to this view. The camera's distance
10580     * affects 3D transformations, for instance rotations around the X and Y
10581     * axis. If the rotationX or rotationY properties are changed and this view is
10582     * large (more than half the size of the screen), it is recommended to always
10583     * use a camera distance that's greater than the height (X axis rotation) or
10584     * the width (Y axis rotation) of this view.</p>
10585     *
10586     * <p>The distance of the camera from the view plane can have an affect on the
10587     * perspective distortion of the view when it is rotated around the x or y axis.
10588     * For example, a large distance will result in a large viewing angle, and there
10589     * will not be much perspective distortion of the view as it rotates. A short
10590     * distance may cause much more perspective distortion upon rotation, and can
10591     * also result in some drawing artifacts if the rotated view ends up partially
10592     * behind the camera (which is why the recommendation is to use a distance at
10593     * least as far as the size of the view, if the view is to be rotated.)</p>
10594     *
10595     * <p>The distance is expressed in "depth pixels." The default distance depends
10596     * on the screen density. For instance, on a medium density display, the
10597     * default distance is 1280. On a high density display, the default distance
10598     * is 1920.</p>
10599     *
10600     * <p>If you want to specify a distance that leads to visually consistent
10601     * results across various densities, use the following formula:</p>
10602     * <pre>
10603     * float scale = context.getResources().getDisplayMetrics().density;
10604     * view.setCameraDistance(distance * scale);
10605     * </pre>
10606     *
10607     * <p>The density scale factor of a high density display is 1.5,
10608     * and 1920 = 1280 * 1.5.</p>
10609     *
10610     * @param distance The distance in "depth pixels", if negative the opposite
10611     *        value is used
10612     *
10613     * @see #setRotationX(float)
10614     * @see #setRotationY(float)
10615     */
10616    public void setCameraDistance(float distance) {
10617        final float dpi = mResources.getDisplayMetrics().densityDpi;
10618
10619        invalidateViewProperty(true, false);
10620        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10621        invalidateViewProperty(false, false);
10622
10623        invalidateParentIfNeededAndWasQuickRejected();
10624    }
10625
10626    /**
10627     * The degrees that the view is rotated around the pivot point.
10628     *
10629     * @see #setRotation(float)
10630     * @see #getPivotX()
10631     * @see #getPivotY()
10632     *
10633     * @return The degrees of rotation.
10634     */
10635    @ViewDebug.ExportedProperty(category = "drawing")
10636    public float getRotation() {
10637        return mRenderNode.getRotation();
10638    }
10639
10640    /**
10641     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10642     * result in clockwise rotation.
10643     *
10644     * @param rotation The degrees of rotation.
10645     *
10646     * @see #getRotation()
10647     * @see #getPivotX()
10648     * @see #getPivotY()
10649     * @see #setRotationX(float)
10650     * @see #setRotationY(float)
10651     *
10652     * @attr ref android.R.styleable#View_rotation
10653     */
10654    public void setRotation(float rotation) {
10655        if (rotation != getRotation()) {
10656            // Double-invalidation is necessary to capture view's old and new areas
10657            invalidateViewProperty(true, false);
10658            mRenderNode.setRotation(rotation);
10659            invalidateViewProperty(false, true);
10660
10661            invalidateParentIfNeededAndWasQuickRejected();
10662            notifySubtreeAccessibilityStateChangedIfNeeded();
10663        }
10664    }
10665
10666    /**
10667     * The degrees that the view is rotated around the vertical axis through the pivot point.
10668     *
10669     * @see #getPivotX()
10670     * @see #getPivotY()
10671     * @see #setRotationY(float)
10672     *
10673     * @return The degrees of Y rotation.
10674     */
10675    @ViewDebug.ExportedProperty(category = "drawing")
10676    public float getRotationY() {
10677        return mRenderNode.getRotationY();
10678    }
10679
10680    /**
10681     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10682     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10683     * down the y axis.
10684     *
10685     * When rotating large views, it is recommended to adjust the camera distance
10686     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10687     *
10688     * @param rotationY The degrees of Y rotation.
10689     *
10690     * @see #getRotationY()
10691     * @see #getPivotX()
10692     * @see #getPivotY()
10693     * @see #setRotation(float)
10694     * @see #setRotationX(float)
10695     * @see #setCameraDistance(float)
10696     *
10697     * @attr ref android.R.styleable#View_rotationY
10698     */
10699    public void setRotationY(float rotationY) {
10700        if (rotationY != getRotationY()) {
10701            invalidateViewProperty(true, false);
10702            mRenderNode.setRotationY(rotationY);
10703            invalidateViewProperty(false, true);
10704
10705            invalidateParentIfNeededAndWasQuickRejected();
10706            notifySubtreeAccessibilityStateChangedIfNeeded();
10707        }
10708    }
10709
10710    /**
10711     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10712     *
10713     * @see #getPivotX()
10714     * @see #getPivotY()
10715     * @see #setRotationX(float)
10716     *
10717     * @return The degrees of X rotation.
10718     */
10719    @ViewDebug.ExportedProperty(category = "drawing")
10720    public float getRotationX() {
10721        return mRenderNode.getRotationX();
10722    }
10723
10724    /**
10725     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10726     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10727     * x axis.
10728     *
10729     * When rotating large views, it is recommended to adjust the camera distance
10730     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10731     *
10732     * @param rotationX The degrees of X rotation.
10733     *
10734     * @see #getRotationX()
10735     * @see #getPivotX()
10736     * @see #getPivotY()
10737     * @see #setRotation(float)
10738     * @see #setRotationY(float)
10739     * @see #setCameraDistance(float)
10740     *
10741     * @attr ref android.R.styleable#View_rotationX
10742     */
10743    public void setRotationX(float rotationX) {
10744        if (rotationX != getRotationX()) {
10745            invalidateViewProperty(true, false);
10746            mRenderNode.setRotationX(rotationX);
10747            invalidateViewProperty(false, true);
10748
10749            invalidateParentIfNeededAndWasQuickRejected();
10750            notifySubtreeAccessibilityStateChangedIfNeeded();
10751        }
10752    }
10753
10754    /**
10755     * The amount that the view is scaled in x around the pivot point, as a proportion of
10756     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10757     *
10758     * <p>By default, this is 1.0f.
10759     *
10760     * @see #getPivotX()
10761     * @see #getPivotY()
10762     * @return The scaling factor.
10763     */
10764    @ViewDebug.ExportedProperty(category = "drawing")
10765    public float getScaleX() {
10766        return mRenderNode.getScaleX();
10767    }
10768
10769    /**
10770     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10771     * the view's unscaled width. A value of 1 means that no scaling is applied.
10772     *
10773     * @param scaleX The scaling factor.
10774     * @see #getPivotX()
10775     * @see #getPivotY()
10776     *
10777     * @attr ref android.R.styleable#View_scaleX
10778     */
10779    public void setScaleX(float scaleX) {
10780        if (scaleX != getScaleX()) {
10781            invalidateViewProperty(true, false);
10782            mRenderNode.setScaleX(scaleX);
10783            invalidateViewProperty(false, true);
10784
10785            invalidateParentIfNeededAndWasQuickRejected();
10786            notifySubtreeAccessibilityStateChangedIfNeeded();
10787        }
10788    }
10789
10790    /**
10791     * The amount that the view is scaled in y around the pivot point, as a proportion of
10792     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10793     *
10794     * <p>By default, this is 1.0f.
10795     *
10796     * @see #getPivotX()
10797     * @see #getPivotY()
10798     * @return The scaling factor.
10799     */
10800    @ViewDebug.ExportedProperty(category = "drawing")
10801    public float getScaleY() {
10802        return mRenderNode.getScaleY();
10803    }
10804
10805    /**
10806     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10807     * the view's unscaled width. A value of 1 means that no scaling is applied.
10808     *
10809     * @param scaleY The scaling factor.
10810     * @see #getPivotX()
10811     * @see #getPivotY()
10812     *
10813     * @attr ref android.R.styleable#View_scaleY
10814     */
10815    public void setScaleY(float scaleY) {
10816        if (scaleY != getScaleY()) {
10817            invalidateViewProperty(true, false);
10818            mRenderNode.setScaleY(scaleY);
10819            invalidateViewProperty(false, true);
10820
10821            invalidateParentIfNeededAndWasQuickRejected();
10822            notifySubtreeAccessibilityStateChangedIfNeeded();
10823        }
10824    }
10825
10826    /**
10827     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10828     * and {@link #setScaleX(float) scaled}.
10829     *
10830     * @see #getRotation()
10831     * @see #getScaleX()
10832     * @see #getScaleY()
10833     * @see #getPivotY()
10834     * @return The x location of the pivot point.
10835     *
10836     * @attr ref android.R.styleable#View_transformPivotX
10837     */
10838    @ViewDebug.ExportedProperty(category = "drawing")
10839    public float getPivotX() {
10840        return mRenderNode.getPivotX();
10841    }
10842
10843    /**
10844     * Sets the x location of the point around which the view is
10845     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10846     * By default, the pivot point is centered on the object.
10847     * Setting this property disables this behavior and causes the view to use only the
10848     * explicitly set pivotX and pivotY values.
10849     *
10850     * @param pivotX The x location of the pivot point.
10851     * @see #getRotation()
10852     * @see #getScaleX()
10853     * @see #getScaleY()
10854     * @see #getPivotY()
10855     *
10856     * @attr ref android.R.styleable#View_transformPivotX
10857     */
10858    public void setPivotX(float pivotX) {
10859        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10860            invalidateViewProperty(true, false);
10861            mRenderNode.setPivotX(pivotX);
10862            invalidateViewProperty(false, true);
10863
10864            invalidateParentIfNeededAndWasQuickRejected();
10865        }
10866    }
10867
10868    /**
10869     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10870     * and {@link #setScaleY(float) scaled}.
10871     *
10872     * @see #getRotation()
10873     * @see #getScaleX()
10874     * @see #getScaleY()
10875     * @see #getPivotY()
10876     * @return The y location of the pivot point.
10877     *
10878     * @attr ref android.R.styleable#View_transformPivotY
10879     */
10880    @ViewDebug.ExportedProperty(category = "drawing")
10881    public float getPivotY() {
10882        return mRenderNode.getPivotY();
10883    }
10884
10885    /**
10886     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10887     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10888     * Setting this property disables this behavior and causes the view to use only the
10889     * explicitly set pivotX and pivotY values.
10890     *
10891     * @param pivotY The y location of the pivot point.
10892     * @see #getRotation()
10893     * @see #getScaleX()
10894     * @see #getScaleY()
10895     * @see #getPivotY()
10896     *
10897     * @attr ref android.R.styleable#View_transformPivotY
10898     */
10899    public void setPivotY(float pivotY) {
10900        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10901            invalidateViewProperty(true, false);
10902            mRenderNode.setPivotY(pivotY);
10903            invalidateViewProperty(false, true);
10904
10905            invalidateParentIfNeededAndWasQuickRejected();
10906        }
10907    }
10908
10909    /**
10910     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10911     * completely transparent and 1 means the view is completely opaque.
10912     *
10913     * <p>By default this is 1.0f.
10914     * @return The opacity of the view.
10915     */
10916    @ViewDebug.ExportedProperty(category = "drawing")
10917    public float getAlpha() {
10918        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10919    }
10920
10921    /**
10922     * Returns whether this View has content which overlaps.
10923     *
10924     * <p>This function, intended to be overridden by specific View types, is an optimization when
10925     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10926     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10927     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10928     * directly. An example of overlapping rendering is a TextView with a background image, such as
10929     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10930     * ImageView with only the foreground image. The default implementation returns true; subclasses
10931     * should override if they have cases which can be optimized.</p>
10932     *
10933     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10934     * necessitates that a View return true if it uses the methods internally without passing the
10935     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10936     *
10937     * @return true if the content in this view might overlap, false otherwise.
10938     */
10939    @ViewDebug.ExportedProperty(category = "drawing")
10940    public boolean hasOverlappingRendering() {
10941        return true;
10942    }
10943
10944    /**
10945     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10946     * completely transparent and 1 means the view is completely opaque.</p>
10947     *
10948     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10949     * performance implications, especially for large views. It is best to use the alpha property
10950     * sparingly and transiently, as in the case of fading animations.</p>
10951     *
10952     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10953     * strongly recommended for performance reasons to either override
10954     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10955     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10956     *
10957     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10958     * responsible for applying the opacity itself.</p>
10959     *
10960     * <p>Note that if the view is backed by a
10961     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10962     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10963     * 1.0 will supersede the alpha of the layer paint.</p>
10964     *
10965     * @param alpha The opacity of the view.
10966     *
10967     * @see #hasOverlappingRendering()
10968     * @see #setLayerType(int, android.graphics.Paint)
10969     *
10970     * @attr ref android.R.styleable#View_alpha
10971     */
10972    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
10973        ensureTransformationInfo();
10974        if (mTransformationInfo.mAlpha != alpha) {
10975            mTransformationInfo.mAlpha = alpha;
10976            if (onSetAlpha((int) (alpha * 255))) {
10977                mPrivateFlags |= PFLAG_ALPHA_SET;
10978                // subclass is handling alpha - don't optimize rendering cache invalidation
10979                invalidateParentCaches();
10980                invalidate(true);
10981            } else {
10982                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10983                invalidateViewProperty(true, false);
10984                mRenderNode.setAlpha(getFinalAlpha());
10985                notifyViewAccessibilityStateChangedIfNeeded(
10986                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10987            }
10988        }
10989    }
10990
10991    /**
10992     * Faster version of setAlpha() which performs the same steps except there are
10993     * no calls to invalidate(). The caller of this function should perform proper invalidation
10994     * on the parent and this object. The return value indicates whether the subclass handles
10995     * alpha (the return value for onSetAlpha()).
10996     *
10997     * @param alpha The new value for the alpha property
10998     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10999     *         the new value for the alpha property is different from the old value
11000     */
11001    boolean setAlphaNoInvalidation(float alpha) {
11002        ensureTransformationInfo();
11003        if (mTransformationInfo.mAlpha != alpha) {
11004            mTransformationInfo.mAlpha = alpha;
11005            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
11006            if (subclassHandlesAlpha) {
11007                mPrivateFlags |= PFLAG_ALPHA_SET;
11008                return true;
11009            } else {
11010                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11011                mRenderNode.setAlpha(getFinalAlpha());
11012            }
11013        }
11014        return false;
11015    }
11016
11017    /**
11018     * This property is hidden and intended only for use by the Fade transition, which
11019     * animates it to produce a visual translucency that does not side-effect (or get
11020     * affected by) the real alpha property. This value is composited with the other
11021     * alpha value (and the AlphaAnimation value, when that is present) to produce
11022     * a final visual translucency result, which is what is passed into the DisplayList.
11023     *
11024     * @hide
11025     */
11026    public void setTransitionAlpha(float alpha) {
11027        ensureTransformationInfo();
11028        if (mTransformationInfo.mTransitionAlpha != alpha) {
11029            mTransformationInfo.mTransitionAlpha = alpha;
11030            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11031            invalidateViewProperty(true, false);
11032            mRenderNode.setAlpha(getFinalAlpha());
11033        }
11034    }
11035
11036    /**
11037     * Calculates the visual alpha of this view, which is a combination of the actual
11038     * alpha value and the transitionAlpha value (if set).
11039     */
11040    private float getFinalAlpha() {
11041        if (mTransformationInfo != null) {
11042            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11043        }
11044        return 1;
11045    }
11046
11047    /**
11048     * This property is hidden and intended only for use by the Fade transition, which
11049     * animates it to produce a visual translucency that does not side-effect (or get
11050     * affected by) the real alpha property. This value is composited with the other
11051     * alpha value (and the AlphaAnimation value, when that is present) to produce
11052     * a final visual translucency result, which is what is passed into the DisplayList.
11053     *
11054     * @hide
11055     */
11056    @ViewDebug.ExportedProperty(category = "drawing")
11057    public float getTransitionAlpha() {
11058        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11059    }
11060
11061    /**
11062     * Top position of this view relative to its parent.
11063     *
11064     * @return The top of this view, in pixels.
11065     */
11066    @ViewDebug.CapturedViewProperty
11067    public final int getTop() {
11068        return mTop;
11069    }
11070
11071    /**
11072     * Sets the top position of this view relative to its parent. This method is meant to be called
11073     * by the layout system and should not generally be called otherwise, because the property
11074     * may be changed at any time by the layout.
11075     *
11076     * @param top The top of this view, in pixels.
11077     */
11078    public final void setTop(int top) {
11079        if (top != mTop) {
11080            final boolean matrixIsIdentity = hasIdentityMatrix();
11081            if (matrixIsIdentity) {
11082                if (mAttachInfo != null) {
11083                    int minTop;
11084                    int yLoc;
11085                    if (top < mTop) {
11086                        minTop = top;
11087                        yLoc = top - mTop;
11088                    } else {
11089                        minTop = mTop;
11090                        yLoc = 0;
11091                    }
11092                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11093                }
11094            } else {
11095                // Double-invalidation is necessary to capture view's old and new areas
11096                invalidate(true);
11097            }
11098
11099            int width = mRight - mLeft;
11100            int oldHeight = mBottom - mTop;
11101
11102            mTop = top;
11103            mRenderNode.setTop(mTop);
11104
11105            sizeChange(width, mBottom - mTop, width, oldHeight);
11106
11107            if (!matrixIsIdentity) {
11108                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11109                invalidate(true);
11110            }
11111            mBackgroundSizeChanged = true;
11112            if (mForegroundInfo != null) {
11113                mForegroundInfo.mBoundsChanged = true;
11114            }
11115            invalidateParentIfNeeded();
11116            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11117                // View was rejected last time it was drawn by its parent; this may have changed
11118                invalidateParentIfNeeded();
11119            }
11120        }
11121    }
11122
11123    /**
11124     * Bottom position of this view relative to its parent.
11125     *
11126     * @return The bottom of this view, in pixels.
11127     */
11128    @ViewDebug.CapturedViewProperty
11129    public final int getBottom() {
11130        return mBottom;
11131    }
11132
11133    /**
11134     * True if this view has changed since the last time being drawn.
11135     *
11136     * @return The dirty state of this view.
11137     */
11138    public boolean isDirty() {
11139        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11140    }
11141
11142    /**
11143     * Sets the bottom position of this view relative to its parent. This method is meant to be
11144     * called by the layout system and should not generally be called otherwise, because the
11145     * property may be changed at any time by the layout.
11146     *
11147     * @param bottom The bottom of this view, in pixels.
11148     */
11149    public final void setBottom(int bottom) {
11150        if (bottom != mBottom) {
11151            final boolean matrixIsIdentity = hasIdentityMatrix();
11152            if (matrixIsIdentity) {
11153                if (mAttachInfo != null) {
11154                    int maxBottom;
11155                    if (bottom < mBottom) {
11156                        maxBottom = mBottom;
11157                    } else {
11158                        maxBottom = bottom;
11159                    }
11160                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11161                }
11162            } else {
11163                // Double-invalidation is necessary to capture view's old and new areas
11164                invalidate(true);
11165            }
11166
11167            int width = mRight - mLeft;
11168            int oldHeight = mBottom - mTop;
11169
11170            mBottom = bottom;
11171            mRenderNode.setBottom(mBottom);
11172
11173            sizeChange(width, mBottom - mTop, width, oldHeight);
11174
11175            if (!matrixIsIdentity) {
11176                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11177                invalidate(true);
11178            }
11179            mBackgroundSizeChanged = true;
11180            if (mForegroundInfo != null) {
11181                mForegroundInfo.mBoundsChanged = true;
11182            }
11183            invalidateParentIfNeeded();
11184            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11185                // View was rejected last time it was drawn by its parent; this may have changed
11186                invalidateParentIfNeeded();
11187            }
11188        }
11189    }
11190
11191    /**
11192     * Left position of this view relative to its parent.
11193     *
11194     * @return The left edge of this view, in pixels.
11195     */
11196    @ViewDebug.CapturedViewProperty
11197    public final int getLeft() {
11198        return mLeft;
11199    }
11200
11201    /**
11202     * Sets the left position of this view relative to its parent. This method is meant to be called
11203     * by the layout system and should not generally be called otherwise, because the property
11204     * may be changed at any time by the layout.
11205     *
11206     * @param left The left of this view, in pixels.
11207     */
11208    public final void setLeft(int left) {
11209        if (left != mLeft) {
11210            final boolean matrixIsIdentity = hasIdentityMatrix();
11211            if (matrixIsIdentity) {
11212                if (mAttachInfo != null) {
11213                    int minLeft;
11214                    int xLoc;
11215                    if (left < mLeft) {
11216                        minLeft = left;
11217                        xLoc = left - mLeft;
11218                    } else {
11219                        minLeft = mLeft;
11220                        xLoc = 0;
11221                    }
11222                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11223                }
11224            } else {
11225                // Double-invalidation is necessary to capture view's old and new areas
11226                invalidate(true);
11227            }
11228
11229            int oldWidth = mRight - mLeft;
11230            int height = mBottom - mTop;
11231
11232            mLeft = left;
11233            mRenderNode.setLeft(left);
11234
11235            sizeChange(mRight - mLeft, height, oldWidth, height);
11236
11237            if (!matrixIsIdentity) {
11238                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11239                invalidate(true);
11240            }
11241            mBackgroundSizeChanged = true;
11242            if (mForegroundInfo != null) {
11243                mForegroundInfo.mBoundsChanged = true;
11244            }
11245            invalidateParentIfNeeded();
11246            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11247                // View was rejected last time it was drawn by its parent; this may have changed
11248                invalidateParentIfNeeded();
11249            }
11250        }
11251    }
11252
11253    /**
11254     * Right position of this view relative to its parent.
11255     *
11256     * @return The right edge of this view, in pixels.
11257     */
11258    @ViewDebug.CapturedViewProperty
11259    public final int getRight() {
11260        return mRight;
11261    }
11262
11263    /**
11264     * Sets the right position of this view relative to its parent. This method is meant to be called
11265     * by the layout system and should not generally be called otherwise, because the property
11266     * may be changed at any time by the layout.
11267     *
11268     * @param right The right of this view, in pixels.
11269     */
11270    public final void setRight(int right) {
11271        if (right != mRight) {
11272            final boolean matrixIsIdentity = hasIdentityMatrix();
11273            if (matrixIsIdentity) {
11274                if (mAttachInfo != null) {
11275                    int maxRight;
11276                    if (right < mRight) {
11277                        maxRight = mRight;
11278                    } else {
11279                        maxRight = right;
11280                    }
11281                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11282                }
11283            } else {
11284                // Double-invalidation is necessary to capture view's old and new areas
11285                invalidate(true);
11286            }
11287
11288            int oldWidth = mRight - mLeft;
11289            int height = mBottom - mTop;
11290
11291            mRight = right;
11292            mRenderNode.setRight(mRight);
11293
11294            sizeChange(mRight - mLeft, height, oldWidth, height);
11295
11296            if (!matrixIsIdentity) {
11297                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11298                invalidate(true);
11299            }
11300            mBackgroundSizeChanged = true;
11301            if (mForegroundInfo != null) {
11302                mForegroundInfo.mBoundsChanged = true;
11303            }
11304            invalidateParentIfNeeded();
11305            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11306                // View was rejected last time it was drawn by its parent; this may have changed
11307                invalidateParentIfNeeded();
11308            }
11309        }
11310    }
11311
11312    /**
11313     * The visual x position of this view, in pixels. This is equivalent to the
11314     * {@link #setTranslationX(float) translationX} property plus the current
11315     * {@link #getLeft() left} property.
11316     *
11317     * @return The visual x position of this view, in pixels.
11318     */
11319    @ViewDebug.ExportedProperty(category = "drawing")
11320    public float getX() {
11321        return mLeft + getTranslationX();
11322    }
11323
11324    /**
11325     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11326     * {@link #setTranslationX(float) translationX} property to be the difference between
11327     * the x value passed in and the current {@link #getLeft() left} property.
11328     *
11329     * @param x The visual x position of this view, in pixels.
11330     */
11331    public void setX(float x) {
11332        setTranslationX(x - mLeft);
11333    }
11334
11335    /**
11336     * The visual y position of this view, in pixels. This is equivalent to the
11337     * {@link #setTranslationY(float) translationY} property plus the current
11338     * {@link #getTop() top} property.
11339     *
11340     * @return The visual y position of this view, in pixels.
11341     */
11342    @ViewDebug.ExportedProperty(category = "drawing")
11343    public float getY() {
11344        return mTop + getTranslationY();
11345    }
11346
11347    /**
11348     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11349     * {@link #setTranslationY(float) translationY} property to be the difference between
11350     * the y value passed in and the current {@link #getTop() top} property.
11351     *
11352     * @param y The visual y position of this view, in pixels.
11353     */
11354    public void setY(float y) {
11355        setTranslationY(y - mTop);
11356    }
11357
11358    /**
11359     * The visual z position of this view, in pixels. This is equivalent to the
11360     * {@link #setTranslationZ(float) translationZ} property plus the current
11361     * {@link #getElevation() elevation} property.
11362     *
11363     * @return The visual z position of this view, in pixels.
11364     */
11365    @ViewDebug.ExportedProperty(category = "drawing")
11366    public float getZ() {
11367        return getElevation() + getTranslationZ();
11368    }
11369
11370    /**
11371     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11372     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11373     * the x value passed in and the current {@link #getElevation() elevation} property.
11374     *
11375     * @param z The visual z position of this view, in pixels.
11376     */
11377    public void setZ(float z) {
11378        setTranslationZ(z - getElevation());
11379    }
11380
11381    /**
11382     * The base elevation of this view relative to its parent, in pixels.
11383     *
11384     * @return The base depth position of the view, in pixels.
11385     */
11386    @ViewDebug.ExportedProperty(category = "drawing")
11387    public float getElevation() {
11388        return mRenderNode.getElevation();
11389    }
11390
11391    /**
11392     * Sets the base elevation of this view, in pixels.
11393     *
11394     * @attr ref android.R.styleable#View_elevation
11395     */
11396    public void setElevation(float elevation) {
11397        if (elevation != getElevation()) {
11398            invalidateViewProperty(true, false);
11399            mRenderNode.setElevation(elevation);
11400            invalidateViewProperty(false, true);
11401
11402            invalidateParentIfNeededAndWasQuickRejected();
11403        }
11404    }
11405
11406    /**
11407     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11408     * This position is post-layout, in addition to wherever the object's
11409     * layout placed it.
11410     *
11411     * @return The horizontal position of this view relative to its left position, in pixels.
11412     */
11413    @ViewDebug.ExportedProperty(category = "drawing")
11414    public float getTranslationX() {
11415        return mRenderNode.getTranslationX();
11416    }
11417
11418    /**
11419     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11420     * This effectively positions the object post-layout, in addition to wherever the object's
11421     * layout placed it.
11422     *
11423     * @param translationX The horizontal position of this view relative to its left position,
11424     * in pixels.
11425     *
11426     * @attr ref android.R.styleable#View_translationX
11427     */
11428    public void setTranslationX(float translationX) {
11429        if (translationX != getTranslationX()) {
11430            invalidateViewProperty(true, false);
11431            mRenderNode.setTranslationX(translationX);
11432            invalidateViewProperty(false, true);
11433
11434            invalidateParentIfNeededAndWasQuickRejected();
11435            notifySubtreeAccessibilityStateChangedIfNeeded();
11436        }
11437    }
11438
11439    /**
11440     * The vertical location of this view relative to its {@link #getTop() top} position.
11441     * This position is post-layout, in addition to wherever the object's
11442     * layout placed it.
11443     *
11444     * @return The vertical position of this view relative to its top position,
11445     * in pixels.
11446     */
11447    @ViewDebug.ExportedProperty(category = "drawing")
11448    public float getTranslationY() {
11449        return mRenderNode.getTranslationY();
11450    }
11451
11452    /**
11453     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11454     * This effectively positions the object post-layout, in addition to wherever the object's
11455     * layout placed it.
11456     *
11457     * @param translationY The vertical position of this view relative to its top position,
11458     * in pixels.
11459     *
11460     * @attr ref android.R.styleable#View_translationY
11461     */
11462    public void setTranslationY(float translationY) {
11463        if (translationY != getTranslationY()) {
11464            invalidateViewProperty(true, false);
11465            mRenderNode.setTranslationY(translationY);
11466            invalidateViewProperty(false, true);
11467
11468            invalidateParentIfNeededAndWasQuickRejected();
11469            notifySubtreeAccessibilityStateChangedIfNeeded();
11470        }
11471    }
11472
11473    /**
11474     * The depth location of this view relative to its {@link #getElevation() elevation}.
11475     *
11476     * @return The depth of this view relative to its elevation.
11477     */
11478    @ViewDebug.ExportedProperty(category = "drawing")
11479    public float getTranslationZ() {
11480        return mRenderNode.getTranslationZ();
11481    }
11482
11483    /**
11484     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11485     *
11486     * @attr ref android.R.styleable#View_translationZ
11487     */
11488    public void setTranslationZ(float translationZ) {
11489        if (translationZ != getTranslationZ()) {
11490            invalidateViewProperty(true, false);
11491            mRenderNode.setTranslationZ(translationZ);
11492            invalidateViewProperty(false, true);
11493
11494            invalidateParentIfNeededAndWasQuickRejected();
11495        }
11496    }
11497
11498    /** @hide */
11499    public void setAnimationMatrix(Matrix matrix) {
11500        invalidateViewProperty(true, false);
11501        mRenderNode.setAnimationMatrix(matrix);
11502        invalidateViewProperty(false, true);
11503
11504        invalidateParentIfNeededAndWasQuickRejected();
11505    }
11506
11507    /**
11508     * Returns the current StateListAnimator if exists.
11509     *
11510     * @return StateListAnimator or null if it does not exists
11511     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11512     */
11513    public StateListAnimator getStateListAnimator() {
11514        return mStateListAnimator;
11515    }
11516
11517    /**
11518     * Attaches the provided StateListAnimator to this View.
11519     * <p>
11520     * Any previously attached StateListAnimator will be detached.
11521     *
11522     * @param stateListAnimator The StateListAnimator to update the view
11523     * @see {@link android.animation.StateListAnimator}
11524     */
11525    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11526        if (mStateListAnimator == stateListAnimator) {
11527            return;
11528        }
11529        if (mStateListAnimator != null) {
11530            mStateListAnimator.setTarget(null);
11531        }
11532        mStateListAnimator = stateListAnimator;
11533        if (stateListAnimator != null) {
11534            stateListAnimator.setTarget(this);
11535            if (isAttachedToWindow()) {
11536                stateListAnimator.setState(getDrawableState());
11537            }
11538        }
11539    }
11540
11541    /**
11542     * Returns whether the Outline should be used to clip the contents of the View.
11543     * <p>
11544     * Note that this flag will only be respected if the View's Outline returns true from
11545     * {@link Outline#canClip()}.
11546     *
11547     * @see #setOutlineProvider(ViewOutlineProvider)
11548     * @see #setClipToOutline(boolean)
11549     */
11550    public final boolean getClipToOutline() {
11551        return mRenderNode.getClipToOutline();
11552    }
11553
11554    /**
11555     * Sets whether the View's Outline should be used to clip the contents of the View.
11556     * <p>
11557     * Only a single non-rectangular clip can be applied on a View at any time.
11558     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11559     * circular reveal} animation take priority over Outline clipping, and
11560     * child Outline clipping takes priority over Outline clipping done by a
11561     * parent.
11562     * <p>
11563     * Note that this flag will only be respected if the View's Outline returns true from
11564     * {@link Outline#canClip()}.
11565     *
11566     * @see #setOutlineProvider(ViewOutlineProvider)
11567     * @see #getClipToOutline()
11568     */
11569    public void setClipToOutline(boolean clipToOutline) {
11570        damageInParent();
11571        if (getClipToOutline() != clipToOutline) {
11572            mRenderNode.setClipToOutline(clipToOutline);
11573        }
11574    }
11575
11576    // correspond to the enum values of View_outlineProvider
11577    private static final int PROVIDER_BACKGROUND = 0;
11578    private static final int PROVIDER_NONE = 1;
11579    private static final int PROVIDER_BOUNDS = 2;
11580    private static final int PROVIDER_PADDED_BOUNDS = 3;
11581    private void setOutlineProviderFromAttribute(int providerInt) {
11582        switch (providerInt) {
11583            case PROVIDER_BACKGROUND:
11584                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11585                break;
11586            case PROVIDER_NONE:
11587                setOutlineProvider(null);
11588                break;
11589            case PROVIDER_BOUNDS:
11590                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11591                break;
11592            case PROVIDER_PADDED_BOUNDS:
11593                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11594                break;
11595        }
11596    }
11597
11598    /**
11599     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11600     * the shape of the shadow it casts, and enables outline clipping.
11601     * <p>
11602     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11603     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11604     * outline provider with this method allows this behavior to be overridden.
11605     * <p>
11606     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11607     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11608     * <p>
11609     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11610     *
11611     * @see #setClipToOutline(boolean)
11612     * @see #getClipToOutline()
11613     * @see #getOutlineProvider()
11614     */
11615    public void setOutlineProvider(ViewOutlineProvider provider) {
11616        mOutlineProvider = provider;
11617        invalidateOutline();
11618    }
11619
11620    /**
11621     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11622     * that defines the shape of the shadow it casts, and enables outline clipping.
11623     *
11624     * @see #setOutlineProvider(ViewOutlineProvider)
11625     */
11626    public ViewOutlineProvider getOutlineProvider() {
11627        return mOutlineProvider;
11628    }
11629
11630    /**
11631     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11632     *
11633     * @see #setOutlineProvider(ViewOutlineProvider)
11634     */
11635    public void invalidateOutline() {
11636        rebuildOutline();
11637
11638        notifySubtreeAccessibilityStateChangedIfNeeded();
11639        invalidateViewProperty(false, false);
11640    }
11641
11642    /**
11643     * Internal version of {@link #invalidateOutline()} which invalidates the
11644     * outline without invalidating the view itself. This is intended to be called from
11645     * within methods in the View class itself which are the result of the view being
11646     * invalidated already. For example, when we are drawing the background of a View,
11647     * we invalidate the outline in case it changed in the meantime, but we do not
11648     * need to invalidate the view because we're already drawing the background as part
11649     * of drawing the view in response to an earlier invalidation of the view.
11650     */
11651    private void rebuildOutline() {
11652        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11653        if (mAttachInfo == null) return;
11654
11655        if (mOutlineProvider == null) {
11656            // no provider, remove outline
11657            mRenderNode.setOutline(null);
11658        } else {
11659            final Outline outline = mAttachInfo.mTmpOutline;
11660            outline.setEmpty();
11661            outline.setAlpha(1.0f);
11662
11663            mOutlineProvider.getOutline(this, outline);
11664            mRenderNode.setOutline(outline);
11665        }
11666    }
11667
11668    /**
11669     * HierarchyViewer only
11670     *
11671     * @hide
11672     */
11673    @ViewDebug.ExportedProperty(category = "drawing")
11674    public boolean hasShadow() {
11675        return mRenderNode.hasShadow();
11676    }
11677
11678
11679    /** @hide */
11680    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11681        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11682        invalidateViewProperty(false, false);
11683    }
11684
11685    /**
11686     * Hit rectangle in parent's coordinates
11687     *
11688     * @param outRect The hit rectangle of the view.
11689     */
11690    public void getHitRect(Rect outRect) {
11691        if (hasIdentityMatrix() || mAttachInfo == null) {
11692            outRect.set(mLeft, mTop, mRight, mBottom);
11693        } else {
11694            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11695            tmpRect.set(0, 0, getWidth(), getHeight());
11696            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11697            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11698                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11699        }
11700    }
11701
11702    /**
11703     * Determines whether the given point, in local coordinates is inside the view.
11704     */
11705    /*package*/ final boolean pointInView(float localX, float localY) {
11706        return localX >= 0 && localX < (mRight - mLeft)
11707                && localY >= 0 && localY < (mBottom - mTop);
11708    }
11709
11710    /**
11711     * Utility method to determine whether the given point, in local coordinates,
11712     * is inside the view, where the area of the view is expanded by the slop factor.
11713     * This method is called while processing touch-move events to determine if the event
11714     * is still within the view.
11715     *
11716     * @hide
11717     */
11718    public boolean pointInView(float localX, float localY, float slop) {
11719        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11720                localY < ((mBottom - mTop) + slop);
11721    }
11722
11723    /**
11724     * When a view has focus and the user navigates away from it, the next view is searched for
11725     * starting from the rectangle filled in by this method.
11726     *
11727     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11728     * of the view.  However, if your view maintains some idea of internal selection,
11729     * such as a cursor, or a selected row or column, you should override this method and
11730     * fill in a more specific rectangle.
11731     *
11732     * @param r The rectangle to fill in, in this view's coordinates.
11733     */
11734    public void getFocusedRect(Rect r) {
11735        getDrawingRect(r);
11736    }
11737
11738    /**
11739     * If some part of this view is not clipped by any of its parents, then
11740     * return that area in r in global (root) coordinates. To convert r to local
11741     * coordinates (without taking possible View rotations into account), offset
11742     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11743     * If the view is completely clipped or translated out, return false.
11744     *
11745     * @param r If true is returned, r holds the global coordinates of the
11746     *        visible portion of this view.
11747     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11748     *        between this view and its root. globalOffet may be null.
11749     * @return true if r is non-empty (i.e. part of the view is visible at the
11750     *         root level.
11751     */
11752    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11753        int width = mRight - mLeft;
11754        int height = mBottom - mTop;
11755        if (width > 0 && height > 0) {
11756            r.set(0, 0, width, height);
11757            if (globalOffset != null) {
11758                globalOffset.set(-mScrollX, -mScrollY);
11759            }
11760            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11761        }
11762        return false;
11763    }
11764
11765    public final boolean getGlobalVisibleRect(Rect r) {
11766        return getGlobalVisibleRect(r, null);
11767    }
11768
11769    public final boolean getLocalVisibleRect(Rect r) {
11770        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11771        if (getGlobalVisibleRect(r, offset)) {
11772            r.offset(-offset.x, -offset.y); // make r local
11773            return true;
11774        }
11775        return false;
11776    }
11777
11778    /**
11779     * Offset this view's vertical location by the specified number of pixels.
11780     *
11781     * @param offset the number of pixels to offset the view by
11782     */
11783    public void offsetTopAndBottom(int offset) {
11784        if (offset != 0) {
11785            final boolean matrixIsIdentity = hasIdentityMatrix();
11786            if (matrixIsIdentity) {
11787                if (isHardwareAccelerated()) {
11788                    invalidateViewProperty(false, false);
11789                } else {
11790                    final ViewParent p = mParent;
11791                    if (p != null && mAttachInfo != null) {
11792                        final Rect r = mAttachInfo.mTmpInvalRect;
11793                        int minTop;
11794                        int maxBottom;
11795                        int yLoc;
11796                        if (offset < 0) {
11797                            minTop = mTop + offset;
11798                            maxBottom = mBottom;
11799                            yLoc = offset;
11800                        } else {
11801                            minTop = mTop;
11802                            maxBottom = mBottom + offset;
11803                            yLoc = 0;
11804                        }
11805                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11806                        p.invalidateChild(this, r);
11807                    }
11808                }
11809            } else {
11810                invalidateViewProperty(false, false);
11811            }
11812
11813            mTop += offset;
11814            mBottom += offset;
11815            mRenderNode.offsetTopAndBottom(offset);
11816            if (isHardwareAccelerated()) {
11817                invalidateViewProperty(false, false);
11818            } else {
11819                if (!matrixIsIdentity) {
11820                    invalidateViewProperty(false, true);
11821                }
11822                invalidateParentIfNeeded();
11823            }
11824            notifySubtreeAccessibilityStateChangedIfNeeded();
11825        }
11826    }
11827
11828    /**
11829     * Offset this view's horizontal location by the specified amount of pixels.
11830     *
11831     * @param offset the number of pixels to offset the view by
11832     */
11833    public void offsetLeftAndRight(int offset) {
11834        if (offset != 0) {
11835            final boolean matrixIsIdentity = hasIdentityMatrix();
11836            if (matrixIsIdentity) {
11837                if (isHardwareAccelerated()) {
11838                    invalidateViewProperty(false, false);
11839                } else {
11840                    final ViewParent p = mParent;
11841                    if (p != null && mAttachInfo != null) {
11842                        final Rect r = mAttachInfo.mTmpInvalRect;
11843                        int minLeft;
11844                        int maxRight;
11845                        if (offset < 0) {
11846                            minLeft = mLeft + offset;
11847                            maxRight = mRight;
11848                        } else {
11849                            minLeft = mLeft;
11850                            maxRight = mRight + offset;
11851                        }
11852                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11853                        p.invalidateChild(this, r);
11854                    }
11855                }
11856            } else {
11857                invalidateViewProperty(false, false);
11858            }
11859
11860            mLeft += offset;
11861            mRight += offset;
11862            mRenderNode.offsetLeftAndRight(offset);
11863            if (isHardwareAccelerated()) {
11864                invalidateViewProperty(false, false);
11865            } else {
11866                if (!matrixIsIdentity) {
11867                    invalidateViewProperty(false, true);
11868                }
11869                invalidateParentIfNeeded();
11870            }
11871            notifySubtreeAccessibilityStateChangedIfNeeded();
11872        }
11873    }
11874
11875    /**
11876     * Get the LayoutParams associated with this view. All views should have
11877     * layout parameters. These supply parameters to the <i>parent</i> of this
11878     * view specifying how it should be arranged. There are many subclasses of
11879     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11880     * of ViewGroup that are responsible for arranging their children.
11881     *
11882     * This method may return null if this View is not attached to a parent
11883     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11884     * was not invoked successfully. When a View is attached to a parent
11885     * ViewGroup, this method must not return null.
11886     *
11887     * @return The LayoutParams associated with this view, or null if no
11888     *         parameters have been set yet
11889     */
11890    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11891    public ViewGroup.LayoutParams getLayoutParams() {
11892        return mLayoutParams;
11893    }
11894
11895    /**
11896     * Set the layout parameters associated with this view. These supply
11897     * parameters to the <i>parent</i> of this view specifying how it should be
11898     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11899     * correspond to the different subclasses of ViewGroup that are responsible
11900     * for arranging their children.
11901     *
11902     * @param params The layout parameters for this view, cannot be null
11903     */
11904    public void setLayoutParams(ViewGroup.LayoutParams params) {
11905        if (params == null) {
11906            throw new NullPointerException("Layout parameters cannot be null");
11907        }
11908        mLayoutParams = params;
11909        resolveLayoutParams();
11910        if (mParent instanceof ViewGroup) {
11911            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11912        }
11913        requestLayout();
11914    }
11915
11916    /**
11917     * Resolve the layout parameters depending on the resolved layout direction
11918     *
11919     * @hide
11920     */
11921    public void resolveLayoutParams() {
11922        if (mLayoutParams != null) {
11923            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11924        }
11925    }
11926
11927    /**
11928     * Set the scrolled position of your view. This will cause a call to
11929     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11930     * invalidated.
11931     * @param x the x position to scroll to
11932     * @param y the y position to scroll to
11933     */
11934    public void scrollTo(int x, int y) {
11935        if (mScrollX != x || mScrollY != y) {
11936            int oldX = mScrollX;
11937            int oldY = mScrollY;
11938            mScrollX = x;
11939            mScrollY = y;
11940            invalidateParentCaches();
11941            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11942            if (!awakenScrollBars()) {
11943                postInvalidateOnAnimation();
11944            }
11945        }
11946    }
11947
11948    /**
11949     * Move the scrolled position of your view. This will cause a call to
11950     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11951     * invalidated.
11952     * @param x the amount of pixels to scroll by horizontally
11953     * @param y the amount of pixels to scroll by vertically
11954     */
11955    public void scrollBy(int x, int y) {
11956        scrollTo(mScrollX + x, mScrollY + y);
11957    }
11958
11959    /**
11960     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11961     * animation to fade the scrollbars out after a default delay. If a subclass
11962     * provides animated scrolling, the start delay should equal the duration
11963     * of the scrolling animation.</p>
11964     *
11965     * <p>The animation starts only if at least one of the scrollbars is
11966     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11967     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11968     * this method returns true, and false otherwise. If the animation is
11969     * started, this method calls {@link #invalidate()}; in that case the
11970     * caller should not call {@link #invalidate()}.</p>
11971     *
11972     * <p>This method should be invoked every time a subclass directly updates
11973     * the scroll parameters.</p>
11974     *
11975     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11976     * and {@link #scrollTo(int, int)}.</p>
11977     *
11978     * @return true if the animation is played, false otherwise
11979     *
11980     * @see #awakenScrollBars(int)
11981     * @see #scrollBy(int, int)
11982     * @see #scrollTo(int, int)
11983     * @see #isHorizontalScrollBarEnabled()
11984     * @see #isVerticalScrollBarEnabled()
11985     * @see #setHorizontalScrollBarEnabled(boolean)
11986     * @see #setVerticalScrollBarEnabled(boolean)
11987     */
11988    protected boolean awakenScrollBars() {
11989        return mScrollCache != null &&
11990                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11991    }
11992
11993    /**
11994     * Trigger the scrollbars to draw.
11995     * This method differs from awakenScrollBars() only in its default duration.
11996     * initialAwakenScrollBars() will show the scroll bars for longer than
11997     * usual to give the user more of a chance to notice them.
11998     *
11999     * @return true if the animation is played, false otherwise.
12000     */
12001    private boolean initialAwakenScrollBars() {
12002        return mScrollCache != null &&
12003                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
12004    }
12005
12006    /**
12007     * <p>
12008     * Trigger the scrollbars to draw. When invoked this method starts an
12009     * animation to fade the scrollbars out after a fixed delay. If a subclass
12010     * provides animated scrolling, the start delay should equal the duration of
12011     * the scrolling animation.
12012     * </p>
12013     *
12014     * <p>
12015     * The animation starts only if at least one of the scrollbars is enabled,
12016     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12017     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12018     * this method returns true, and false otherwise. If the animation is
12019     * started, this method calls {@link #invalidate()}; in that case the caller
12020     * should not call {@link #invalidate()}.
12021     * </p>
12022     *
12023     * <p>
12024     * This method should be invoked every time a subclass directly updates the
12025     * scroll parameters.
12026     * </p>
12027     *
12028     * @param startDelay the delay, in milliseconds, after which the animation
12029     *        should start; when the delay is 0, the animation starts
12030     *        immediately
12031     * @return true if the animation is played, false otherwise
12032     *
12033     * @see #scrollBy(int, int)
12034     * @see #scrollTo(int, int)
12035     * @see #isHorizontalScrollBarEnabled()
12036     * @see #isVerticalScrollBarEnabled()
12037     * @see #setHorizontalScrollBarEnabled(boolean)
12038     * @see #setVerticalScrollBarEnabled(boolean)
12039     */
12040    protected boolean awakenScrollBars(int startDelay) {
12041        return awakenScrollBars(startDelay, true);
12042    }
12043
12044    /**
12045     * <p>
12046     * Trigger the scrollbars to draw. When invoked this method starts an
12047     * animation to fade the scrollbars out after a fixed delay. If a subclass
12048     * provides animated scrolling, the start delay should equal the duration of
12049     * the scrolling animation.
12050     * </p>
12051     *
12052     * <p>
12053     * The animation starts only if at least one of the scrollbars is enabled,
12054     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12055     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12056     * this method returns true, and false otherwise. If the animation is
12057     * started, this method calls {@link #invalidate()} if the invalidate parameter
12058     * is set to true; in that case the caller
12059     * should not call {@link #invalidate()}.
12060     * </p>
12061     *
12062     * <p>
12063     * This method should be invoked every time a subclass directly updates the
12064     * scroll parameters.
12065     * </p>
12066     *
12067     * @param startDelay the delay, in milliseconds, after which the animation
12068     *        should start; when the delay is 0, the animation starts
12069     *        immediately
12070     *
12071     * @param invalidate Whether this method should call invalidate
12072     *
12073     * @return true if the animation is played, false otherwise
12074     *
12075     * @see #scrollBy(int, int)
12076     * @see #scrollTo(int, int)
12077     * @see #isHorizontalScrollBarEnabled()
12078     * @see #isVerticalScrollBarEnabled()
12079     * @see #setHorizontalScrollBarEnabled(boolean)
12080     * @see #setVerticalScrollBarEnabled(boolean)
12081     */
12082    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
12083        final ScrollabilityCache scrollCache = mScrollCache;
12084
12085        if (scrollCache == null || !scrollCache.fadeScrollBars) {
12086            return false;
12087        }
12088
12089        if (scrollCache.scrollBar == null) {
12090            scrollCache.scrollBar = new ScrollBarDrawable();
12091            scrollCache.scrollBar.setCallback(this);
12092            scrollCache.scrollBar.setState(getDrawableState());
12093        }
12094
12095        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12096
12097            if (invalidate) {
12098                // Invalidate to show the scrollbars
12099                postInvalidateOnAnimation();
12100            }
12101
12102            if (scrollCache.state == ScrollabilityCache.OFF) {
12103                // FIXME: this is copied from WindowManagerService.
12104                // We should get this value from the system when it
12105                // is possible to do so.
12106                final int KEY_REPEAT_FIRST_DELAY = 750;
12107                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12108            }
12109
12110            // Tell mScrollCache when we should start fading. This may
12111            // extend the fade start time if one was already scheduled
12112            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12113            scrollCache.fadeStartTime = fadeStartTime;
12114            scrollCache.state = ScrollabilityCache.ON;
12115
12116            // Schedule our fader to run, unscheduling any old ones first
12117            if (mAttachInfo != null) {
12118                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12119                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12120            }
12121
12122            return true;
12123        }
12124
12125        return false;
12126    }
12127
12128    /**
12129     * Do not invalidate views which are not visible and which are not running an animation. They
12130     * will not get drawn and they should not set dirty flags as if they will be drawn
12131     */
12132    private boolean skipInvalidate() {
12133        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12134                (!(mParent instanceof ViewGroup) ||
12135                        !((ViewGroup) mParent).isViewTransitioning(this));
12136    }
12137
12138    /**
12139     * Mark the area defined by dirty as needing to be drawn. If the view is
12140     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12141     * point in the future.
12142     * <p>
12143     * This must be called from a UI thread. To call from a non-UI thread, call
12144     * {@link #postInvalidate()}.
12145     * <p>
12146     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12147     * {@code dirty}.
12148     *
12149     * @param dirty the rectangle representing the bounds of the dirty region
12150     */
12151    public void invalidate(Rect dirty) {
12152        final int scrollX = mScrollX;
12153        final int scrollY = mScrollY;
12154        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12155                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12156    }
12157
12158    /**
12159     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12160     * coordinates of the dirty rect are relative to the view. If the view is
12161     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12162     * point in the future.
12163     * <p>
12164     * This must be called from a UI thread. To call from a non-UI thread, call
12165     * {@link #postInvalidate()}.
12166     *
12167     * @param l the left position of the dirty region
12168     * @param t the top position of the dirty region
12169     * @param r the right position of the dirty region
12170     * @param b the bottom position of the dirty region
12171     */
12172    public void invalidate(int l, int t, int r, int b) {
12173        final int scrollX = mScrollX;
12174        final int scrollY = mScrollY;
12175        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12176    }
12177
12178    /**
12179     * Invalidate the whole view. If the view is visible,
12180     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12181     * the future.
12182     * <p>
12183     * This must be called from a UI thread. To call from a non-UI thread, call
12184     * {@link #postInvalidate()}.
12185     */
12186    public void invalidate() {
12187        invalidate(true);
12188    }
12189
12190    /**
12191     * This is where the invalidate() work actually happens. A full invalidate()
12192     * causes the drawing cache to be invalidated, but this function can be
12193     * called with invalidateCache set to false to skip that invalidation step
12194     * for cases that do not need it (for example, a component that remains at
12195     * the same dimensions with the same content).
12196     *
12197     * @param invalidateCache Whether the drawing cache for this view should be
12198     *            invalidated as well. This is usually true for a full
12199     *            invalidate, but may be set to false if the View's contents or
12200     *            dimensions have not changed.
12201     */
12202    void invalidate(boolean invalidateCache) {
12203        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12204    }
12205
12206    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12207            boolean fullInvalidate) {
12208        if (mGhostView != null) {
12209            mGhostView.invalidate(true);
12210            return;
12211        }
12212
12213        if (skipInvalidate()) {
12214            return;
12215        }
12216
12217        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12218                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12219                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12220                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12221            if (fullInvalidate) {
12222                mLastIsOpaque = isOpaque();
12223                mPrivateFlags &= ~PFLAG_DRAWN;
12224            }
12225
12226            mPrivateFlags |= PFLAG_DIRTY;
12227
12228            if (invalidateCache) {
12229                mPrivateFlags |= PFLAG_INVALIDATED;
12230                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12231            }
12232
12233            // Propagate the damage rectangle to the parent view.
12234            final AttachInfo ai = mAttachInfo;
12235            final ViewParent p = mParent;
12236            if (p != null && ai != null && l < r && t < b) {
12237                final Rect damage = ai.mTmpInvalRect;
12238                damage.set(l, t, r, b);
12239                p.invalidateChild(this, damage);
12240            }
12241
12242            // Damage the entire projection receiver, if necessary.
12243            if (mBackground != null && mBackground.isProjected()) {
12244                final View receiver = getProjectionReceiver();
12245                if (receiver != null) {
12246                    receiver.damageInParent();
12247                }
12248            }
12249
12250            // Damage the entire IsolatedZVolume receiving this view's shadow.
12251            if (isHardwareAccelerated() && getZ() != 0) {
12252                damageShadowReceiver();
12253            }
12254        }
12255    }
12256
12257    /**
12258     * @return this view's projection receiver, or {@code null} if none exists
12259     */
12260    private View getProjectionReceiver() {
12261        ViewParent p = getParent();
12262        while (p != null && p instanceof View) {
12263            final View v = (View) p;
12264            if (v.isProjectionReceiver()) {
12265                return v;
12266            }
12267            p = p.getParent();
12268        }
12269
12270        return null;
12271    }
12272
12273    /**
12274     * @return whether the view is a projection receiver
12275     */
12276    private boolean isProjectionReceiver() {
12277        return mBackground != null;
12278    }
12279
12280    /**
12281     * Damage area of the screen that can be covered by this View's shadow.
12282     *
12283     * This method will guarantee that any changes to shadows cast by a View
12284     * are damaged on the screen for future redraw.
12285     */
12286    private void damageShadowReceiver() {
12287        final AttachInfo ai = mAttachInfo;
12288        if (ai != null) {
12289            ViewParent p = getParent();
12290            if (p != null && p instanceof ViewGroup) {
12291                final ViewGroup vg = (ViewGroup) p;
12292                vg.damageInParent();
12293            }
12294        }
12295    }
12296
12297    /**
12298     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12299     * set any flags or handle all of the cases handled by the default invalidation methods.
12300     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12301     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12302     * walk up the hierarchy, transforming the dirty rect as necessary.
12303     *
12304     * The method also handles normal invalidation logic if display list properties are not
12305     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12306     * backup approach, to handle these cases used in the various property-setting methods.
12307     *
12308     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12309     * are not being used in this view
12310     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12311     * list properties are not being used in this view
12312     */
12313    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12314        if (!isHardwareAccelerated()
12315                || !mRenderNode.isValid()
12316                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12317            if (invalidateParent) {
12318                invalidateParentCaches();
12319            }
12320            if (forceRedraw) {
12321                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12322            }
12323            invalidate(false);
12324        } else {
12325            damageInParent();
12326        }
12327        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12328            damageShadowReceiver();
12329        }
12330    }
12331
12332    /**
12333     * Tells the parent view to damage this view's bounds.
12334     *
12335     * @hide
12336     */
12337    protected void damageInParent() {
12338        final AttachInfo ai = mAttachInfo;
12339        final ViewParent p = mParent;
12340        if (p != null && ai != null) {
12341            final Rect r = ai.mTmpInvalRect;
12342            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12343            if (mParent instanceof ViewGroup) {
12344                ((ViewGroup) mParent).damageChild(this, r);
12345            } else {
12346                mParent.invalidateChild(this, r);
12347            }
12348        }
12349    }
12350
12351    /**
12352     * Utility method to transform a given Rect by the current matrix of this view.
12353     */
12354    void transformRect(final Rect rect) {
12355        if (!getMatrix().isIdentity()) {
12356            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12357            boundingRect.set(rect);
12358            getMatrix().mapRect(boundingRect);
12359            rect.set((int) Math.floor(boundingRect.left),
12360                    (int) Math.floor(boundingRect.top),
12361                    (int) Math.ceil(boundingRect.right),
12362                    (int) Math.ceil(boundingRect.bottom));
12363        }
12364    }
12365
12366    /**
12367     * Used to indicate that the parent of this view should clear its caches. This functionality
12368     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12369     * which is necessary when various parent-managed properties of the view change, such as
12370     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12371     * clears the parent caches and does not causes an invalidate event.
12372     *
12373     * @hide
12374     */
12375    protected void invalidateParentCaches() {
12376        if (mParent instanceof View) {
12377            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12378        }
12379    }
12380
12381    /**
12382     * Used to indicate that the parent of this view should be invalidated. This functionality
12383     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12384     * which is necessary when various parent-managed properties of the view change, such as
12385     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12386     * an invalidation event to the parent.
12387     *
12388     * @hide
12389     */
12390    protected void invalidateParentIfNeeded() {
12391        if (isHardwareAccelerated() && mParent instanceof View) {
12392            ((View) mParent).invalidate(true);
12393        }
12394    }
12395
12396    /**
12397     * @hide
12398     */
12399    protected void invalidateParentIfNeededAndWasQuickRejected() {
12400        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12401            // View was rejected last time it was drawn by its parent; this may have changed
12402            invalidateParentIfNeeded();
12403        }
12404    }
12405
12406    /**
12407     * Indicates whether this View is opaque. An opaque View guarantees that it will
12408     * draw all the pixels overlapping its bounds using a fully opaque color.
12409     *
12410     * Subclasses of View should override this method whenever possible to indicate
12411     * whether an instance is opaque. Opaque Views are treated in a special way by
12412     * the View hierarchy, possibly allowing it to perform optimizations during
12413     * invalidate/draw passes.
12414     *
12415     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12416     */
12417    @ViewDebug.ExportedProperty(category = "drawing")
12418    public boolean isOpaque() {
12419        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12420                getFinalAlpha() >= 1.0f;
12421    }
12422
12423    /**
12424     * @hide
12425     */
12426    protected void computeOpaqueFlags() {
12427        // Opaque if:
12428        //   - Has a background
12429        //   - Background is opaque
12430        //   - Doesn't have scrollbars or scrollbars overlay
12431
12432        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12433            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12434        } else {
12435            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12436        }
12437
12438        final int flags = mViewFlags;
12439        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12440                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12441                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12442            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12443        } else {
12444            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12445        }
12446    }
12447
12448    /**
12449     * @hide
12450     */
12451    protected boolean hasOpaqueScrollbars() {
12452        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12453    }
12454
12455    /**
12456     * @return A handler associated with the thread running the View. This
12457     * handler can be used to pump events in the UI events queue.
12458     */
12459    public Handler getHandler() {
12460        final AttachInfo attachInfo = mAttachInfo;
12461        if (attachInfo != null) {
12462            return attachInfo.mHandler;
12463        }
12464        return null;
12465    }
12466
12467    /**
12468     * Gets the view root associated with the View.
12469     * @return The view root, or null if none.
12470     * @hide
12471     */
12472    public ViewRootImpl getViewRootImpl() {
12473        if (mAttachInfo != null) {
12474            return mAttachInfo.mViewRootImpl;
12475        }
12476        return null;
12477    }
12478
12479    /**
12480     * @hide
12481     */
12482    public HardwareRenderer getHardwareRenderer() {
12483        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12484    }
12485
12486    /**
12487     * <p>Causes the Runnable to be added to the message queue.
12488     * The runnable will be run on the user interface thread.</p>
12489     *
12490     * @param action The Runnable that will be executed.
12491     *
12492     * @return Returns true if the Runnable was successfully placed in to the
12493     *         message queue.  Returns false on failure, usually because the
12494     *         looper processing the message queue is exiting.
12495     *
12496     * @see #postDelayed
12497     * @see #removeCallbacks
12498     */
12499    public boolean post(Runnable action) {
12500        final AttachInfo attachInfo = mAttachInfo;
12501        if (attachInfo != null) {
12502            return attachInfo.mHandler.post(action);
12503        }
12504        // Assume that post will succeed later
12505        ViewRootImpl.getRunQueue().post(action);
12506        return true;
12507    }
12508
12509    /**
12510     * <p>Causes the Runnable to be added to the message queue, to be run
12511     * after the specified amount of time elapses.
12512     * The runnable will be run on the user interface thread.</p>
12513     *
12514     * @param action The Runnable that will be executed.
12515     * @param delayMillis The delay (in milliseconds) until the Runnable
12516     *        will be executed.
12517     *
12518     * @return true if the Runnable was successfully placed in to the
12519     *         message queue.  Returns false on failure, usually because the
12520     *         looper processing the message queue is exiting.  Note that a
12521     *         result of true does not mean the Runnable will be processed --
12522     *         if the looper is quit before the delivery time of the message
12523     *         occurs then the message will be dropped.
12524     *
12525     * @see #post
12526     * @see #removeCallbacks
12527     */
12528    public boolean postDelayed(Runnable action, long delayMillis) {
12529        final AttachInfo attachInfo = mAttachInfo;
12530        if (attachInfo != null) {
12531            return attachInfo.mHandler.postDelayed(action, delayMillis);
12532        }
12533        // Assume that post will succeed later
12534        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12535        return true;
12536    }
12537
12538    /**
12539     * <p>Causes the Runnable to execute on the next animation time step.
12540     * The runnable will be run on the user interface thread.</p>
12541     *
12542     * @param action The Runnable that will be executed.
12543     *
12544     * @see #postOnAnimationDelayed
12545     * @see #removeCallbacks
12546     */
12547    public void postOnAnimation(Runnable action) {
12548        final AttachInfo attachInfo = mAttachInfo;
12549        if (attachInfo != null) {
12550            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12551                    Choreographer.CALLBACK_ANIMATION, action, null);
12552        } else {
12553            // Assume that post will succeed later
12554            ViewRootImpl.getRunQueue().post(action);
12555        }
12556    }
12557
12558    /**
12559     * <p>Causes the Runnable to execute on the next animation time step,
12560     * after the specified amount of time elapses.
12561     * The runnable will be run on the user interface thread.</p>
12562     *
12563     * @param action The Runnable that will be executed.
12564     * @param delayMillis The delay (in milliseconds) until the Runnable
12565     *        will be executed.
12566     *
12567     * @see #postOnAnimation
12568     * @see #removeCallbacks
12569     */
12570    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12571        final AttachInfo attachInfo = mAttachInfo;
12572        if (attachInfo != null) {
12573            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12574                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12575        } else {
12576            // Assume that post will succeed later
12577            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12578        }
12579    }
12580
12581    /**
12582     * <p>Removes the specified Runnable from the message queue.</p>
12583     *
12584     * @param action The Runnable to remove from the message handling queue
12585     *
12586     * @return true if this view could ask the Handler to remove the Runnable,
12587     *         false otherwise. When the returned value is true, the Runnable
12588     *         may or may not have been actually removed from the message queue
12589     *         (for instance, if the Runnable was not in the queue already.)
12590     *
12591     * @see #post
12592     * @see #postDelayed
12593     * @see #postOnAnimation
12594     * @see #postOnAnimationDelayed
12595     */
12596    public boolean removeCallbacks(Runnable action) {
12597        if (action != null) {
12598            final AttachInfo attachInfo = mAttachInfo;
12599            if (attachInfo != null) {
12600                attachInfo.mHandler.removeCallbacks(action);
12601                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12602                        Choreographer.CALLBACK_ANIMATION, action, null);
12603            }
12604            // Assume that post will succeed later
12605            ViewRootImpl.getRunQueue().removeCallbacks(action);
12606        }
12607        return true;
12608    }
12609
12610    /**
12611     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12612     * Use this to invalidate the View from a non-UI thread.</p>
12613     *
12614     * <p>This method can be invoked from outside of the UI thread
12615     * only when this View is attached to a window.</p>
12616     *
12617     * @see #invalidate()
12618     * @see #postInvalidateDelayed(long)
12619     */
12620    public void postInvalidate() {
12621        postInvalidateDelayed(0);
12622    }
12623
12624    /**
12625     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12626     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12627     *
12628     * <p>This method can be invoked from outside of the UI thread
12629     * only when this View is attached to a window.</p>
12630     *
12631     * @param left The left coordinate of the rectangle to invalidate.
12632     * @param top The top coordinate of the rectangle to invalidate.
12633     * @param right The right coordinate of the rectangle to invalidate.
12634     * @param bottom The bottom coordinate of the rectangle to invalidate.
12635     *
12636     * @see #invalidate(int, int, int, int)
12637     * @see #invalidate(Rect)
12638     * @see #postInvalidateDelayed(long, int, int, int, int)
12639     */
12640    public void postInvalidate(int left, int top, int right, int bottom) {
12641        postInvalidateDelayed(0, left, top, right, bottom);
12642    }
12643
12644    /**
12645     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12646     * loop. Waits for the specified amount of time.</p>
12647     *
12648     * <p>This method can be invoked from outside of the UI thread
12649     * only when this View is attached to a window.</p>
12650     *
12651     * @param delayMilliseconds the duration in milliseconds to delay the
12652     *         invalidation by
12653     *
12654     * @see #invalidate()
12655     * @see #postInvalidate()
12656     */
12657    public void postInvalidateDelayed(long delayMilliseconds) {
12658        // We try only with the AttachInfo because there's no point in invalidating
12659        // if we are not attached to our window
12660        final AttachInfo attachInfo = mAttachInfo;
12661        if (attachInfo != null) {
12662            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12663        }
12664    }
12665
12666    /**
12667     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12668     * through the event loop. Waits for the specified amount of time.</p>
12669     *
12670     * <p>This method can be invoked from outside of the UI thread
12671     * only when this View is attached to a window.</p>
12672     *
12673     * @param delayMilliseconds the duration in milliseconds to delay the
12674     *         invalidation by
12675     * @param left The left coordinate of the rectangle to invalidate.
12676     * @param top The top coordinate of the rectangle to invalidate.
12677     * @param right The right coordinate of the rectangle to invalidate.
12678     * @param bottom The bottom coordinate of the rectangle to invalidate.
12679     *
12680     * @see #invalidate(int, int, int, int)
12681     * @see #invalidate(Rect)
12682     * @see #postInvalidate(int, int, int, int)
12683     */
12684    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12685            int right, int bottom) {
12686
12687        // We try only with the AttachInfo because there's no point in invalidating
12688        // if we are not attached to our window
12689        final AttachInfo attachInfo = mAttachInfo;
12690        if (attachInfo != null) {
12691            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12692            info.target = this;
12693            info.left = left;
12694            info.top = top;
12695            info.right = right;
12696            info.bottom = bottom;
12697
12698            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12699        }
12700    }
12701
12702    /**
12703     * <p>Cause an invalidate to happen on the next animation time step, typically the
12704     * next display frame.</p>
12705     *
12706     * <p>This method can be invoked from outside of the UI thread
12707     * only when this View is attached to a window.</p>
12708     *
12709     * @see #invalidate()
12710     */
12711    public void postInvalidateOnAnimation() {
12712        // We try only with the AttachInfo because there's no point in invalidating
12713        // if we are not attached to our window
12714        final AttachInfo attachInfo = mAttachInfo;
12715        if (attachInfo != null) {
12716            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12717        }
12718    }
12719
12720    /**
12721     * <p>Cause an invalidate of the specified area to happen on the next animation
12722     * time step, typically the next display frame.</p>
12723     *
12724     * <p>This method can be invoked from outside of the UI thread
12725     * only when this View is attached to a window.</p>
12726     *
12727     * @param left The left coordinate of the rectangle to invalidate.
12728     * @param top The top coordinate of the rectangle to invalidate.
12729     * @param right The right coordinate of the rectangle to invalidate.
12730     * @param bottom The bottom coordinate of the rectangle to invalidate.
12731     *
12732     * @see #invalidate(int, int, int, int)
12733     * @see #invalidate(Rect)
12734     */
12735    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12736        // We try only with the AttachInfo because there's no point in invalidating
12737        // if we are not attached to our window
12738        final AttachInfo attachInfo = mAttachInfo;
12739        if (attachInfo != null) {
12740            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12741            info.target = this;
12742            info.left = left;
12743            info.top = top;
12744            info.right = right;
12745            info.bottom = bottom;
12746
12747            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12748        }
12749    }
12750
12751    /**
12752     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12753     * This event is sent at most once every
12754     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12755     */
12756    private void postSendViewScrolledAccessibilityEventCallback() {
12757        if (mSendViewScrolledAccessibilityEvent == null) {
12758            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12759        }
12760        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12761            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12762            postDelayed(mSendViewScrolledAccessibilityEvent,
12763                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12764        }
12765    }
12766
12767    /**
12768     * Called by a parent to request that a child update its values for mScrollX
12769     * and mScrollY if necessary. This will typically be done if the child is
12770     * animating a scroll using a {@link android.widget.Scroller Scroller}
12771     * object.
12772     */
12773    public void computeScroll() {
12774    }
12775
12776    /**
12777     * <p>Indicate whether the horizontal edges are faded when the view is
12778     * scrolled horizontally.</p>
12779     *
12780     * @return true if the horizontal edges should are faded on scroll, false
12781     *         otherwise
12782     *
12783     * @see #setHorizontalFadingEdgeEnabled(boolean)
12784     *
12785     * @attr ref android.R.styleable#View_requiresFadingEdge
12786     */
12787    public boolean isHorizontalFadingEdgeEnabled() {
12788        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12789    }
12790
12791    /**
12792     * <p>Define whether the horizontal edges should be faded when this view
12793     * is scrolled horizontally.</p>
12794     *
12795     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12796     *                                    be faded when the view is scrolled
12797     *                                    horizontally
12798     *
12799     * @see #isHorizontalFadingEdgeEnabled()
12800     *
12801     * @attr ref android.R.styleable#View_requiresFadingEdge
12802     */
12803    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12804        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12805            if (horizontalFadingEdgeEnabled) {
12806                initScrollCache();
12807            }
12808
12809            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12810        }
12811    }
12812
12813    /**
12814     * <p>Indicate whether the vertical edges are faded when the view is
12815     * scrolled horizontally.</p>
12816     *
12817     * @return true if the vertical edges should are faded on scroll, false
12818     *         otherwise
12819     *
12820     * @see #setVerticalFadingEdgeEnabled(boolean)
12821     *
12822     * @attr ref android.R.styleable#View_requiresFadingEdge
12823     */
12824    public boolean isVerticalFadingEdgeEnabled() {
12825        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12826    }
12827
12828    /**
12829     * <p>Define whether the vertical edges should be faded when this view
12830     * is scrolled vertically.</p>
12831     *
12832     * @param verticalFadingEdgeEnabled true if the vertical edges should
12833     *                                  be faded when the view is scrolled
12834     *                                  vertically
12835     *
12836     * @see #isVerticalFadingEdgeEnabled()
12837     *
12838     * @attr ref android.R.styleable#View_requiresFadingEdge
12839     */
12840    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12841        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12842            if (verticalFadingEdgeEnabled) {
12843                initScrollCache();
12844            }
12845
12846            mViewFlags ^= FADING_EDGE_VERTICAL;
12847        }
12848    }
12849
12850    /**
12851     * Returns the strength, or intensity, of the top faded edge. The strength is
12852     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12853     * returns 0.0 or 1.0 but no value in between.
12854     *
12855     * Subclasses should override this method to provide a smoother fade transition
12856     * when scrolling occurs.
12857     *
12858     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12859     */
12860    protected float getTopFadingEdgeStrength() {
12861        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12862    }
12863
12864    /**
12865     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12866     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12867     * returns 0.0 or 1.0 but no value in between.
12868     *
12869     * Subclasses should override this method to provide a smoother fade transition
12870     * when scrolling occurs.
12871     *
12872     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12873     */
12874    protected float getBottomFadingEdgeStrength() {
12875        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12876                computeVerticalScrollRange() ? 1.0f : 0.0f;
12877    }
12878
12879    /**
12880     * Returns the strength, or intensity, of the left faded edge. The strength is
12881     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12882     * returns 0.0 or 1.0 but no value in between.
12883     *
12884     * Subclasses should override this method to provide a smoother fade transition
12885     * when scrolling occurs.
12886     *
12887     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12888     */
12889    protected float getLeftFadingEdgeStrength() {
12890        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12891    }
12892
12893    /**
12894     * Returns the strength, or intensity, of the right faded edge. The strength is
12895     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12896     * returns 0.0 or 1.0 but no value in between.
12897     *
12898     * Subclasses should override this method to provide a smoother fade transition
12899     * when scrolling occurs.
12900     *
12901     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12902     */
12903    protected float getRightFadingEdgeStrength() {
12904        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12905                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12906    }
12907
12908    /**
12909     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12910     * scrollbar is not drawn by default.</p>
12911     *
12912     * @return true if the horizontal scrollbar should be painted, false
12913     *         otherwise
12914     *
12915     * @see #setHorizontalScrollBarEnabled(boolean)
12916     */
12917    public boolean isHorizontalScrollBarEnabled() {
12918        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12919    }
12920
12921    /**
12922     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12923     * scrollbar is not drawn by default.</p>
12924     *
12925     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12926     *                                   be painted
12927     *
12928     * @see #isHorizontalScrollBarEnabled()
12929     */
12930    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12931        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12932            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12933            computeOpaqueFlags();
12934            resolvePadding();
12935        }
12936    }
12937
12938    /**
12939     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12940     * scrollbar is not drawn by default.</p>
12941     *
12942     * @return true if the vertical scrollbar should be painted, false
12943     *         otherwise
12944     *
12945     * @see #setVerticalScrollBarEnabled(boolean)
12946     */
12947    public boolean isVerticalScrollBarEnabled() {
12948        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12949    }
12950
12951    /**
12952     * <p>Define whether the vertical scrollbar should be drawn or not. The
12953     * scrollbar is not drawn by default.</p>
12954     *
12955     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12956     *                                 be painted
12957     *
12958     * @see #isVerticalScrollBarEnabled()
12959     */
12960    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12961        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12962            mViewFlags ^= SCROLLBARS_VERTICAL;
12963            computeOpaqueFlags();
12964            resolvePadding();
12965        }
12966    }
12967
12968    /**
12969     * @hide
12970     */
12971    protected void recomputePadding() {
12972        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12973    }
12974
12975    /**
12976     * Define whether scrollbars will fade when the view is not scrolling.
12977     *
12978     * @param fadeScrollbars whether to enable fading
12979     *
12980     * @attr ref android.R.styleable#View_fadeScrollbars
12981     */
12982    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12983        initScrollCache();
12984        final ScrollabilityCache scrollabilityCache = mScrollCache;
12985        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12986        if (fadeScrollbars) {
12987            scrollabilityCache.state = ScrollabilityCache.OFF;
12988        } else {
12989            scrollabilityCache.state = ScrollabilityCache.ON;
12990        }
12991    }
12992
12993    /**
12994     *
12995     * Returns true if scrollbars will fade when this view is not scrolling
12996     *
12997     * @return true if scrollbar fading is enabled
12998     *
12999     * @attr ref android.R.styleable#View_fadeScrollbars
13000     */
13001    public boolean isScrollbarFadingEnabled() {
13002        return mScrollCache != null && mScrollCache.fadeScrollBars;
13003    }
13004
13005    /**
13006     *
13007     * Returns the delay before scrollbars fade.
13008     *
13009     * @return the delay before scrollbars fade
13010     *
13011     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13012     */
13013    public int getScrollBarDefaultDelayBeforeFade() {
13014        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
13015                mScrollCache.scrollBarDefaultDelayBeforeFade;
13016    }
13017
13018    /**
13019     * Define the delay before scrollbars fade.
13020     *
13021     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
13022     *
13023     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13024     */
13025    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
13026        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
13027    }
13028
13029    /**
13030     *
13031     * Returns the scrollbar fade duration.
13032     *
13033     * @return the scrollbar fade duration
13034     *
13035     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13036     */
13037    public int getScrollBarFadeDuration() {
13038        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
13039                mScrollCache.scrollBarFadeDuration;
13040    }
13041
13042    /**
13043     * Define the scrollbar fade duration.
13044     *
13045     * @param scrollBarFadeDuration - the scrollbar fade duration
13046     *
13047     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13048     */
13049    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
13050        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
13051    }
13052
13053    /**
13054     *
13055     * Returns the scrollbar size.
13056     *
13057     * @return the scrollbar size
13058     *
13059     * @attr ref android.R.styleable#View_scrollbarSize
13060     */
13061    public int getScrollBarSize() {
13062        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
13063                mScrollCache.scrollBarSize;
13064    }
13065
13066    /**
13067     * Define the scrollbar size.
13068     *
13069     * @param scrollBarSize - the scrollbar size
13070     *
13071     * @attr ref android.R.styleable#View_scrollbarSize
13072     */
13073    public void setScrollBarSize(int scrollBarSize) {
13074        getScrollCache().scrollBarSize = scrollBarSize;
13075    }
13076
13077    /**
13078     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
13079     * inset. When inset, they add to the padding of the view. And the scrollbars
13080     * can be drawn inside the padding area or on the edge of the view. For example,
13081     * if a view has a background drawable and you want to draw the scrollbars
13082     * inside the padding specified by the drawable, you can use
13083     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
13084     * appear at the edge of the view, ignoring the padding, then you can use
13085     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
13086     * @param style the style of the scrollbars. Should be one of
13087     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
13088     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
13089     * @see #SCROLLBARS_INSIDE_OVERLAY
13090     * @see #SCROLLBARS_INSIDE_INSET
13091     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13092     * @see #SCROLLBARS_OUTSIDE_INSET
13093     *
13094     * @attr ref android.R.styleable#View_scrollbarStyle
13095     */
13096    public void setScrollBarStyle(@ScrollBarStyle int style) {
13097        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13098            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13099            computeOpaqueFlags();
13100            resolvePadding();
13101        }
13102    }
13103
13104    /**
13105     * <p>Returns the current scrollbar style.</p>
13106     * @return the current scrollbar style
13107     * @see #SCROLLBARS_INSIDE_OVERLAY
13108     * @see #SCROLLBARS_INSIDE_INSET
13109     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13110     * @see #SCROLLBARS_OUTSIDE_INSET
13111     *
13112     * @attr ref android.R.styleable#View_scrollbarStyle
13113     */
13114    @ViewDebug.ExportedProperty(mapping = {
13115            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13116            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13117            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13118            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13119    })
13120    @ScrollBarStyle
13121    public int getScrollBarStyle() {
13122        return mViewFlags & SCROLLBARS_STYLE_MASK;
13123    }
13124
13125    /**
13126     * <p>Compute the horizontal range that the horizontal scrollbar
13127     * represents.</p>
13128     *
13129     * <p>The range is expressed in arbitrary units that must be the same as the
13130     * units used by {@link #computeHorizontalScrollExtent()} and
13131     * {@link #computeHorizontalScrollOffset()}.</p>
13132     *
13133     * <p>The default range is the drawing width of this view.</p>
13134     *
13135     * @return the total horizontal range represented by the horizontal
13136     *         scrollbar
13137     *
13138     * @see #computeHorizontalScrollExtent()
13139     * @see #computeHorizontalScrollOffset()
13140     * @see android.widget.ScrollBarDrawable
13141     */
13142    protected int computeHorizontalScrollRange() {
13143        return getWidth();
13144    }
13145
13146    /**
13147     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13148     * within the horizontal range. This value is used to compute the position
13149     * of the thumb within the scrollbar's track.</p>
13150     *
13151     * <p>The range is expressed in arbitrary units that must be the same as the
13152     * units used by {@link #computeHorizontalScrollRange()} and
13153     * {@link #computeHorizontalScrollExtent()}.</p>
13154     *
13155     * <p>The default offset is the scroll offset of this view.</p>
13156     *
13157     * @return the horizontal offset of the scrollbar's thumb
13158     *
13159     * @see #computeHorizontalScrollRange()
13160     * @see #computeHorizontalScrollExtent()
13161     * @see android.widget.ScrollBarDrawable
13162     */
13163    protected int computeHorizontalScrollOffset() {
13164        return mScrollX;
13165    }
13166
13167    /**
13168     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13169     * within the horizontal range. This value is used to compute the length
13170     * of the thumb within the scrollbar's track.</p>
13171     *
13172     * <p>The range is expressed in arbitrary units that must be the same as the
13173     * units used by {@link #computeHorizontalScrollRange()} and
13174     * {@link #computeHorizontalScrollOffset()}.</p>
13175     *
13176     * <p>The default extent is the drawing width of this view.</p>
13177     *
13178     * @return the horizontal extent of the scrollbar's thumb
13179     *
13180     * @see #computeHorizontalScrollRange()
13181     * @see #computeHorizontalScrollOffset()
13182     * @see android.widget.ScrollBarDrawable
13183     */
13184    protected int computeHorizontalScrollExtent() {
13185        return getWidth();
13186    }
13187
13188    /**
13189     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13190     *
13191     * <p>The range is expressed in arbitrary units that must be the same as the
13192     * units used by {@link #computeVerticalScrollExtent()} and
13193     * {@link #computeVerticalScrollOffset()}.</p>
13194     *
13195     * @return the total vertical range represented by the vertical scrollbar
13196     *
13197     * <p>The default range is the drawing height of this view.</p>
13198     *
13199     * @see #computeVerticalScrollExtent()
13200     * @see #computeVerticalScrollOffset()
13201     * @see android.widget.ScrollBarDrawable
13202     */
13203    protected int computeVerticalScrollRange() {
13204        return getHeight();
13205    }
13206
13207    /**
13208     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13209     * within the horizontal range. This value is used to compute the position
13210     * of the thumb within the scrollbar's track.</p>
13211     *
13212     * <p>The range is expressed in arbitrary units that must be the same as the
13213     * units used by {@link #computeVerticalScrollRange()} and
13214     * {@link #computeVerticalScrollExtent()}.</p>
13215     *
13216     * <p>The default offset is the scroll offset of this view.</p>
13217     *
13218     * @return the vertical offset of the scrollbar's thumb
13219     *
13220     * @see #computeVerticalScrollRange()
13221     * @see #computeVerticalScrollExtent()
13222     * @see android.widget.ScrollBarDrawable
13223     */
13224    protected int computeVerticalScrollOffset() {
13225        return mScrollY;
13226    }
13227
13228    /**
13229     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13230     * within the vertical range. This value is used to compute the length
13231     * of the thumb within the scrollbar's track.</p>
13232     *
13233     * <p>The range is expressed in arbitrary units that must be the same as the
13234     * units used by {@link #computeVerticalScrollRange()} and
13235     * {@link #computeVerticalScrollOffset()}.</p>
13236     *
13237     * <p>The default extent is the drawing height of this view.</p>
13238     *
13239     * @return the vertical extent of the scrollbar's thumb
13240     *
13241     * @see #computeVerticalScrollRange()
13242     * @see #computeVerticalScrollOffset()
13243     * @see android.widget.ScrollBarDrawable
13244     */
13245    protected int computeVerticalScrollExtent() {
13246        return getHeight();
13247    }
13248
13249    /**
13250     * Check if this view can be scrolled horizontally in a certain direction.
13251     *
13252     * @param direction Negative to check scrolling left, positive to check scrolling right.
13253     * @return true if this view can be scrolled in the specified direction, false otherwise.
13254     */
13255    public boolean canScrollHorizontally(int direction) {
13256        final int offset = computeHorizontalScrollOffset();
13257        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13258        if (range == 0) return false;
13259        if (direction < 0) {
13260            return offset > 0;
13261        } else {
13262            return offset < range - 1;
13263        }
13264    }
13265
13266    /**
13267     * Check if this view can be scrolled vertically in a certain direction.
13268     *
13269     * @param direction Negative to check scrolling up, positive to check scrolling down.
13270     * @return true if this view can be scrolled in the specified direction, false otherwise.
13271     */
13272    public boolean canScrollVertically(int direction) {
13273        final int offset = computeVerticalScrollOffset();
13274        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13275        if (range == 0) return false;
13276        if (direction < 0) {
13277            return offset > 0;
13278        } else {
13279            return offset < range - 1;
13280        }
13281    }
13282
13283    /**
13284     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13285     * scrollbars are painted only if they have been awakened first.</p>
13286     *
13287     * @param canvas the canvas on which to draw the scrollbars
13288     *
13289     * @see #awakenScrollBars(int)
13290     */
13291    protected final void onDrawScrollBars(Canvas canvas) {
13292        // scrollbars are drawn only when the animation is running
13293        final ScrollabilityCache cache = mScrollCache;
13294        if (cache != null) {
13295
13296            int state = cache.state;
13297
13298            if (state == ScrollabilityCache.OFF) {
13299                return;
13300            }
13301
13302            boolean invalidate = false;
13303
13304            if (state == ScrollabilityCache.FADING) {
13305                // We're fading -- get our fade interpolation
13306                if (cache.interpolatorValues == null) {
13307                    cache.interpolatorValues = new float[1];
13308                }
13309
13310                float[] values = cache.interpolatorValues;
13311
13312                // Stops the animation if we're done
13313                if (cache.scrollBarInterpolator.timeToValues(values) ==
13314                        Interpolator.Result.FREEZE_END) {
13315                    cache.state = ScrollabilityCache.OFF;
13316                } else {
13317                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13318                }
13319
13320                // This will make the scroll bars inval themselves after
13321                // drawing. We only want this when we're fading so that
13322                // we prevent excessive redraws
13323                invalidate = true;
13324            } else {
13325                // We're just on -- but we may have been fading before so
13326                // reset alpha
13327                cache.scrollBar.mutate().setAlpha(255);
13328            }
13329
13330
13331            final int viewFlags = mViewFlags;
13332
13333            final boolean drawHorizontalScrollBar =
13334                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13335            final boolean drawVerticalScrollBar =
13336                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13337                && !isVerticalScrollBarHidden();
13338
13339            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13340                final int width = mRight - mLeft;
13341                final int height = mBottom - mTop;
13342
13343                final ScrollBarDrawable scrollBar = cache.scrollBar;
13344
13345                final int scrollX = mScrollX;
13346                final int scrollY = mScrollY;
13347                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13348
13349                int left;
13350                int top;
13351                int right;
13352                int bottom;
13353
13354                if (drawHorizontalScrollBar) {
13355                    int size = scrollBar.getSize(false);
13356                    if (size <= 0) {
13357                        size = cache.scrollBarSize;
13358                    }
13359
13360                    scrollBar.setParameters(computeHorizontalScrollRange(),
13361                                            computeHorizontalScrollOffset(),
13362                                            computeHorizontalScrollExtent(), false);
13363                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13364                            getVerticalScrollbarWidth() : 0;
13365                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13366                    left = scrollX + (mPaddingLeft & inside);
13367                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13368                    bottom = top + size;
13369                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13370                    if (invalidate) {
13371                        invalidate(left, top, right, bottom);
13372                    }
13373                }
13374
13375                if (drawVerticalScrollBar) {
13376                    int size = scrollBar.getSize(true);
13377                    if (size <= 0) {
13378                        size = cache.scrollBarSize;
13379                    }
13380
13381                    scrollBar.setParameters(computeVerticalScrollRange(),
13382                                            computeVerticalScrollOffset(),
13383                                            computeVerticalScrollExtent(), true);
13384                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13385                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13386                        verticalScrollbarPosition = isLayoutRtl() ?
13387                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13388                    }
13389                    switch (verticalScrollbarPosition) {
13390                        default:
13391                        case SCROLLBAR_POSITION_RIGHT:
13392                            left = scrollX + width - size - (mUserPaddingRight & inside);
13393                            break;
13394                        case SCROLLBAR_POSITION_LEFT:
13395                            left = scrollX + (mUserPaddingLeft & inside);
13396                            break;
13397                    }
13398                    top = scrollY + (mPaddingTop & inside);
13399                    right = left + size;
13400                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13401                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13402                    if (invalidate) {
13403                        invalidate(left, top, right, bottom);
13404                    }
13405                }
13406            }
13407        }
13408    }
13409
13410    /**
13411     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13412     * FastScroller is visible.
13413     * @return whether to temporarily hide the vertical scrollbar
13414     * @hide
13415     */
13416    protected boolean isVerticalScrollBarHidden() {
13417        return false;
13418    }
13419
13420    /**
13421     * <p>Draw the horizontal scrollbar if
13422     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13423     *
13424     * @param canvas the canvas on which to draw the scrollbar
13425     * @param scrollBar the scrollbar's drawable
13426     *
13427     * @see #isHorizontalScrollBarEnabled()
13428     * @see #computeHorizontalScrollRange()
13429     * @see #computeHorizontalScrollExtent()
13430     * @see #computeHorizontalScrollOffset()
13431     * @see android.widget.ScrollBarDrawable
13432     * @hide
13433     */
13434    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13435            int l, int t, int r, int b) {
13436        scrollBar.setBounds(l, t, r, b);
13437        scrollBar.draw(canvas);
13438    }
13439
13440    /**
13441     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13442     * returns true.</p>
13443     *
13444     * @param canvas the canvas on which to draw the scrollbar
13445     * @param scrollBar the scrollbar's drawable
13446     *
13447     * @see #isVerticalScrollBarEnabled()
13448     * @see #computeVerticalScrollRange()
13449     * @see #computeVerticalScrollExtent()
13450     * @see #computeVerticalScrollOffset()
13451     * @see android.widget.ScrollBarDrawable
13452     * @hide
13453     */
13454    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13455            int l, int t, int r, int b) {
13456        scrollBar.setBounds(l, t, r, b);
13457        scrollBar.draw(canvas);
13458    }
13459
13460    /**
13461     * Implement this to do your drawing.
13462     *
13463     * @param canvas the canvas on which the background will be drawn
13464     */
13465    protected void onDraw(Canvas canvas) {
13466    }
13467
13468    /*
13469     * Caller is responsible for calling requestLayout if necessary.
13470     * (This allows addViewInLayout to not request a new layout.)
13471     */
13472    void assignParent(ViewParent parent) {
13473        if (mParent == null) {
13474            mParent = parent;
13475        } else if (parent == null) {
13476            mParent = null;
13477        } else {
13478            throw new RuntimeException("view " + this + " being added, but"
13479                    + " it already has a parent");
13480        }
13481    }
13482
13483    /**
13484     * This is called when the view is attached to a window.  At this point it
13485     * has a Surface and will start drawing.  Note that this function is
13486     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13487     * however it may be called any time before the first onDraw -- including
13488     * before or after {@link #onMeasure(int, int)}.
13489     *
13490     * @see #onDetachedFromWindow()
13491     */
13492    @CallSuper
13493    protected void onAttachedToWindow() {
13494        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13495            mParent.requestTransparentRegion(this);
13496        }
13497
13498        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13499            initialAwakenScrollBars();
13500            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13501        }
13502
13503        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13504
13505        jumpDrawablesToCurrentState();
13506
13507        resetSubtreeAccessibilityStateChanged();
13508
13509        // rebuild, since Outline not maintained while View is detached
13510        rebuildOutline();
13511
13512        if (isFocused()) {
13513            InputMethodManager imm = InputMethodManager.peekInstance();
13514            if (imm != null) {
13515                imm.focusIn(this);
13516            }
13517        }
13518    }
13519
13520    /**
13521     * Resolve all RTL related properties.
13522     *
13523     * @return true if resolution of RTL properties has been done
13524     *
13525     * @hide
13526     */
13527    public boolean resolveRtlPropertiesIfNeeded() {
13528        if (!needRtlPropertiesResolution()) return false;
13529
13530        // Order is important here: LayoutDirection MUST be resolved first
13531        if (!isLayoutDirectionResolved()) {
13532            resolveLayoutDirection();
13533            resolveLayoutParams();
13534        }
13535        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13536        if (!isTextDirectionResolved()) {
13537            resolveTextDirection();
13538        }
13539        if (!isTextAlignmentResolved()) {
13540            resolveTextAlignment();
13541        }
13542        // Should resolve Drawables before Padding because we need the layout direction of the
13543        // Drawable to correctly resolve Padding.
13544        if (!areDrawablesResolved()) {
13545            resolveDrawables();
13546        }
13547        if (!isPaddingResolved()) {
13548            resolvePadding();
13549        }
13550        onRtlPropertiesChanged(getLayoutDirection());
13551        return true;
13552    }
13553
13554    /**
13555     * Reset resolution of all RTL related properties.
13556     *
13557     * @hide
13558     */
13559    public void resetRtlProperties() {
13560        resetResolvedLayoutDirection();
13561        resetResolvedTextDirection();
13562        resetResolvedTextAlignment();
13563        resetResolvedPadding();
13564        resetResolvedDrawables();
13565    }
13566
13567    /**
13568     * @see #onScreenStateChanged(int)
13569     */
13570    void dispatchScreenStateChanged(int screenState) {
13571        onScreenStateChanged(screenState);
13572    }
13573
13574    /**
13575     * This method is called whenever the state of the screen this view is
13576     * attached to changes. A state change will usually occurs when the screen
13577     * turns on or off (whether it happens automatically or the user does it
13578     * manually.)
13579     *
13580     * @param screenState The new state of the screen. Can be either
13581     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13582     */
13583    public void onScreenStateChanged(int screenState) {
13584    }
13585
13586    /**
13587     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13588     */
13589    private boolean hasRtlSupport() {
13590        return mContext.getApplicationInfo().hasRtlSupport();
13591    }
13592
13593    /**
13594     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13595     * RTL not supported)
13596     */
13597    private boolean isRtlCompatibilityMode() {
13598        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13599        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13600    }
13601
13602    /**
13603     * @return true if RTL properties need resolution.
13604     *
13605     */
13606    private boolean needRtlPropertiesResolution() {
13607        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13608    }
13609
13610    /**
13611     * Called when any RTL property (layout direction or text direction or text alignment) has
13612     * been changed.
13613     *
13614     * Subclasses need to override this method to take care of cached information that depends on the
13615     * resolved layout direction, or to inform child views that inherit their layout direction.
13616     *
13617     * The default implementation does nothing.
13618     *
13619     * @param layoutDirection the direction of the layout
13620     *
13621     * @see #LAYOUT_DIRECTION_LTR
13622     * @see #LAYOUT_DIRECTION_RTL
13623     */
13624    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13625    }
13626
13627    /**
13628     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13629     * that the parent directionality can and will be resolved before its children.
13630     *
13631     * @return true if resolution has been done, false otherwise.
13632     *
13633     * @hide
13634     */
13635    public boolean resolveLayoutDirection() {
13636        // Clear any previous layout direction resolution
13637        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13638
13639        if (hasRtlSupport()) {
13640            // Set resolved depending on layout direction
13641            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13642                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13643                case LAYOUT_DIRECTION_INHERIT:
13644                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13645                    // later to get the correct resolved value
13646                    if (!canResolveLayoutDirection()) return false;
13647
13648                    // Parent has not yet resolved, LTR is still the default
13649                    try {
13650                        if (!mParent.isLayoutDirectionResolved()) return false;
13651
13652                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13653                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13654                        }
13655                    } catch (AbstractMethodError e) {
13656                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13657                                " does not fully implement ViewParent", e);
13658                    }
13659                    break;
13660                case LAYOUT_DIRECTION_RTL:
13661                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13662                    break;
13663                case LAYOUT_DIRECTION_LOCALE:
13664                    if((LAYOUT_DIRECTION_RTL ==
13665                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13666                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13667                    }
13668                    break;
13669                default:
13670                    // Nothing to do, LTR by default
13671            }
13672        }
13673
13674        // Set to resolved
13675        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13676        return true;
13677    }
13678
13679    /**
13680     * Check if layout direction resolution can be done.
13681     *
13682     * @return true if layout direction resolution can be done otherwise return false.
13683     */
13684    public boolean canResolveLayoutDirection() {
13685        switch (getRawLayoutDirection()) {
13686            case LAYOUT_DIRECTION_INHERIT:
13687                if (mParent != null) {
13688                    try {
13689                        return mParent.canResolveLayoutDirection();
13690                    } catch (AbstractMethodError e) {
13691                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13692                                " does not fully implement ViewParent", e);
13693                    }
13694                }
13695                return false;
13696
13697            default:
13698                return true;
13699        }
13700    }
13701
13702    /**
13703     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13704     * {@link #onMeasure(int, int)}.
13705     *
13706     * @hide
13707     */
13708    public void resetResolvedLayoutDirection() {
13709        // Reset the current resolved bits
13710        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13711    }
13712
13713    /**
13714     * @return true if the layout direction is inherited.
13715     *
13716     * @hide
13717     */
13718    public boolean isLayoutDirectionInherited() {
13719        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13720    }
13721
13722    /**
13723     * @return true if layout direction has been resolved.
13724     */
13725    public boolean isLayoutDirectionResolved() {
13726        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13727    }
13728
13729    /**
13730     * Return if padding has been resolved
13731     *
13732     * @hide
13733     */
13734    boolean isPaddingResolved() {
13735        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13736    }
13737
13738    /**
13739     * Resolves padding depending on layout direction, if applicable, and
13740     * recomputes internal padding values to adjust for scroll bars.
13741     *
13742     * @hide
13743     */
13744    public void resolvePadding() {
13745        final int resolvedLayoutDirection = getLayoutDirection();
13746
13747        if (!isRtlCompatibilityMode()) {
13748            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13749            // If start / end padding are defined, they will be resolved (hence overriding) to
13750            // left / right or right / left depending on the resolved layout direction.
13751            // If start / end padding are not defined, use the left / right ones.
13752            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13753                Rect padding = sThreadLocal.get();
13754                if (padding == null) {
13755                    padding = new Rect();
13756                    sThreadLocal.set(padding);
13757                }
13758                mBackground.getPadding(padding);
13759                if (!mLeftPaddingDefined) {
13760                    mUserPaddingLeftInitial = padding.left;
13761                }
13762                if (!mRightPaddingDefined) {
13763                    mUserPaddingRightInitial = padding.right;
13764                }
13765            }
13766            switch (resolvedLayoutDirection) {
13767                case LAYOUT_DIRECTION_RTL:
13768                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13769                        mUserPaddingRight = mUserPaddingStart;
13770                    } else {
13771                        mUserPaddingRight = mUserPaddingRightInitial;
13772                    }
13773                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13774                        mUserPaddingLeft = mUserPaddingEnd;
13775                    } else {
13776                        mUserPaddingLeft = mUserPaddingLeftInitial;
13777                    }
13778                    break;
13779                case LAYOUT_DIRECTION_LTR:
13780                default:
13781                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13782                        mUserPaddingLeft = mUserPaddingStart;
13783                    } else {
13784                        mUserPaddingLeft = mUserPaddingLeftInitial;
13785                    }
13786                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13787                        mUserPaddingRight = mUserPaddingEnd;
13788                    } else {
13789                        mUserPaddingRight = mUserPaddingRightInitial;
13790                    }
13791            }
13792
13793            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13794        }
13795
13796        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13797        onRtlPropertiesChanged(resolvedLayoutDirection);
13798
13799        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13800    }
13801
13802    /**
13803     * Reset the resolved layout direction.
13804     *
13805     * @hide
13806     */
13807    public void resetResolvedPadding() {
13808        resetResolvedPaddingInternal();
13809    }
13810
13811    /**
13812     * Used when we only want to reset *this* view's padding and not trigger overrides
13813     * in ViewGroup that reset children too.
13814     */
13815    void resetResolvedPaddingInternal() {
13816        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13817    }
13818
13819    /**
13820     * This is called when the view is detached from a window.  At this point it
13821     * no longer has a surface for drawing.
13822     *
13823     * @see #onAttachedToWindow()
13824     */
13825    @CallSuper
13826    protected void onDetachedFromWindow() {
13827    }
13828
13829    /**
13830     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13831     * after onDetachedFromWindow().
13832     *
13833     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13834     * The super method should be called at the end of the overridden method to ensure
13835     * subclasses are destroyed first
13836     *
13837     * @hide
13838     */
13839    @CallSuper
13840    protected void onDetachedFromWindowInternal() {
13841        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13842        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13843
13844        removeUnsetPressCallback();
13845        removeLongPressCallback();
13846        removePerformClickCallback();
13847        removeSendViewScrolledAccessibilityEventCallback();
13848        stopNestedScroll();
13849
13850        // Anything that started animating right before detach should already
13851        // be in its final state when re-attached.
13852        jumpDrawablesToCurrentState();
13853
13854        destroyDrawingCache();
13855
13856        cleanupDraw();
13857        mCurrentAnimation = null;
13858    }
13859
13860    private void cleanupDraw() {
13861        resetDisplayList();
13862        if (mAttachInfo != null) {
13863            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13864        }
13865    }
13866
13867    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13868    }
13869
13870    /**
13871     * @return The number of times this view has been attached to a window
13872     */
13873    protected int getWindowAttachCount() {
13874        return mWindowAttachCount;
13875    }
13876
13877    /**
13878     * Retrieve a unique token identifying the window this view is attached to.
13879     * @return Return the window's token for use in
13880     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13881     */
13882    public IBinder getWindowToken() {
13883        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13884    }
13885
13886    /**
13887     * Retrieve the {@link WindowId} for the window this view is
13888     * currently attached to.
13889     */
13890    public WindowId getWindowId() {
13891        if (mAttachInfo == null) {
13892            return null;
13893        }
13894        if (mAttachInfo.mWindowId == null) {
13895            try {
13896                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13897                        mAttachInfo.mWindowToken);
13898                mAttachInfo.mWindowId = new WindowId(
13899                        mAttachInfo.mIWindowId);
13900            } catch (RemoteException e) {
13901            }
13902        }
13903        return mAttachInfo.mWindowId;
13904    }
13905
13906    /**
13907     * Retrieve a unique token identifying the top-level "real" window of
13908     * the window that this view is attached to.  That is, this is like
13909     * {@link #getWindowToken}, except if the window this view in is a panel
13910     * window (attached to another containing window), then the token of
13911     * the containing window is returned instead.
13912     *
13913     * @return Returns the associated window token, either
13914     * {@link #getWindowToken()} or the containing window's token.
13915     */
13916    public IBinder getApplicationWindowToken() {
13917        AttachInfo ai = mAttachInfo;
13918        if (ai != null) {
13919            IBinder appWindowToken = ai.mPanelParentWindowToken;
13920            if (appWindowToken == null) {
13921                appWindowToken = ai.mWindowToken;
13922            }
13923            return appWindowToken;
13924        }
13925        return null;
13926    }
13927
13928    /**
13929     * Gets the logical display to which the view's window has been attached.
13930     *
13931     * @return The logical display, or null if the view is not currently attached to a window.
13932     */
13933    public Display getDisplay() {
13934        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13935    }
13936
13937    /**
13938     * Retrieve private session object this view hierarchy is using to
13939     * communicate with the window manager.
13940     * @return the session object to communicate with the window manager
13941     */
13942    /*package*/ IWindowSession getWindowSession() {
13943        return mAttachInfo != null ? mAttachInfo.mSession : null;
13944    }
13945
13946    /**
13947     * @param info the {@link android.view.View.AttachInfo} to associated with
13948     *        this view
13949     */
13950    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13951        //System.out.println("Attached! " + this);
13952        mAttachInfo = info;
13953        if (mOverlay != null) {
13954            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13955        }
13956        mWindowAttachCount++;
13957        // We will need to evaluate the drawable state at least once.
13958        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13959        if (mFloatingTreeObserver != null) {
13960            info.mTreeObserver.merge(mFloatingTreeObserver);
13961            mFloatingTreeObserver = null;
13962        }
13963        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13964            mAttachInfo.mScrollContainers.add(this);
13965            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13966        }
13967        performCollectViewAttributes(mAttachInfo, visibility);
13968        onAttachedToWindow();
13969
13970        ListenerInfo li = mListenerInfo;
13971        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13972                li != null ? li.mOnAttachStateChangeListeners : null;
13973        if (listeners != null && listeners.size() > 0) {
13974            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13975            // perform the dispatching. The iterator is a safe guard against listeners that
13976            // could mutate the list by calling the various add/remove methods. This prevents
13977            // the array from being modified while we iterate it.
13978            for (OnAttachStateChangeListener listener : listeners) {
13979                listener.onViewAttachedToWindow(this);
13980            }
13981        }
13982
13983        int vis = info.mWindowVisibility;
13984        if (vis != GONE) {
13985            onWindowVisibilityChanged(vis);
13986        }
13987        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13988            // If nobody has evaluated the drawable state yet, then do it now.
13989            refreshDrawableState();
13990        }
13991        needGlobalAttributesUpdate(false);
13992    }
13993
13994    void dispatchDetachedFromWindow() {
13995        AttachInfo info = mAttachInfo;
13996        if (info != null) {
13997            int vis = info.mWindowVisibility;
13998            if (vis != GONE) {
13999                onWindowVisibilityChanged(GONE);
14000            }
14001        }
14002
14003        onDetachedFromWindow();
14004        onDetachedFromWindowInternal();
14005
14006        ListenerInfo li = mListenerInfo;
14007        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14008                li != null ? li.mOnAttachStateChangeListeners : null;
14009        if (listeners != null && listeners.size() > 0) {
14010            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14011            // perform the dispatching. The iterator is a safe guard against listeners that
14012            // could mutate the list by calling the various add/remove methods. This prevents
14013            // the array from being modified while we iterate it.
14014            for (OnAttachStateChangeListener listener : listeners) {
14015                listener.onViewDetachedFromWindow(this);
14016            }
14017        }
14018
14019        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
14020            mAttachInfo.mScrollContainers.remove(this);
14021            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
14022        }
14023
14024        mAttachInfo = null;
14025        if (mOverlay != null) {
14026            mOverlay.getOverlayView().dispatchDetachedFromWindow();
14027        }
14028    }
14029
14030    /**
14031     * Cancel any deferred high-level input events that were previously posted to the event queue.
14032     *
14033     * <p>Many views post high-level events such as click handlers to the event queue
14034     * to run deferred in order to preserve a desired user experience - clearing visible
14035     * pressed states before executing, etc. This method will abort any events of this nature
14036     * that are currently in flight.</p>
14037     *
14038     * <p>Custom views that generate their own high-level deferred input events should override
14039     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
14040     *
14041     * <p>This will also cancel pending input events for any child views.</p>
14042     *
14043     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
14044     * This will not impact newer events posted after this call that may occur as a result of
14045     * lower-level input events still waiting in the queue. If you are trying to prevent
14046     * double-submitted  events for the duration of some sort of asynchronous transaction
14047     * you should also take other steps to protect against unexpected double inputs e.g. calling
14048     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
14049     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
14050     */
14051    public final void cancelPendingInputEvents() {
14052        dispatchCancelPendingInputEvents();
14053    }
14054
14055    /**
14056     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
14057     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
14058     */
14059    void dispatchCancelPendingInputEvents() {
14060        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
14061        onCancelPendingInputEvents();
14062        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
14063            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
14064                    " did not call through to super.onCancelPendingInputEvents()");
14065        }
14066    }
14067
14068    /**
14069     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
14070     * a parent view.
14071     *
14072     * <p>This method is responsible for removing any pending high-level input events that were
14073     * posted to the event queue to run later. Custom view classes that post their own deferred
14074     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
14075     * {@link android.os.Handler} should override this method, call
14076     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
14077     * </p>
14078     */
14079    public void onCancelPendingInputEvents() {
14080        removePerformClickCallback();
14081        cancelLongPress();
14082        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
14083    }
14084
14085    /**
14086     * Store this view hierarchy's frozen state into the given container.
14087     *
14088     * @param container The SparseArray in which to save the view's state.
14089     *
14090     * @see #restoreHierarchyState(android.util.SparseArray)
14091     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14092     * @see #onSaveInstanceState()
14093     */
14094    public void saveHierarchyState(SparseArray<Parcelable> container) {
14095        dispatchSaveInstanceState(container);
14096    }
14097
14098    /**
14099     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14100     * this view and its children. May be overridden to modify how freezing happens to a
14101     * view's children; for example, some views may want to not store state for their children.
14102     *
14103     * @param container The SparseArray in which to save the view's state.
14104     *
14105     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14106     * @see #saveHierarchyState(android.util.SparseArray)
14107     * @see #onSaveInstanceState()
14108     */
14109    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14110        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14111            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14112            Parcelable state = onSaveInstanceState();
14113            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14114                throw new IllegalStateException(
14115                        "Derived class did not call super.onSaveInstanceState()");
14116            }
14117            if (state != null) {
14118                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14119                // + ": " + state);
14120                container.put(mID, state);
14121            }
14122        }
14123    }
14124
14125    /**
14126     * Hook allowing a view to generate a representation of its internal state
14127     * that can later be used to create a new instance with that same state.
14128     * This state should only contain information that is not persistent or can
14129     * not be reconstructed later. For example, you will never store your
14130     * current position on screen because that will be computed again when a
14131     * new instance of the view is placed in its view hierarchy.
14132     * <p>
14133     * Some examples of things you may store here: the current cursor position
14134     * in a text view (but usually not the text itself since that is stored in a
14135     * content provider or other persistent storage), the currently selected
14136     * item in a list view.
14137     *
14138     * @return Returns a Parcelable object containing the view's current dynamic
14139     *         state, or null if there is nothing interesting to save. The
14140     *         default implementation returns null.
14141     * @see #onRestoreInstanceState(android.os.Parcelable)
14142     * @see #saveHierarchyState(android.util.SparseArray)
14143     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14144     * @see #setSaveEnabled(boolean)
14145     */
14146    @CallSuper
14147    protected Parcelable onSaveInstanceState() {
14148        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14149        if (mStartActivityRequestWho != null) {
14150            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14151            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14152            return state;
14153        }
14154        return BaseSavedState.EMPTY_STATE;
14155    }
14156
14157    /**
14158     * Restore this view hierarchy's frozen state from the given container.
14159     *
14160     * @param container The SparseArray which holds previously frozen states.
14161     *
14162     * @see #saveHierarchyState(android.util.SparseArray)
14163     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14164     * @see #onRestoreInstanceState(android.os.Parcelable)
14165     */
14166    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14167        dispatchRestoreInstanceState(container);
14168    }
14169
14170    /**
14171     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14172     * state for this view and its children. May be overridden to modify how restoring
14173     * happens to a view's children; for example, some views may want to not store state
14174     * for their children.
14175     *
14176     * @param container The SparseArray which holds previously saved state.
14177     *
14178     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14179     * @see #restoreHierarchyState(android.util.SparseArray)
14180     * @see #onRestoreInstanceState(android.os.Parcelable)
14181     */
14182    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14183        if (mID != NO_ID) {
14184            Parcelable state = container.get(mID);
14185            if (state != null) {
14186                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14187                // + ": " + state);
14188                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14189                onRestoreInstanceState(state);
14190                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14191                    throw new IllegalStateException(
14192                            "Derived class did not call super.onRestoreInstanceState()");
14193                }
14194            }
14195        }
14196    }
14197
14198    /**
14199     * Hook allowing a view to re-apply a representation of its internal state that had previously
14200     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14201     * null state.
14202     *
14203     * @param state The frozen state that had previously been returned by
14204     *        {@link #onSaveInstanceState}.
14205     *
14206     * @see #onSaveInstanceState()
14207     * @see #restoreHierarchyState(android.util.SparseArray)
14208     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14209     */
14210    @CallSuper
14211    protected void onRestoreInstanceState(Parcelable state) {
14212        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14213        if (state != null && !(state instanceof AbsSavedState)) {
14214            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14215                    + "received " + state.getClass().toString() + " instead. This usually happens "
14216                    + "when two views of different type have the same id in the same hierarchy. "
14217                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14218                    + "other views do not use the same id.");
14219        }
14220        if (state != null && state instanceof BaseSavedState) {
14221            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14222        }
14223    }
14224
14225    /**
14226     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14227     *
14228     * @return the drawing start time in milliseconds
14229     */
14230    public long getDrawingTime() {
14231        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14232    }
14233
14234    /**
14235     * <p>Enables or disables the duplication of the parent's state into this view. When
14236     * duplication is enabled, this view gets its drawable state from its parent rather
14237     * than from its own internal properties.</p>
14238     *
14239     * <p>Note: in the current implementation, setting this property to true after the
14240     * view was added to a ViewGroup might have no effect at all. This property should
14241     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14242     *
14243     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14244     * property is enabled, an exception will be thrown.</p>
14245     *
14246     * <p>Note: if the child view uses and updates additional states which are unknown to the
14247     * parent, these states should not be affected by this method.</p>
14248     *
14249     * @param enabled True to enable duplication of the parent's drawable state, false
14250     *                to disable it.
14251     *
14252     * @see #getDrawableState()
14253     * @see #isDuplicateParentStateEnabled()
14254     */
14255    public void setDuplicateParentStateEnabled(boolean enabled) {
14256        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14257    }
14258
14259    /**
14260     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14261     *
14262     * @return True if this view's drawable state is duplicated from the parent,
14263     *         false otherwise
14264     *
14265     * @see #getDrawableState()
14266     * @see #setDuplicateParentStateEnabled(boolean)
14267     */
14268    public boolean isDuplicateParentStateEnabled() {
14269        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14270    }
14271
14272    /**
14273     * <p>Specifies the type of layer backing this view. The layer can be
14274     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14275     * {@link #LAYER_TYPE_HARDWARE}.</p>
14276     *
14277     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14278     * instance that controls how the layer is composed on screen. The following
14279     * properties of the paint are taken into account when composing the layer:</p>
14280     * <ul>
14281     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14282     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14283     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14284     * </ul>
14285     *
14286     * <p>If this view has an alpha value set to < 1.0 by calling
14287     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14288     * by this view's alpha value.</p>
14289     *
14290     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14291     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14292     * for more information on when and how to use layers.</p>
14293     *
14294     * @param layerType The type of layer to use with this view, must be one of
14295     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14296     *        {@link #LAYER_TYPE_HARDWARE}
14297     * @param paint The paint used to compose the layer. This argument is optional
14298     *        and can be null. It is ignored when the layer type is
14299     *        {@link #LAYER_TYPE_NONE}
14300     *
14301     * @see #getLayerType()
14302     * @see #LAYER_TYPE_NONE
14303     * @see #LAYER_TYPE_SOFTWARE
14304     * @see #LAYER_TYPE_HARDWARE
14305     * @see #setAlpha(float)
14306     *
14307     * @attr ref android.R.styleable#View_layerType
14308     */
14309    public void setLayerType(int layerType, Paint paint) {
14310        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14311            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14312                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14313        }
14314
14315        boolean typeChanged = mRenderNode.setLayerType(layerType);
14316
14317        if (!typeChanged) {
14318            setLayerPaint(paint);
14319            return;
14320        }
14321
14322        // Destroy any previous software drawing cache if needed
14323        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14324            destroyDrawingCache();
14325        }
14326
14327        mLayerType = layerType;
14328        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14329        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14330        mRenderNode.setLayerPaint(mLayerPaint);
14331
14332        // draw() behaves differently if we are on a layer, so we need to
14333        // invalidate() here
14334        invalidateParentCaches();
14335        invalidate(true);
14336    }
14337
14338    /**
14339     * Updates the {@link Paint} object used with the current layer (used only if the current
14340     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14341     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14342     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14343     * ensure that the view gets redrawn immediately.
14344     *
14345     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14346     * instance that controls how the layer is composed on screen. The following
14347     * properties of the paint are taken into account when composing the layer:</p>
14348     * <ul>
14349     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14350     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14351     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14352     * </ul>
14353     *
14354     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14355     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14356     *
14357     * @param paint The paint used to compose the layer. This argument is optional
14358     *        and can be null. It is ignored when the layer type is
14359     *        {@link #LAYER_TYPE_NONE}
14360     *
14361     * @see #setLayerType(int, android.graphics.Paint)
14362     */
14363    public void setLayerPaint(Paint paint) {
14364        int layerType = getLayerType();
14365        if (layerType != LAYER_TYPE_NONE) {
14366            mLayerPaint = paint == null ? new Paint() : paint;
14367            if (layerType == LAYER_TYPE_HARDWARE) {
14368                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14369                    invalidateViewProperty(false, false);
14370                }
14371            } else {
14372                invalidate();
14373            }
14374        }
14375    }
14376
14377    /**
14378     * Indicates what type of layer is currently associated with this view. By default
14379     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14380     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14381     * for more information on the different types of layers.
14382     *
14383     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14384     *         {@link #LAYER_TYPE_HARDWARE}
14385     *
14386     * @see #setLayerType(int, android.graphics.Paint)
14387     * @see #buildLayer()
14388     * @see #LAYER_TYPE_NONE
14389     * @see #LAYER_TYPE_SOFTWARE
14390     * @see #LAYER_TYPE_HARDWARE
14391     */
14392    public int getLayerType() {
14393        return mLayerType;
14394    }
14395
14396    /**
14397     * Forces this view's layer to be created and this view to be rendered
14398     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14399     * invoking this method will have no effect.
14400     *
14401     * This method can for instance be used to render a view into its layer before
14402     * starting an animation. If this view is complex, rendering into the layer
14403     * before starting the animation will avoid skipping frames.
14404     *
14405     * @throws IllegalStateException If this view is not attached to a window
14406     *
14407     * @see #setLayerType(int, android.graphics.Paint)
14408     */
14409    public void buildLayer() {
14410        if (mLayerType == LAYER_TYPE_NONE) return;
14411
14412        final AttachInfo attachInfo = mAttachInfo;
14413        if (attachInfo == null) {
14414            throw new IllegalStateException("This view must be attached to a window first");
14415        }
14416
14417        if (getWidth() == 0 || getHeight() == 0) {
14418            return;
14419        }
14420
14421        switch (mLayerType) {
14422            case LAYER_TYPE_HARDWARE:
14423                updateDisplayListIfDirty();
14424                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14425                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14426                }
14427                break;
14428            case LAYER_TYPE_SOFTWARE:
14429                buildDrawingCache(true);
14430                break;
14431        }
14432    }
14433
14434    /**
14435     * If this View draws with a HardwareLayer, returns it.
14436     * Otherwise returns null
14437     *
14438     * TODO: Only TextureView uses this, can we eliminate it?
14439     */
14440    HardwareLayer getHardwareLayer() {
14441        return null;
14442    }
14443
14444    /**
14445     * Destroys all hardware rendering resources. This method is invoked
14446     * when the system needs to reclaim resources. Upon execution of this
14447     * method, you should free any OpenGL resources created by the view.
14448     *
14449     * Note: you <strong>must</strong> call
14450     * <code>super.destroyHardwareResources()</code> when overriding
14451     * this method.
14452     *
14453     * @hide
14454     */
14455    @CallSuper
14456    protected void destroyHardwareResources() {
14457        // Although the Layer will be destroyed by RenderNode, we want to release
14458        // the staging display list, which is also a signal to RenderNode that it's
14459        // safe to free its copy of the display list as it knows that we will
14460        // push an updated DisplayList if we try to draw again
14461        resetDisplayList();
14462    }
14463
14464    /**
14465     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14466     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14467     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14468     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14469     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14470     * null.</p>
14471     *
14472     * <p>Enabling the drawing cache is similar to
14473     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14474     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14475     * drawing cache has no effect on rendering because the system uses a different mechanism
14476     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14477     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14478     * for information on how to enable software and hardware layers.</p>
14479     *
14480     * <p>This API can be used to manually generate
14481     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14482     * {@link #getDrawingCache()}.</p>
14483     *
14484     * @param enabled true to enable the drawing cache, false otherwise
14485     *
14486     * @see #isDrawingCacheEnabled()
14487     * @see #getDrawingCache()
14488     * @see #buildDrawingCache()
14489     * @see #setLayerType(int, android.graphics.Paint)
14490     */
14491    public void setDrawingCacheEnabled(boolean enabled) {
14492        mCachingFailed = false;
14493        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14494    }
14495
14496    /**
14497     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14498     *
14499     * @return true if the drawing cache is enabled
14500     *
14501     * @see #setDrawingCacheEnabled(boolean)
14502     * @see #getDrawingCache()
14503     */
14504    @ViewDebug.ExportedProperty(category = "drawing")
14505    public boolean isDrawingCacheEnabled() {
14506        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14507    }
14508
14509    /**
14510     * Debugging utility which recursively outputs the dirty state of a view and its
14511     * descendants.
14512     *
14513     * @hide
14514     */
14515    @SuppressWarnings({"UnusedDeclaration"})
14516    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14517        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14518                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14519                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14520                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14521        if (clear) {
14522            mPrivateFlags &= clearMask;
14523        }
14524        if (this instanceof ViewGroup) {
14525            ViewGroup parent = (ViewGroup) this;
14526            final int count = parent.getChildCount();
14527            for (int i = 0; i < count; i++) {
14528                final View child = parent.getChildAt(i);
14529                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14530            }
14531        }
14532    }
14533
14534    /**
14535     * This method is used by ViewGroup to cause its children to restore or recreate their
14536     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14537     * to recreate its own display list, which would happen if it went through the normal
14538     * draw/dispatchDraw mechanisms.
14539     *
14540     * @hide
14541     */
14542    protected void dispatchGetDisplayList() {}
14543
14544    /**
14545     * A view that is not attached or hardware accelerated cannot create a display list.
14546     * This method checks these conditions and returns the appropriate result.
14547     *
14548     * @return true if view has the ability to create a display list, false otherwise.
14549     *
14550     * @hide
14551     */
14552    public boolean canHaveDisplayList() {
14553        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14554    }
14555
14556    private void updateDisplayListIfDirty() {
14557        final RenderNode renderNode = mRenderNode;
14558        if (!canHaveDisplayList()) {
14559            // can't populate RenderNode, don't try
14560            return;
14561        }
14562
14563        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14564                || !renderNode.isValid()
14565                || (mRecreateDisplayList)) {
14566            // Don't need to recreate the display list, just need to tell our
14567            // children to restore/recreate theirs
14568            if (renderNode.isValid()
14569                    && !mRecreateDisplayList) {
14570                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14571                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14572                dispatchGetDisplayList();
14573
14574                return; // no work needed
14575            }
14576
14577            // If we got here, we're recreating it. Mark it as such to ensure that
14578            // we copy in child display lists into ours in drawChild()
14579            mRecreateDisplayList = true;
14580
14581            int width = mRight - mLeft;
14582            int height = mBottom - mTop;
14583            int layerType = getLayerType();
14584
14585            final DisplayListCanvas canvas = renderNode.start(width, height);
14586            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14587
14588            try {
14589                final HardwareLayer layer = getHardwareLayer();
14590                if (layer != null && layer.isValid()) {
14591                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14592                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14593                    buildDrawingCache(true);
14594                    Bitmap cache = getDrawingCache(true);
14595                    if (cache != null) {
14596                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14597                    }
14598                } else {
14599                    computeScroll();
14600
14601                    canvas.translate(-mScrollX, -mScrollY);
14602                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14603                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14604
14605                    // Fast path for layouts with no backgrounds
14606                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14607                        dispatchDraw(canvas);
14608                        if (mOverlay != null && !mOverlay.isEmpty()) {
14609                            mOverlay.getOverlayView().draw(canvas);
14610                        }
14611                    } else {
14612                        draw(canvas);
14613                    }
14614                }
14615            } finally {
14616                renderNode.end(canvas);
14617                setDisplayListProperties(renderNode);
14618            }
14619        } else {
14620            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14621            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14622        }
14623    }
14624
14625    /**
14626     * Returns a RenderNode with View draw content recorded, which can be
14627     * used to draw this view again without executing its draw method.
14628     *
14629     * @return A RenderNode ready to replay, or null if caching is not enabled.
14630     *
14631     * @hide
14632     */
14633    public RenderNode getDisplayList() {
14634        updateDisplayListIfDirty();
14635        return mRenderNode;
14636    }
14637
14638    private void resetDisplayList() {
14639        if (mRenderNode.isValid()) {
14640            mRenderNode.destroyDisplayListData();
14641        }
14642
14643        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14644            mBackgroundRenderNode.destroyDisplayListData();
14645        }
14646    }
14647
14648    /**
14649     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14650     *
14651     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14652     *
14653     * @see #getDrawingCache(boolean)
14654     */
14655    public Bitmap getDrawingCache() {
14656        return getDrawingCache(false);
14657    }
14658
14659    /**
14660     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14661     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14662     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14663     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14664     * request the drawing cache by calling this method and draw it on screen if the
14665     * returned bitmap is not null.</p>
14666     *
14667     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14668     * this method will create a bitmap of the same size as this view. Because this bitmap
14669     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14670     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14671     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14672     * size than the view. This implies that your application must be able to handle this
14673     * size.</p>
14674     *
14675     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14676     *        the current density of the screen when the application is in compatibility
14677     *        mode.
14678     *
14679     * @return A bitmap representing this view or null if cache is disabled.
14680     *
14681     * @see #setDrawingCacheEnabled(boolean)
14682     * @see #isDrawingCacheEnabled()
14683     * @see #buildDrawingCache(boolean)
14684     * @see #destroyDrawingCache()
14685     */
14686    public Bitmap getDrawingCache(boolean autoScale) {
14687        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14688            return null;
14689        }
14690        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14691            buildDrawingCache(autoScale);
14692        }
14693        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14694    }
14695
14696    /**
14697     * <p>Frees the resources used by the drawing cache. If you call
14698     * {@link #buildDrawingCache()} manually without calling
14699     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14700     * should cleanup the cache with this method afterwards.</p>
14701     *
14702     * @see #setDrawingCacheEnabled(boolean)
14703     * @see #buildDrawingCache()
14704     * @see #getDrawingCache()
14705     */
14706    public void destroyDrawingCache() {
14707        if (mDrawingCache != null) {
14708            mDrawingCache.recycle();
14709            mDrawingCache = null;
14710        }
14711        if (mUnscaledDrawingCache != null) {
14712            mUnscaledDrawingCache.recycle();
14713            mUnscaledDrawingCache = null;
14714        }
14715    }
14716
14717    /**
14718     * Setting a solid background color for the drawing cache's bitmaps will improve
14719     * performance and memory usage. Note, though that this should only be used if this
14720     * view will always be drawn on top of a solid color.
14721     *
14722     * @param color The background color to use for the drawing cache's bitmap
14723     *
14724     * @see #setDrawingCacheEnabled(boolean)
14725     * @see #buildDrawingCache()
14726     * @see #getDrawingCache()
14727     */
14728    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
14729        if (color != mDrawingCacheBackgroundColor) {
14730            mDrawingCacheBackgroundColor = color;
14731            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14732        }
14733    }
14734
14735    /**
14736     * @see #setDrawingCacheBackgroundColor(int)
14737     *
14738     * @return The background color to used for the drawing cache's bitmap
14739     */
14740    @ColorInt
14741    public int getDrawingCacheBackgroundColor() {
14742        return mDrawingCacheBackgroundColor;
14743    }
14744
14745    /**
14746     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14747     *
14748     * @see #buildDrawingCache(boolean)
14749     */
14750    public void buildDrawingCache() {
14751        buildDrawingCache(false);
14752    }
14753
14754    /**
14755     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14756     *
14757     * <p>If you call {@link #buildDrawingCache()} manually without calling
14758     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14759     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14760     *
14761     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14762     * this method will create a bitmap of the same size as this view. Because this bitmap
14763     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14764     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14765     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14766     * size than the view. This implies that your application must be able to handle this
14767     * size.</p>
14768     *
14769     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14770     * you do not need the drawing cache bitmap, calling this method will increase memory
14771     * usage and cause the view to be rendered in software once, thus negatively impacting
14772     * performance.</p>
14773     *
14774     * @see #getDrawingCache()
14775     * @see #destroyDrawingCache()
14776     */
14777    public void buildDrawingCache(boolean autoScale) {
14778        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14779                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14780            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14781                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14782                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14783            }
14784            try {
14785                buildDrawingCacheImpl(autoScale);
14786            } finally {
14787                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14788            }
14789        }
14790    }
14791
14792    /**
14793     * private, internal implementation of buildDrawingCache, used to enable tracing
14794     */
14795    private void buildDrawingCacheImpl(boolean autoScale) {
14796        mCachingFailed = false;
14797
14798        int width = mRight - mLeft;
14799        int height = mBottom - mTop;
14800
14801        final AttachInfo attachInfo = mAttachInfo;
14802        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14803
14804        if (autoScale && scalingRequired) {
14805            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14806            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14807        }
14808
14809        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14810        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14811        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14812
14813        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14814        final long drawingCacheSize =
14815                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14816        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14817            if (width > 0 && height > 0) {
14818                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14819                        + projectedBitmapSize + " bytes, only "
14820                        + drawingCacheSize + " available");
14821            }
14822            destroyDrawingCache();
14823            mCachingFailed = true;
14824            return;
14825        }
14826
14827        boolean clear = true;
14828        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14829
14830        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14831            Bitmap.Config quality;
14832            if (!opaque) {
14833                // Never pick ARGB_4444 because it looks awful
14834                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14835                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14836                    case DRAWING_CACHE_QUALITY_AUTO:
14837                    case DRAWING_CACHE_QUALITY_LOW:
14838                    case DRAWING_CACHE_QUALITY_HIGH:
14839                    default:
14840                        quality = Bitmap.Config.ARGB_8888;
14841                        break;
14842                }
14843            } else {
14844                // Optimization for translucent windows
14845                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14846                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14847            }
14848
14849            // Try to cleanup memory
14850            if (bitmap != null) bitmap.recycle();
14851
14852            try {
14853                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14854                        width, height, quality);
14855                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14856                if (autoScale) {
14857                    mDrawingCache = bitmap;
14858                } else {
14859                    mUnscaledDrawingCache = bitmap;
14860                }
14861                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14862            } catch (OutOfMemoryError e) {
14863                // If there is not enough memory to create the bitmap cache, just
14864                // ignore the issue as bitmap caches are not required to draw the
14865                // view hierarchy
14866                if (autoScale) {
14867                    mDrawingCache = null;
14868                } else {
14869                    mUnscaledDrawingCache = null;
14870                }
14871                mCachingFailed = true;
14872                return;
14873            }
14874
14875            clear = drawingCacheBackgroundColor != 0;
14876        }
14877
14878        Canvas canvas;
14879        if (attachInfo != null) {
14880            canvas = attachInfo.mCanvas;
14881            if (canvas == null) {
14882                canvas = new Canvas();
14883            }
14884            canvas.setBitmap(bitmap);
14885            // Temporarily clobber the cached Canvas in case one of our children
14886            // is also using a drawing cache. Without this, the children would
14887            // steal the canvas by attaching their own bitmap to it and bad, bad
14888            // thing would happen (invisible views, corrupted drawings, etc.)
14889            attachInfo.mCanvas = null;
14890        } else {
14891            // This case should hopefully never or seldom happen
14892            canvas = new Canvas(bitmap);
14893        }
14894
14895        if (clear) {
14896            bitmap.eraseColor(drawingCacheBackgroundColor);
14897        }
14898
14899        computeScroll();
14900        final int restoreCount = canvas.save();
14901
14902        if (autoScale && scalingRequired) {
14903            final float scale = attachInfo.mApplicationScale;
14904            canvas.scale(scale, scale);
14905        }
14906
14907        canvas.translate(-mScrollX, -mScrollY);
14908
14909        mPrivateFlags |= PFLAG_DRAWN;
14910        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14911                mLayerType != LAYER_TYPE_NONE) {
14912            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14913        }
14914
14915        // Fast path for layouts with no backgrounds
14916        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14917            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14918            dispatchDraw(canvas);
14919            if (mOverlay != null && !mOverlay.isEmpty()) {
14920                mOverlay.getOverlayView().draw(canvas);
14921            }
14922        } else {
14923            draw(canvas);
14924        }
14925
14926        canvas.restoreToCount(restoreCount);
14927        canvas.setBitmap(null);
14928
14929        if (attachInfo != null) {
14930            // Restore the cached Canvas for our siblings
14931            attachInfo.mCanvas = canvas;
14932        }
14933    }
14934
14935    /**
14936     * Create a snapshot of the view into a bitmap.  We should probably make
14937     * some form of this public, but should think about the API.
14938     */
14939    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14940        int width = mRight - mLeft;
14941        int height = mBottom - mTop;
14942
14943        final AttachInfo attachInfo = mAttachInfo;
14944        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14945        width = (int) ((width * scale) + 0.5f);
14946        height = (int) ((height * scale) + 0.5f);
14947
14948        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14949                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14950        if (bitmap == null) {
14951            throw new OutOfMemoryError();
14952        }
14953
14954        Resources resources = getResources();
14955        if (resources != null) {
14956            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14957        }
14958
14959        Canvas canvas;
14960        if (attachInfo != null) {
14961            canvas = attachInfo.mCanvas;
14962            if (canvas == null) {
14963                canvas = new Canvas();
14964            }
14965            canvas.setBitmap(bitmap);
14966            // Temporarily clobber the cached Canvas in case one of our children
14967            // is also using a drawing cache. Without this, the children would
14968            // steal the canvas by attaching their own bitmap to it and bad, bad
14969            // things would happen (invisible views, corrupted drawings, etc.)
14970            attachInfo.mCanvas = null;
14971        } else {
14972            // This case should hopefully never or seldom happen
14973            canvas = new Canvas(bitmap);
14974        }
14975
14976        if ((backgroundColor & 0xff000000) != 0) {
14977            bitmap.eraseColor(backgroundColor);
14978        }
14979
14980        computeScroll();
14981        final int restoreCount = canvas.save();
14982        canvas.scale(scale, scale);
14983        canvas.translate(-mScrollX, -mScrollY);
14984
14985        // Temporarily remove the dirty mask
14986        int flags = mPrivateFlags;
14987        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14988
14989        // Fast path for layouts with no backgrounds
14990        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14991            dispatchDraw(canvas);
14992            if (mOverlay != null && !mOverlay.isEmpty()) {
14993                mOverlay.getOverlayView().draw(canvas);
14994            }
14995        } else {
14996            draw(canvas);
14997        }
14998
14999        mPrivateFlags = flags;
15000
15001        canvas.restoreToCount(restoreCount);
15002        canvas.setBitmap(null);
15003
15004        if (attachInfo != null) {
15005            // Restore the cached Canvas for our siblings
15006            attachInfo.mCanvas = canvas;
15007        }
15008
15009        return bitmap;
15010    }
15011
15012    /**
15013     * Indicates whether this View is currently in edit mode. A View is usually
15014     * in edit mode when displayed within a developer tool. For instance, if
15015     * this View is being drawn by a visual user interface builder, this method
15016     * should return true.
15017     *
15018     * Subclasses should check the return value of this method to provide
15019     * different behaviors if their normal behavior might interfere with the
15020     * host environment. For instance: the class spawns a thread in its
15021     * constructor, the drawing code relies on device-specific features, etc.
15022     *
15023     * This method is usually checked in the drawing code of custom widgets.
15024     *
15025     * @return True if this View is in edit mode, false otherwise.
15026     */
15027    public boolean isInEditMode() {
15028        return false;
15029    }
15030
15031    /**
15032     * If the View draws content inside its padding and enables fading edges,
15033     * it needs to support padding offsets. Padding offsets are added to the
15034     * fading edges to extend the length of the fade so that it covers pixels
15035     * drawn inside the padding.
15036     *
15037     * Subclasses of this class should override this method if they need
15038     * to draw content inside the padding.
15039     *
15040     * @return True if padding offset must be applied, false otherwise.
15041     *
15042     * @see #getLeftPaddingOffset()
15043     * @see #getRightPaddingOffset()
15044     * @see #getTopPaddingOffset()
15045     * @see #getBottomPaddingOffset()
15046     *
15047     * @since CURRENT
15048     */
15049    protected boolean isPaddingOffsetRequired() {
15050        return false;
15051    }
15052
15053    /**
15054     * Amount by which to extend the left fading region. Called only when
15055     * {@link #isPaddingOffsetRequired()} returns true.
15056     *
15057     * @return The left padding offset in pixels.
15058     *
15059     * @see #isPaddingOffsetRequired()
15060     *
15061     * @since CURRENT
15062     */
15063    protected int getLeftPaddingOffset() {
15064        return 0;
15065    }
15066
15067    /**
15068     * Amount by which to extend the right fading region. Called only when
15069     * {@link #isPaddingOffsetRequired()} returns true.
15070     *
15071     * @return The right padding offset in pixels.
15072     *
15073     * @see #isPaddingOffsetRequired()
15074     *
15075     * @since CURRENT
15076     */
15077    protected int getRightPaddingOffset() {
15078        return 0;
15079    }
15080
15081    /**
15082     * Amount by which to extend the top fading region. Called only when
15083     * {@link #isPaddingOffsetRequired()} returns true.
15084     *
15085     * @return The top padding offset in pixels.
15086     *
15087     * @see #isPaddingOffsetRequired()
15088     *
15089     * @since CURRENT
15090     */
15091    protected int getTopPaddingOffset() {
15092        return 0;
15093    }
15094
15095    /**
15096     * Amount by which to extend the bottom fading region. Called only when
15097     * {@link #isPaddingOffsetRequired()} returns true.
15098     *
15099     * @return The bottom padding offset in pixels.
15100     *
15101     * @see #isPaddingOffsetRequired()
15102     *
15103     * @since CURRENT
15104     */
15105    protected int getBottomPaddingOffset() {
15106        return 0;
15107    }
15108
15109    /**
15110     * @hide
15111     * @param offsetRequired
15112     */
15113    protected int getFadeTop(boolean offsetRequired) {
15114        int top = mPaddingTop;
15115        if (offsetRequired) top += getTopPaddingOffset();
15116        return top;
15117    }
15118
15119    /**
15120     * @hide
15121     * @param offsetRequired
15122     */
15123    protected int getFadeHeight(boolean offsetRequired) {
15124        int padding = mPaddingTop;
15125        if (offsetRequired) padding += getTopPaddingOffset();
15126        return mBottom - mTop - mPaddingBottom - padding;
15127    }
15128
15129    /**
15130     * <p>Indicates whether this view is attached to a hardware accelerated
15131     * window or not.</p>
15132     *
15133     * <p>Even if this method returns true, it does not mean that every call
15134     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15135     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15136     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15137     * window is hardware accelerated,
15138     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15139     * return false, and this method will return true.</p>
15140     *
15141     * @return True if the view is attached to a window and the window is
15142     *         hardware accelerated; false in any other case.
15143     */
15144    @ViewDebug.ExportedProperty(category = "drawing")
15145    public boolean isHardwareAccelerated() {
15146        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15147    }
15148
15149    /**
15150     * Sets a rectangular area on this view to which the view will be clipped
15151     * when it is drawn. Setting the value to null will remove the clip bounds
15152     * and the view will draw normally, using its full bounds.
15153     *
15154     * @param clipBounds The rectangular area, in the local coordinates of
15155     * this view, to which future drawing operations will be clipped.
15156     */
15157    public void setClipBounds(Rect clipBounds) {
15158        if (clipBounds == mClipBounds
15159                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15160            return;
15161        }
15162        if (clipBounds != null) {
15163            if (mClipBounds == null) {
15164                mClipBounds = new Rect(clipBounds);
15165            } else {
15166                mClipBounds.set(clipBounds);
15167            }
15168        } else {
15169            mClipBounds = null;
15170        }
15171        mRenderNode.setClipBounds(mClipBounds);
15172        invalidateViewProperty(false, false);
15173    }
15174
15175    /**
15176     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15177     *
15178     * @return A copy of the current clip bounds if clip bounds are set,
15179     * otherwise null.
15180     */
15181    public Rect getClipBounds() {
15182        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15183    }
15184
15185
15186    /**
15187     * Populates an output rectangle with the clip bounds of the view,
15188     * returning {@code true} if successful or {@code false} if the view's
15189     * clip bounds are {@code null}.
15190     *
15191     * @param outRect rectangle in which to place the clip bounds of the view
15192     * @return {@code true} if successful or {@code false} if the view's
15193     *         clip bounds are {@code null}
15194     */
15195    public boolean getClipBounds(Rect outRect) {
15196        if (mClipBounds != null) {
15197            outRect.set(mClipBounds);
15198            return true;
15199        }
15200        return false;
15201    }
15202
15203    /**
15204     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15205     * case of an active Animation being run on the view.
15206     */
15207    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15208            Animation a, boolean scalingRequired) {
15209        Transformation invalidationTransform;
15210        final int flags = parent.mGroupFlags;
15211        final boolean initialized = a.isInitialized();
15212        if (!initialized) {
15213            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15214            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15215            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15216            onAnimationStart();
15217        }
15218
15219        final Transformation t = parent.getChildTransformation();
15220        boolean more = a.getTransformation(drawingTime, t, 1f);
15221        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15222            if (parent.mInvalidationTransformation == null) {
15223                parent.mInvalidationTransformation = new Transformation();
15224            }
15225            invalidationTransform = parent.mInvalidationTransformation;
15226            a.getTransformation(drawingTime, invalidationTransform, 1f);
15227        } else {
15228            invalidationTransform = t;
15229        }
15230
15231        if (more) {
15232            if (!a.willChangeBounds()) {
15233                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15234                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15235                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15236                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15237                    // The child need to draw an animation, potentially offscreen, so
15238                    // make sure we do not cancel invalidate requests
15239                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15240                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15241                }
15242            } else {
15243                if (parent.mInvalidateRegion == null) {
15244                    parent.mInvalidateRegion = new RectF();
15245                }
15246                final RectF region = parent.mInvalidateRegion;
15247                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15248                        invalidationTransform);
15249
15250                // The child need to draw an animation, potentially offscreen, so
15251                // make sure we do not cancel invalidate requests
15252                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15253
15254                final int left = mLeft + (int) region.left;
15255                final int top = mTop + (int) region.top;
15256                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15257                        top + (int) (region.height() + .5f));
15258            }
15259        }
15260        return more;
15261    }
15262
15263    /**
15264     * This method is called by getDisplayList() when a display list is recorded for a View.
15265     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15266     */
15267    void setDisplayListProperties(RenderNode renderNode) {
15268        if (renderNode != null) {
15269            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15270            renderNode.setClipToBounds(mParent instanceof ViewGroup
15271                    && ((ViewGroup) mParent).getClipChildren());
15272
15273            float alpha = 1;
15274            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15275                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15276                ViewGroup parentVG = (ViewGroup) mParent;
15277                final Transformation t = parentVG.getChildTransformation();
15278                if (parentVG.getChildStaticTransformation(this, t)) {
15279                    final int transformType = t.getTransformationType();
15280                    if (transformType != Transformation.TYPE_IDENTITY) {
15281                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15282                            alpha = t.getAlpha();
15283                        }
15284                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15285                            renderNode.setStaticMatrix(t.getMatrix());
15286                        }
15287                    }
15288                }
15289            }
15290            if (mTransformationInfo != null) {
15291                alpha *= getFinalAlpha();
15292                if (alpha < 1) {
15293                    final int multipliedAlpha = (int) (255 * alpha);
15294                    if (onSetAlpha(multipliedAlpha)) {
15295                        alpha = 1;
15296                    }
15297                }
15298                renderNode.setAlpha(alpha);
15299            } else if (alpha < 1) {
15300                renderNode.setAlpha(alpha);
15301            }
15302        }
15303    }
15304
15305    /**
15306     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15307     *
15308     * This is where the View specializes rendering behavior based on layer type,
15309     * and hardware acceleration.
15310     */
15311    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15312        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15313        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15314         *
15315         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15316         * HW accelerated, it can't handle drawing RenderNodes.
15317         */
15318        boolean drawingWithRenderNode = mAttachInfo != null
15319                && mAttachInfo.mHardwareAccelerated
15320                && hardwareAcceleratedCanvas;
15321
15322        boolean more = false;
15323        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15324        final int parentFlags = parent.mGroupFlags;
15325
15326        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15327            parent.getChildTransformation().clear();
15328            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15329        }
15330
15331        Transformation transformToApply = null;
15332        boolean concatMatrix = false;
15333        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15334        final Animation a = getAnimation();
15335        if (a != null) {
15336            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15337            concatMatrix = a.willChangeTransformationMatrix();
15338            if (concatMatrix) {
15339                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15340            }
15341            transformToApply = parent.getChildTransformation();
15342        } else {
15343            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15344                // No longer animating: clear out old animation matrix
15345                mRenderNode.setAnimationMatrix(null);
15346                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15347            }
15348            if (!drawingWithRenderNode
15349                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15350                final Transformation t = parent.getChildTransformation();
15351                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15352                if (hasTransform) {
15353                    final int transformType = t.getTransformationType();
15354                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15355                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15356                }
15357            }
15358        }
15359
15360        concatMatrix |= !childHasIdentityMatrix;
15361
15362        // Sets the flag as early as possible to allow draw() implementations
15363        // to call invalidate() successfully when doing animations
15364        mPrivateFlags |= PFLAG_DRAWN;
15365
15366        if (!concatMatrix &&
15367                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15368                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15369                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15370                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15371            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15372            return more;
15373        }
15374        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15375
15376        if (hardwareAcceleratedCanvas) {
15377            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15378            // retain the flag's value temporarily in the mRecreateDisplayList flag
15379            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15380            mPrivateFlags &= ~PFLAG_INVALIDATED;
15381        }
15382
15383        RenderNode renderNode = null;
15384        Bitmap cache = null;
15385        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15386        if (layerType == LAYER_TYPE_SOFTWARE
15387                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15388            // If not drawing with RenderNode, treat HW layers as SW
15389            layerType = LAYER_TYPE_SOFTWARE;
15390            buildDrawingCache(true);
15391            cache = getDrawingCache(true);
15392        }
15393
15394        if (drawingWithRenderNode) {
15395            // Delay getting the display list until animation-driven alpha values are
15396            // set up and possibly passed on to the view
15397            renderNode = getDisplayList();
15398            if (!renderNode.isValid()) {
15399                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15400                // to getDisplayList(), the display list will be marked invalid and we should not
15401                // try to use it again.
15402                renderNode = null;
15403                drawingWithRenderNode = false;
15404            }
15405        }
15406
15407        int sx = 0;
15408        int sy = 0;
15409        if (!drawingWithRenderNode) {
15410            computeScroll();
15411            sx = mScrollX;
15412            sy = mScrollY;
15413        }
15414
15415        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15416        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15417
15418        int restoreTo = -1;
15419        if (!drawingWithRenderNode || transformToApply != null) {
15420            restoreTo = canvas.save();
15421        }
15422        if (offsetForScroll) {
15423            canvas.translate(mLeft - sx, mTop - sy);
15424        } else {
15425            if (!drawingWithRenderNode) {
15426                canvas.translate(mLeft, mTop);
15427            }
15428            if (scalingRequired) {
15429                if (drawingWithRenderNode) {
15430                    // TODO: Might not need this if we put everything inside the DL
15431                    restoreTo = canvas.save();
15432                }
15433                // mAttachInfo cannot be null, otherwise scalingRequired == false
15434                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15435                canvas.scale(scale, scale);
15436            }
15437        }
15438
15439        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15440        if (transformToApply != null
15441                || alpha < 1
15442                || !hasIdentityMatrix()
15443                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15444            if (transformToApply != null || !childHasIdentityMatrix) {
15445                int transX = 0;
15446                int transY = 0;
15447
15448                if (offsetForScroll) {
15449                    transX = -sx;
15450                    transY = -sy;
15451                }
15452
15453                if (transformToApply != null) {
15454                    if (concatMatrix) {
15455                        if (drawingWithRenderNode) {
15456                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15457                        } else {
15458                            // Undo the scroll translation, apply the transformation matrix,
15459                            // then redo the scroll translate to get the correct result.
15460                            canvas.translate(-transX, -transY);
15461                            canvas.concat(transformToApply.getMatrix());
15462                            canvas.translate(transX, transY);
15463                        }
15464                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15465                    }
15466
15467                    float transformAlpha = transformToApply.getAlpha();
15468                    if (transformAlpha < 1) {
15469                        alpha *= transformAlpha;
15470                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15471                    }
15472                }
15473
15474                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
15475                    canvas.translate(-transX, -transY);
15476                    canvas.concat(getMatrix());
15477                    canvas.translate(transX, transY);
15478                }
15479            }
15480
15481            // Deal with alpha if it is or used to be <1
15482            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15483                if (alpha < 1) {
15484                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15485                } else {
15486                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15487                }
15488                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15489                if (!drawingWithDrawingCache) {
15490                    final int multipliedAlpha = (int) (255 * alpha);
15491                    if (!onSetAlpha(multipliedAlpha)) {
15492                        if (drawingWithRenderNode) {
15493                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15494                        } else if (layerType == LAYER_TYPE_NONE) {
15495                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
15496                                    multipliedAlpha);
15497                        }
15498                    } else {
15499                        // Alpha is handled by the child directly, clobber the layer's alpha
15500                        mPrivateFlags |= PFLAG_ALPHA_SET;
15501                    }
15502                }
15503            }
15504        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15505            onSetAlpha(255);
15506            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15507        }
15508
15509        if (!drawingWithRenderNode) {
15510            // apply clips directly, since RenderNode won't do it for this draw
15511            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
15512                if (offsetForScroll) {
15513                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
15514                } else {
15515                    if (!scalingRequired || cache == null) {
15516                        canvas.clipRect(0, 0, getWidth(), getHeight());
15517                    } else {
15518                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15519                    }
15520                }
15521            }
15522
15523            if (mClipBounds != null) {
15524                // clip bounds ignore scroll
15525                canvas.clipRect(mClipBounds);
15526            }
15527        }
15528
15529        if (!drawingWithDrawingCache) {
15530            if (drawingWithRenderNode) {
15531                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15532                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15533            } else {
15534                // Fast path for layouts with no backgrounds
15535                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15536                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15537                    dispatchDraw(canvas);
15538                } else {
15539                    draw(canvas);
15540                }
15541            }
15542        } else if (cache != null) {
15543            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15544            Paint cachePaint;
15545            int restoreAlpha = 0;
15546
15547            if (layerType == LAYER_TYPE_NONE) {
15548                cachePaint = parent.mCachePaint;
15549                if (cachePaint == null) {
15550                    cachePaint = new Paint();
15551                    cachePaint.setDither(false);
15552                    parent.mCachePaint = cachePaint;
15553                }
15554            } else {
15555                cachePaint = mLayerPaint;
15556                restoreAlpha = mLayerPaint.getAlpha();
15557            }
15558            cachePaint.setAlpha((int) (alpha * 255));
15559            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15560            cachePaint.setAlpha(restoreAlpha);
15561        }
15562
15563        if (restoreTo >= 0) {
15564            canvas.restoreToCount(restoreTo);
15565        }
15566
15567        if (a != null && !more) {
15568            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
15569                onSetAlpha(255);
15570            }
15571            parent.finishAnimatingView(this, a);
15572        }
15573
15574        if (more && hardwareAcceleratedCanvas) {
15575            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15576                // alpha animations should cause the child to recreate its display list
15577                invalidate(true);
15578            }
15579        }
15580
15581        mRecreateDisplayList = false;
15582
15583        return more;
15584    }
15585
15586    /**
15587     * Manually render this view (and all of its children) to the given Canvas.
15588     * The view must have already done a full layout before this function is
15589     * called.  When implementing a view, implement
15590     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15591     * If you do need to override this method, call the superclass version.
15592     *
15593     * @param canvas The Canvas to which the View is rendered.
15594     */
15595    @CallSuper
15596    public void draw(Canvas canvas) {
15597        final int privateFlags = mPrivateFlags;
15598        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15599                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15600        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15601
15602        /*
15603         * Draw traversal performs several drawing steps which must be executed
15604         * in the appropriate order:
15605         *
15606         *      1. Draw the background
15607         *      2. If necessary, save the canvas' layers to prepare for fading
15608         *      3. Draw view's content
15609         *      4. Draw children
15610         *      5. If necessary, draw the fading edges and restore layers
15611         *      6. Draw decorations (scrollbars for instance)
15612         */
15613
15614        // Step 1, draw the background, if needed
15615        int saveCount;
15616
15617        if (!dirtyOpaque) {
15618            drawBackground(canvas);
15619        }
15620
15621        // skip step 2 & 5 if possible (common case)
15622        final int viewFlags = mViewFlags;
15623        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15624        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15625        if (!verticalEdges && !horizontalEdges) {
15626            // Step 3, draw the content
15627            if (!dirtyOpaque) onDraw(canvas);
15628
15629            // Step 4, draw the children
15630            dispatchDraw(canvas);
15631
15632            // Overlay is part of the content and draws beneath Foreground
15633            if (mOverlay != null && !mOverlay.isEmpty()) {
15634                mOverlay.getOverlayView().dispatchDraw(canvas);
15635            }
15636
15637            // Step 6, draw decorations (foreground, scrollbars)
15638            onDrawForeground(canvas);
15639
15640            // we're done...
15641            return;
15642        }
15643
15644        /*
15645         * Here we do the full fledged routine...
15646         * (this is an uncommon case where speed matters less,
15647         * this is why we repeat some of the tests that have been
15648         * done above)
15649         */
15650
15651        boolean drawTop = false;
15652        boolean drawBottom = false;
15653        boolean drawLeft = false;
15654        boolean drawRight = false;
15655
15656        float topFadeStrength = 0.0f;
15657        float bottomFadeStrength = 0.0f;
15658        float leftFadeStrength = 0.0f;
15659        float rightFadeStrength = 0.0f;
15660
15661        // Step 2, save the canvas' layers
15662        int paddingLeft = mPaddingLeft;
15663
15664        final boolean offsetRequired = isPaddingOffsetRequired();
15665        if (offsetRequired) {
15666            paddingLeft += getLeftPaddingOffset();
15667        }
15668
15669        int left = mScrollX + paddingLeft;
15670        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15671        int top = mScrollY + getFadeTop(offsetRequired);
15672        int bottom = top + getFadeHeight(offsetRequired);
15673
15674        if (offsetRequired) {
15675            right += getRightPaddingOffset();
15676            bottom += getBottomPaddingOffset();
15677        }
15678
15679        final ScrollabilityCache scrollabilityCache = mScrollCache;
15680        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15681        int length = (int) fadeHeight;
15682
15683        // clip the fade length if top and bottom fades overlap
15684        // overlapping fades produce odd-looking artifacts
15685        if (verticalEdges && (top + length > bottom - length)) {
15686            length = (bottom - top) / 2;
15687        }
15688
15689        // also clip horizontal fades if necessary
15690        if (horizontalEdges && (left + length > right - length)) {
15691            length = (right - left) / 2;
15692        }
15693
15694        if (verticalEdges) {
15695            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15696            drawTop = topFadeStrength * fadeHeight > 1.0f;
15697            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15698            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15699        }
15700
15701        if (horizontalEdges) {
15702            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15703            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15704            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15705            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15706        }
15707
15708        saveCount = canvas.getSaveCount();
15709
15710        int solidColor = getSolidColor();
15711        if (solidColor == 0) {
15712            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15713
15714            if (drawTop) {
15715                canvas.saveLayer(left, top, right, top + length, null, flags);
15716            }
15717
15718            if (drawBottom) {
15719                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15720            }
15721
15722            if (drawLeft) {
15723                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15724            }
15725
15726            if (drawRight) {
15727                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15728            }
15729        } else {
15730            scrollabilityCache.setFadeColor(solidColor);
15731        }
15732
15733        // Step 3, draw the content
15734        if (!dirtyOpaque) onDraw(canvas);
15735
15736        // Step 4, draw the children
15737        dispatchDraw(canvas);
15738
15739        // Step 5, draw the fade effect and restore layers
15740        final Paint p = scrollabilityCache.paint;
15741        final Matrix matrix = scrollabilityCache.matrix;
15742        final Shader fade = scrollabilityCache.shader;
15743
15744        if (drawTop) {
15745            matrix.setScale(1, fadeHeight * topFadeStrength);
15746            matrix.postTranslate(left, top);
15747            fade.setLocalMatrix(matrix);
15748            p.setShader(fade);
15749            canvas.drawRect(left, top, right, top + length, p);
15750        }
15751
15752        if (drawBottom) {
15753            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15754            matrix.postRotate(180);
15755            matrix.postTranslate(left, bottom);
15756            fade.setLocalMatrix(matrix);
15757            p.setShader(fade);
15758            canvas.drawRect(left, bottom - length, right, bottom, p);
15759        }
15760
15761        if (drawLeft) {
15762            matrix.setScale(1, fadeHeight * leftFadeStrength);
15763            matrix.postRotate(-90);
15764            matrix.postTranslate(left, top);
15765            fade.setLocalMatrix(matrix);
15766            p.setShader(fade);
15767            canvas.drawRect(left, top, left + length, bottom, p);
15768        }
15769
15770        if (drawRight) {
15771            matrix.setScale(1, fadeHeight * rightFadeStrength);
15772            matrix.postRotate(90);
15773            matrix.postTranslate(right, top);
15774            fade.setLocalMatrix(matrix);
15775            p.setShader(fade);
15776            canvas.drawRect(right - length, top, right, bottom, p);
15777        }
15778
15779        canvas.restoreToCount(saveCount);
15780
15781        // Overlay is part of the content and draws beneath Foreground
15782        if (mOverlay != null && !mOverlay.isEmpty()) {
15783            mOverlay.getOverlayView().dispatchDraw(canvas);
15784        }
15785
15786        // Step 6, draw decorations (foreground, scrollbars)
15787        onDrawForeground(canvas);
15788    }
15789
15790    /**
15791     * Draws the background onto the specified canvas.
15792     *
15793     * @param canvas Canvas on which to draw the background
15794     */
15795    private void drawBackground(Canvas canvas) {
15796        final Drawable background = mBackground;
15797        if (background == null) {
15798            return;
15799        }
15800
15801        setBackgroundBounds();
15802
15803        // Attempt to use a display list if requested.
15804        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15805                && mAttachInfo.mHardwareRenderer != null) {
15806            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15807
15808            final RenderNode renderNode = mBackgroundRenderNode;
15809            if (renderNode != null && renderNode.isValid()) {
15810                setBackgroundRenderNodeProperties(renderNode);
15811                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15812                return;
15813            }
15814        }
15815
15816        final int scrollX = mScrollX;
15817        final int scrollY = mScrollY;
15818        if ((scrollX | scrollY) == 0) {
15819            background.draw(canvas);
15820        } else {
15821            canvas.translate(scrollX, scrollY);
15822            background.draw(canvas);
15823            canvas.translate(-scrollX, -scrollY);
15824        }
15825    }
15826
15827    /**
15828     * Sets the correct background bounds and rebuilds the outline, if needed.
15829     * <p/>
15830     * This is called by LayoutLib.
15831     */
15832    void setBackgroundBounds() {
15833        if (mBackgroundSizeChanged && mBackground != null) {
15834            mBackground.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15835            mBackgroundSizeChanged = false;
15836            rebuildOutline();
15837        }
15838    }
15839
15840    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15841        renderNode.setTranslationX(mScrollX);
15842        renderNode.setTranslationY(mScrollY);
15843    }
15844
15845    /**
15846     * Creates a new display list or updates the existing display list for the
15847     * specified Drawable.
15848     *
15849     * @param drawable Drawable for which to create a display list
15850     * @param renderNode Existing RenderNode, or {@code null}
15851     * @return A valid display list for the specified drawable
15852     */
15853    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15854        if (renderNode == null) {
15855            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15856        }
15857
15858        final Rect bounds = drawable.getBounds();
15859        final int width = bounds.width();
15860        final int height = bounds.height();
15861        final DisplayListCanvas canvas = renderNode.start(width, height);
15862
15863        // Reverse left/top translation done by drawable canvas, which will
15864        // instead be applied by rendernode's LTRB bounds below. This way, the
15865        // drawable's bounds match with its rendernode bounds and its content
15866        // will lie within those bounds in the rendernode tree.
15867        canvas.translate(-bounds.left, -bounds.top);
15868
15869        try {
15870            drawable.draw(canvas);
15871        } finally {
15872            renderNode.end(canvas);
15873        }
15874
15875        // Set up drawable properties that are view-independent.
15876        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15877        renderNode.setProjectBackwards(drawable.isProjected());
15878        renderNode.setProjectionReceiver(true);
15879        renderNode.setClipToBounds(false);
15880        return renderNode;
15881    }
15882
15883    /**
15884     * Returns the overlay for this view, creating it if it does not yet exist.
15885     * Adding drawables to the overlay will cause them to be displayed whenever
15886     * the view itself is redrawn. Objects in the overlay should be actively
15887     * managed: remove them when they should not be displayed anymore. The
15888     * overlay will always have the same size as its host view.
15889     *
15890     * <p>Note: Overlays do not currently work correctly with {@link
15891     * SurfaceView} or {@link TextureView}; contents in overlays for these
15892     * types of views may not display correctly.</p>
15893     *
15894     * @return The ViewOverlay object for this view.
15895     * @see ViewOverlay
15896     */
15897    public ViewOverlay getOverlay() {
15898        if (mOverlay == null) {
15899            mOverlay = new ViewOverlay(mContext, this);
15900        }
15901        return mOverlay;
15902    }
15903
15904    /**
15905     * Override this if your view is known to always be drawn on top of a solid color background,
15906     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15907     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15908     * should be set to 0xFF.
15909     *
15910     * @see #setVerticalFadingEdgeEnabled(boolean)
15911     * @see #setHorizontalFadingEdgeEnabled(boolean)
15912     *
15913     * @return The known solid color background for this view, or 0 if the color may vary
15914     */
15915    @ViewDebug.ExportedProperty(category = "drawing")
15916    @ColorInt
15917    public int getSolidColor() {
15918        return 0;
15919    }
15920
15921    /**
15922     * Build a human readable string representation of the specified view flags.
15923     *
15924     * @param flags the view flags to convert to a string
15925     * @return a String representing the supplied flags
15926     */
15927    private static String printFlags(int flags) {
15928        String output = "";
15929        int numFlags = 0;
15930        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15931            output += "TAKES_FOCUS";
15932            numFlags++;
15933        }
15934
15935        switch (flags & VISIBILITY_MASK) {
15936        case INVISIBLE:
15937            if (numFlags > 0) {
15938                output += " ";
15939            }
15940            output += "INVISIBLE";
15941            // USELESS HERE numFlags++;
15942            break;
15943        case GONE:
15944            if (numFlags > 0) {
15945                output += " ";
15946            }
15947            output += "GONE";
15948            // USELESS HERE numFlags++;
15949            break;
15950        default:
15951            break;
15952        }
15953        return output;
15954    }
15955
15956    /**
15957     * Build a human readable string representation of the specified private
15958     * view flags.
15959     *
15960     * @param privateFlags the private view flags to convert to a string
15961     * @return a String representing the supplied flags
15962     */
15963    private static String printPrivateFlags(int privateFlags) {
15964        String output = "";
15965        int numFlags = 0;
15966
15967        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15968            output += "WANTS_FOCUS";
15969            numFlags++;
15970        }
15971
15972        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15973            if (numFlags > 0) {
15974                output += " ";
15975            }
15976            output += "FOCUSED";
15977            numFlags++;
15978        }
15979
15980        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15981            if (numFlags > 0) {
15982                output += " ";
15983            }
15984            output += "SELECTED";
15985            numFlags++;
15986        }
15987
15988        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15989            if (numFlags > 0) {
15990                output += " ";
15991            }
15992            output += "IS_ROOT_NAMESPACE";
15993            numFlags++;
15994        }
15995
15996        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15997            if (numFlags > 0) {
15998                output += " ";
15999            }
16000            output += "HAS_BOUNDS";
16001            numFlags++;
16002        }
16003
16004        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
16005            if (numFlags > 0) {
16006                output += " ";
16007            }
16008            output += "DRAWN";
16009            // USELESS HERE numFlags++;
16010        }
16011        return output;
16012    }
16013
16014    /**
16015     * <p>Indicates whether or not this view's layout will be requested during
16016     * the next hierarchy layout pass.</p>
16017     *
16018     * @return true if the layout will be forced during next layout pass
16019     */
16020    public boolean isLayoutRequested() {
16021        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
16022    }
16023
16024    /**
16025     * Return true if o is a ViewGroup that is laying out using optical bounds.
16026     * @hide
16027     */
16028    public static boolean isLayoutModeOptical(Object o) {
16029        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16030    }
16031
16032    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16033        Insets parentInsets = mParent instanceof View ?
16034                ((View) mParent).getOpticalInsets() : Insets.NONE;
16035        Insets childInsets = getOpticalInsets();
16036        return setFrame(
16037                left   + parentInsets.left - childInsets.left,
16038                top    + parentInsets.top  - childInsets.top,
16039                right  + parentInsets.left + childInsets.right,
16040                bottom + parentInsets.top  + childInsets.bottom);
16041    }
16042
16043    /**
16044     * Assign a size and position to a view and all of its
16045     * descendants
16046     *
16047     * <p>This is the second phase of the layout mechanism.
16048     * (The first is measuring). In this phase, each parent calls
16049     * layout on all of its children to position them.
16050     * This is typically done using the child measurements
16051     * that were stored in the measure pass().</p>
16052     *
16053     * <p>Derived classes should not override this method.
16054     * Derived classes with children should override
16055     * onLayout. In that method, they should
16056     * call layout on each of their children.</p>
16057     *
16058     * @param l Left position, relative to parent
16059     * @param t Top position, relative to parent
16060     * @param r Right position, relative to parent
16061     * @param b Bottom position, relative to parent
16062     */
16063    @SuppressWarnings({"unchecked"})
16064    public void layout(int l, int t, int r, int b) {
16065        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16066            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16067            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16068        }
16069
16070        int oldL = mLeft;
16071        int oldT = mTop;
16072        int oldB = mBottom;
16073        int oldR = mRight;
16074
16075        boolean changed = isLayoutModeOptical(mParent) ?
16076                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16077
16078        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16079            onLayout(changed, l, t, r, b);
16080            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16081
16082            ListenerInfo li = mListenerInfo;
16083            if (li != null && li.mOnLayoutChangeListeners != null) {
16084                ArrayList<OnLayoutChangeListener> listenersCopy =
16085                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16086                int numListeners = listenersCopy.size();
16087                for (int i = 0; i < numListeners; ++i) {
16088                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16089                }
16090            }
16091        }
16092
16093        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16094        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16095    }
16096
16097    /**
16098     * Called from layout when this view should
16099     * assign a size and position to each of its children.
16100     *
16101     * Derived classes with children should override
16102     * this method and call layout on each of
16103     * their children.
16104     * @param changed This is a new size or position for this view
16105     * @param left Left position, relative to parent
16106     * @param top Top position, relative to parent
16107     * @param right Right position, relative to parent
16108     * @param bottom Bottom position, relative to parent
16109     */
16110    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16111    }
16112
16113    /**
16114     * Assign a size and position to this view.
16115     *
16116     * This is called from layout.
16117     *
16118     * @param left Left position, relative to parent
16119     * @param top Top position, relative to parent
16120     * @param right Right position, relative to parent
16121     * @param bottom Bottom position, relative to parent
16122     * @return true if the new size and position are different than the
16123     *         previous ones
16124     * {@hide}
16125     */
16126    protected boolean setFrame(int left, int top, int right, int bottom) {
16127        boolean changed = false;
16128
16129        if (DBG) {
16130            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16131                    + right + "," + bottom + ")");
16132        }
16133
16134        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16135            changed = true;
16136
16137            // Remember our drawn bit
16138            int drawn = mPrivateFlags & PFLAG_DRAWN;
16139
16140            int oldWidth = mRight - mLeft;
16141            int oldHeight = mBottom - mTop;
16142            int newWidth = right - left;
16143            int newHeight = bottom - top;
16144            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16145
16146            // Invalidate our old position
16147            invalidate(sizeChanged);
16148
16149            mLeft = left;
16150            mTop = top;
16151            mRight = right;
16152            mBottom = bottom;
16153            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16154
16155            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16156
16157
16158            if (sizeChanged) {
16159                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16160            }
16161
16162            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16163                // If we are visible, force the DRAWN bit to on so that
16164                // this invalidate will go through (at least to our parent).
16165                // This is because someone may have invalidated this view
16166                // before this call to setFrame came in, thereby clearing
16167                // the DRAWN bit.
16168                mPrivateFlags |= PFLAG_DRAWN;
16169                invalidate(sizeChanged);
16170                // parent display list may need to be recreated based on a change in the bounds
16171                // of any child
16172                invalidateParentCaches();
16173            }
16174
16175            // Reset drawn bit to original value (invalidate turns it off)
16176            mPrivateFlags |= drawn;
16177
16178            mBackgroundSizeChanged = true;
16179            if (mForegroundInfo != null) {
16180                mForegroundInfo.mBoundsChanged = true;
16181            }
16182
16183            notifySubtreeAccessibilityStateChangedIfNeeded();
16184        }
16185        return changed;
16186    }
16187
16188    /**
16189     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16190     * @hide
16191     */
16192    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16193        setFrame(left, top, right, bottom);
16194    }
16195
16196    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16197        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16198        if (mOverlay != null) {
16199            mOverlay.getOverlayView().setRight(newWidth);
16200            mOverlay.getOverlayView().setBottom(newHeight);
16201        }
16202        rebuildOutline();
16203    }
16204
16205    /**
16206     * Finalize inflating a view from XML.  This is called as the last phase
16207     * of inflation, after all child views have been added.
16208     *
16209     * <p>Even if the subclass overrides onFinishInflate, they should always be
16210     * sure to call the super method, so that we get called.
16211     */
16212    @CallSuper
16213    protected void onFinishInflate() {
16214    }
16215
16216    /**
16217     * Returns the resources associated with this view.
16218     *
16219     * @return Resources object.
16220     */
16221    public Resources getResources() {
16222        return mResources;
16223    }
16224
16225    /**
16226     * Invalidates the specified Drawable.
16227     *
16228     * @param drawable the drawable to invalidate
16229     */
16230    @Override
16231    public void invalidateDrawable(@NonNull Drawable drawable) {
16232        if (verifyDrawable(drawable)) {
16233            final Rect dirty = drawable.getDirtyBounds();
16234            final int scrollX = mScrollX;
16235            final int scrollY = mScrollY;
16236
16237            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16238                    dirty.right + scrollX, dirty.bottom + scrollY);
16239            rebuildOutline();
16240        }
16241    }
16242
16243    /**
16244     * Schedules an action on a drawable to occur at a specified time.
16245     *
16246     * @param who the recipient of the action
16247     * @param what the action to run on the drawable
16248     * @param when the time at which the action must occur. Uses the
16249     *        {@link SystemClock#uptimeMillis} timebase.
16250     */
16251    @Override
16252    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16253        if (verifyDrawable(who) && what != null) {
16254            final long delay = when - SystemClock.uptimeMillis();
16255            if (mAttachInfo != null) {
16256                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16257                        Choreographer.CALLBACK_ANIMATION, what, who,
16258                        Choreographer.subtractFrameDelay(delay));
16259            } else {
16260                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16261            }
16262        }
16263    }
16264
16265    /**
16266     * Cancels a scheduled action on a drawable.
16267     *
16268     * @param who the recipient of the action
16269     * @param what the action to cancel
16270     */
16271    @Override
16272    public void unscheduleDrawable(Drawable who, Runnable what) {
16273        if (verifyDrawable(who) && what != null) {
16274            if (mAttachInfo != null) {
16275                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16276                        Choreographer.CALLBACK_ANIMATION, what, who);
16277            }
16278            ViewRootImpl.getRunQueue().removeCallbacks(what);
16279        }
16280    }
16281
16282    /**
16283     * Unschedule any events associated with the given Drawable.  This can be
16284     * used when selecting a new Drawable into a view, so that the previous
16285     * one is completely unscheduled.
16286     *
16287     * @param who The Drawable to unschedule.
16288     *
16289     * @see #drawableStateChanged
16290     */
16291    public void unscheduleDrawable(Drawable who) {
16292        if (mAttachInfo != null && who != null) {
16293            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16294                    Choreographer.CALLBACK_ANIMATION, null, who);
16295        }
16296    }
16297
16298    /**
16299     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16300     * that the View directionality can and will be resolved before its Drawables.
16301     *
16302     * Will call {@link View#onResolveDrawables} when resolution is done.
16303     *
16304     * @hide
16305     */
16306    protected void resolveDrawables() {
16307        // Drawables resolution may need to happen before resolving the layout direction (which is
16308        // done only during the measure() call).
16309        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16310        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16311        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16312        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16313        // direction to be resolved as its resolved value will be the same as its raw value.
16314        if (!isLayoutDirectionResolved() &&
16315                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16316            return;
16317        }
16318
16319        final int layoutDirection = isLayoutDirectionResolved() ?
16320                getLayoutDirection() : getRawLayoutDirection();
16321
16322        if (mBackground != null) {
16323            mBackground.setLayoutDirection(layoutDirection);
16324        }
16325        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16326            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16327        }
16328        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16329        onResolveDrawables(layoutDirection);
16330    }
16331
16332    boolean areDrawablesResolved() {
16333        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16334    }
16335
16336    /**
16337     * Called when layout direction has been resolved.
16338     *
16339     * The default implementation does nothing.
16340     *
16341     * @param layoutDirection The resolved layout direction.
16342     *
16343     * @see #LAYOUT_DIRECTION_LTR
16344     * @see #LAYOUT_DIRECTION_RTL
16345     *
16346     * @hide
16347     */
16348    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16349    }
16350
16351    /**
16352     * @hide
16353     */
16354    protected void resetResolvedDrawables() {
16355        resetResolvedDrawablesInternal();
16356    }
16357
16358    void resetResolvedDrawablesInternal() {
16359        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16360    }
16361
16362    /**
16363     * If your view subclass is displaying its own Drawable objects, it should
16364     * override this function and return true for any Drawable it is
16365     * displaying.  This allows animations for those drawables to be
16366     * scheduled.
16367     *
16368     * <p>Be sure to call through to the super class when overriding this
16369     * function.
16370     *
16371     * @param who The Drawable to verify.  Return true if it is one you are
16372     *            displaying, else return the result of calling through to the
16373     *            super class.
16374     *
16375     * @return boolean If true than the Drawable is being displayed in the
16376     *         view; else false and it is not allowed to animate.
16377     *
16378     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16379     * @see #drawableStateChanged()
16380     */
16381    @CallSuper
16382    protected boolean verifyDrawable(Drawable who) {
16383        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16384                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16385    }
16386
16387    /**
16388     * This function is called whenever the state of the view changes in such
16389     * a way that it impacts the state of drawables being shown.
16390     * <p>
16391     * If the View has a StateListAnimator, it will also be called to run necessary state
16392     * change animations.
16393     * <p>
16394     * Be sure to call through to the superclass when overriding this function.
16395     *
16396     * @see Drawable#setState(int[])
16397     */
16398    @CallSuper
16399    protected void drawableStateChanged() {
16400        final int[] state = getDrawableState();
16401
16402        final Drawable bg = mBackground;
16403        if (bg != null && bg.isStateful()) {
16404            bg.setState(state);
16405        }
16406
16407        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16408        if (fg != null && fg.isStateful()) {
16409            fg.setState(state);
16410        }
16411
16412        if (mScrollCache != null) {
16413            final Drawable scrollBar = mScrollCache.scrollBar;
16414            if (scrollBar != null && scrollBar.isStateful()) {
16415                scrollBar.setState(state);
16416            }
16417        }
16418
16419        if (mStateListAnimator != null) {
16420            mStateListAnimator.setState(state);
16421        }
16422    }
16423
16424    /**
16425     * This function is called whenever the view hotspot changes and needs to
16426     * be propagated to drawables or child views managed by the view.
16427     * <p>
16428     * Dispatching to child views is handled by
16429     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16430     * <p>
16431     * Be sure to call through to the superclass when overriding this function.
16432     *
16433     * @param x hotspot x coordinate
16434     * @param y hotspot y coordinate
16435     */
16436    @CallSuper
16437    public void drawableHotspotChanged(float x, float y) {
16438        if (mBackground != null) {
16439            mBackground.setHotspot(x, y);
16440        }
16441        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16442            mForegroundInfo.mDrawable.setHotspot(x, y);
16443        }
16444
16445        dispatchDrawableHotspotChanged(x, y);
16446    }
16447
16448    /**
16449     * Dispatches drawableHotspotChanged to all of this View's children.
16450     *
16451     * @param x hotspot x coordinate
16452     * @param y hotspot y coordinate
16453     * @see #drawableHotspotChanged(float, float)
16454     */
16455    public void dispatchDrawableHotspotChanged(float x, float y) {
16456    }
16457
16458    /**
16459     * Call this to force a view to update its drawable state. This will cause
16460     * drawableStateChanged to be called on this view. Views that are interested
16461     * in the new state should call getDrawableState.
16462     *
16463     * @see #drawableStateChanged
16464     * @see #getDrawableState
16465     */
16466    public void refreshDrawableState() {
16467        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16468        drawableStateChanged();
16469
16470        ViewParent parent = mParent;
16471        if (parent != null) {
16472            parent.childDrawableStateChanged(this);
16473        }
16474    }
16475
16476    /**
16477     * Return an array of resource IDs of the drawable states representing the
16478     * current state of the view.
16479     *
16480     * @return The current drawable state
16481     *
16482     * @see Drawable#setState(int[])
16483     * @see #drawableStateChanged()
16484     * @see #onCreateDrawableState(int)
16485     */
16486    public final int[] getDrawableState() {
16487        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16488            return mDrawableState;
16489        } else {
16490            mDrawableState = onCreateDrawableState(0);
16491            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16492            return mDrawableState;
16493        }
16494    }
16495
16496    /**
16497     * Generate the new {@link android.graphics.drawable.Drawable} state for
16498     * this view. This is called by the view
16499     * system when the cached Drawable state is determined to be invalid.  To
16500     * retrieve the current state, you should use {@link #getDrawableState}.
16501     *
16502     * @param extraSpace if non-zero, this is the number of extra entries you
16503     * would like in the returned array in which you can place your own
16504     * states.
16505     *
16506     * @return Returns an array holding the current {@link Drawable} state of
16507     * the view.
16508     *
16509     * @see #mergeDrawableStates(int[], int[])
16510     */
16511    protected int[] onCreateDrawableState(int extraSpace) {
16512        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16513                mParent instanceof View) {
16514            return ((View) mParent).onCreateDrawableState(extraSpace);
16515        }
16516
16517        int[] drawableState;
16518
16519        int privateFlags = mPrivateFlags;
16520
16521        int viewStateIndex = 0;
16522        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16523        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16524        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16525        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16526        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16527        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16528        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16529                HardwareRenderer.isAvailable()) {
16530            // This is set if HW acceleration is requested, even if the current
16531            // process doesn't allow it.  This is just to allow app preview
16532            // windows to better match their app.
16533            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16534        }
16535        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16536
16537        final int privateFlags2 = mPrivateFlags2;
16538        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16539            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16540        }
16541        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16542            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16543        }
16544
16545        drawableState = StateSet.get(viewStateIndex);
16546
16547        //noinspection ConstantIfStatement
16548        if (false) {
16549            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16550            Log.i("View", toString()
16551                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16552                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16553                    + " fo=" + hasFocus()
16554                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16555                    + " wf=" + hasWindowFocus()
16556                    + ": " + Arrays.toString(drawableState));
16557        }
16558
16559        if (extraSpace == 0) {
16560            return drawableState;
16561        }
16562
16563        final int[] fullState;
16564        if (drawableState != null) {
16565            fullState = new int[drawableState.length + extraSpace];
16566            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16567        } else {
16568            fullState = new int[extraSpace];
16569        }
16570
16571        return fullState;
16572    }
16573
16574    /**
16575     * Merge your own state values in <var>additionalState</var> into the base
16576     * state values <var>baseState</var> that were returned by
16577     * {@link #onCreateDrawableState(int)}.
16578     *
16579     * @param baseState The base state values returned by
16580     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16581     * own additional state values.
16582     *
16583     * @param additionalState The additional state values you would like
16584     * added to <var>baseState</var>; this array is not modified.
16585     *
16586     * @return As a convenience, the <var>baseState</var> array you originally
16587     * passed into the function is returned.
16588     *
16589     * @see #onCreateDrawableState(int)
16590     */
16591    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16592        final int N = baseState.length;
16593        int i = N - 1;
16594        while (i >= 0 && baseState[i] == 0) {
16595            i--;
16596        }
16597        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16598        return baseState;
16599    }
16600
16601    /**
16602     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16603     * on all Drawable objects associated with this view.
16604     * <p>
16605     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16606     * attached to this view.
16607     */
16608    public void jumpDrawablesToCurrentState() {
16609        if (mBackground != null) {
16610            mBackground.jumpToCurrentState();
16611        }
16612        if (mStateListAnimator != null) {
16613            mStateListAnimator.jumpToCurrentState();
16614        }
16615        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16616            mForegroundInfo.mDrawable.jumpToCurrentState();
16617        }
16618    }
16619
16620    /**
16621     * Sets the background color for this view.
16622     * @param color the color of the background
16623     */
16624    @RemotableViewMethod
16625    public void setBackgroundColor(@ColorInt int color) {
16626        if (mBackground instanceof ColorDrawable) {
16627            ((ColorDrawable) mBackground.mutate()).setColor(color);
16628            computeOpaqueFlags();
16629            mBackgroundResource = 0;
16630        } else {
16631            setBackground(new ColorDrawable(color));
16632        }
16633    }
16634
16635    /**
16636     * If the view has a ColorDrawable background, returns the color of that
16637     * drawable.
16638     *
16639     * @return The color of the ColorDrawable background, if set, otherwise 0.
16640     */
16641    @ColorInt
16642    public int getBackgroundColor() {
16643        if (mBackground instanceof ColorDrawable) {
16644            return ((ColorDrawable) mBackground).getColor();
16645        }
16646        return 0;
16647    }
16648
16649    /**
16650     * Set the background to a given resource. The resource should refer to
16651     * a Drawable object or 0 to remove the background.
16652     * @param resid The identifier of the resource.
16653     *
16654     * @attr ref android.R.styleable#View_background
16655     */
16656    @RemotableViewMethod
16657    public void setBackgroundResource(@DrawableRes int resid) {
16658        if (resid != 0 && resid == mBackgroundResource) {
16659            return;
16660        }
16661
16662        Drawable d = null;
16663        if (resid != 0) {
16664            d = mContext.getDrawable(resid);
16665        }
16666        setBackground(d);
16667
16668        mBackgroundResource = resid;
16669    }
16670
16671    /**
16672     * Set the background to a given Drawable, or remove the background. If the
16673     * background has padding, this View's padding is set to the background's
16674     * padding. However, when a background is removed, this View's padding isn't
16675     * touched. If setting the padding is desired, please use
16676     * {@link #setPadding(int, int, int, int)}.
16677     *
16678     * @param background The Drawable to use as the background, or null to remove the
16679     *        background
16680     */
16681    public void setBackground(Drawable background) {
16682        //noinspection deprecation
16683        setBackgroundDrawable(background);
16684    }
16685
16686    /**
16687     * @deprecated use {@link #setBackground(Drawable)} instead
16688     */
16689    @Deprecated
16690    public void setBackgroundDrawable(Drawable background) {
16691        computeOpaqueFlags();
16692
16693        if (background == mBackground) {
16694            return;
16695        }
16696
16697        boolean requestLayout = false;
16698
16699        mBackgroundResource = 0;
16700
16701        /*
16702         * Regardless of whether we're setting a new background or not, we want
16703         * to clear the previous drawable.
16704         */
16705        if (mBackground != null) {
16706            mBackground.setCallback(null);
16707            unscheduleDrawable(mBackground);
16708        }
16709
16710        if (background != null) {
16711            Rect padding = sThreadLocal.get();
16712            if (padding == null) {
16713                padding = new Rect();
16714                sThreadLocal.set(padding);
16715            }
16716            resetResolvedDrawablesInternal();
16717            background.setLayoutDirection(getLayoutDirection());
16718            if (background.getPadding(padding)) {
16719                resetResolvedPaddingInternal();
16720                switch (background.getLayoutDirection()) {
16721                    case LAYOUT_DIRECTION_RTL:
16722                        mUserPaddingLeftInitial = padding.right;
16723                        mUserPaddingRightInitial = padding.left;
16724                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16725                        break;
16726                    case LAYOUT_DIRECTION_LTR:
16727                    default:
16728                        mUserPaddingLeftInitial = padding.left;
16729                        mUserPaddingRightInitial = padding.right;
16730                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16731                }
16732                mLeftPaddingDefined = false;
16733                mRightPaddingDefined = false;
16734            }
16735
16736            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16737            // if it has a different minimum size, we should layout again
16738            if (mBackground == null
16739                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16740                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16741                requestLayout = true;
16742            }
16743
16744            background.setCallback(this);
16745            if (background.isStateful()) {
16746                background.setState(getDrawableState());
16747            }
16748            background.setVisible(getVisibility() == VISIBLE, false);
16749            mBackground = background;
16750
16751            applyBackgroundTint();
16752
16753            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16754                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16755                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16756                requestLayout = true;
16757            }
16758        } else {
16759            /* Remove the background */
16760            mBackground = null;
16761
16762            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16763                /*
16764                 * This view ONLY drew the background before and we're removing
16765                 * the background, so now it won't draw anything
16766                 * (hence we SKIP_DRAW)
16767                 */
16768                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16769                mPrivateFlags |= PFLAG_SKIP_DRAW;
16770            }
16771
16772            /*
16773             * When the background is set, we try to apply its padding to this
16774             * View. When the background is removed, we don't touch this View's
16775             * padding. This is noted in the Javadocs. Hence, we don't need to
16776             * requestLayout(), the invalidate() below is sufficient.
16777             */
16778
16779            // The old background's minimum size could have affected this
16780            // View's layout, so let's requestLayout
16781            requestLayout = true;
16782        }
16783
16784        computeOpaqueFlags();
16785
16786        if (requestLayout) {
16787            requestLayout();
16788        }
16789
16790        mBackgroundSizeChanged = true;
16791        invalidate(true);
16792    }
16793
16794    /**
16795     * Gets the background drawable
16796     *
16797     * @return The drawable used as the background for this view, if any.
16798     *
16799     * @see #setBackground(Drawable)
16800     *
16801     * @attr ref android.R.styleable#View_background
16802     */
16803    public Drawable getBackground() {
16804        return mBackground;
16805    }
16806
16807    /**
16808     * Applies a tint to the background drawable. Does not modify the current tint
16809     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16810     * <p>
16811     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16812     * mutate the drawable and apply the specified tint and tint mode using
16813     * {@link Drawable#setTintList(ColorStateList)}.
16814     *
16815     * @param tint the tint to apply, may be {@code null} to clear tint
16816     *
16817     * @attr ref android.R.styleable#View_backgroundTint
16818     * @see #getBackgroundTintList()
16819     * @see Drawable#setTintList(ColorStateList)
16820     */
16821    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16822        if (mBackgroundTint == null) {
16823            mBackgroundTint = new TintInfo();
16824        }
16825        mBackgroundTint.mTintList = tint;
16826        mBackgroundTint.mHasTintList = true;
16827
16828        applyBackgroundTint();
16829    }
16830
16831    /**
16832     * Return the tint applied to the background drawable, if specified.
16833     *
16834     * @return the tint applied to the background drawable
16835     * @attr ref android.R.styleable#View_backgroundTint
16836     * @see #setBackgroundTintList(ColorStateList)
16837     */
16838    @Nullable
16839    public ColorStateList getBackgroundTintList() {
16840        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16841    }
16842
16843    /**
16844     * Specifies the blending mode used to apply the tint specified by
16845     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16846     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16847     *
16848     * @param tintMode the blending mode used to apply the tint, may be
16849     *                 {@code null} to clear tint
16850     * @attr ref android.R.styleable#View_backgroundTintMode
16851     * @see #getBackgroundTintMode()
16852     * @see Drawable#setTintMode(PorterDuff.Mode)
16853     */
16854    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16855        if (mBackgroundTint == null) {
16856            mBackgroundTint = new TintInfo();
16857        }
16858        mBackgroundTint.mTintMode = tintMode;
16859        mBackgroundTint.mHasTintMode = true;
16860
16861        applyBackgroundTint();
16862    }
16863
16864    /**
16865     * Return the blending mode used to apply the tint to the background
16866     * drawable, if specified.
16867     *
16868     * @return the blending mode used to apply the tint to the background
16869     *         drawable
16870     * @attr ref android.R.styleable#View_backgroundTintMode
16871     * @see #setBackgroundTintMode(PorterDuff.Mode)
16872     */
16873    @Nullable
16874    public PorterDuff.Mode getBackgroundTintMode() {
16875        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16876    }
16877
16878    private void applyBackgroundTint() {
16879        if (mBackground != null && mBackgroundTint != null) {
16880            final TintInfo tintInfo = mBackgroundTint;
16881            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16882                mBackground = mBackground.mutate();
16883
16884                if (tintInfo.mHasTintList) {
16885                    mBackground.setTintList(tintInfo.mTintList);
16886                }
16887
16888                if (tintInfo.mHasTintMode) {
16889                    mBackground.setTintMode(tintInfo.mTintMode);
16890                }
16891
16892                // The drawable (or one of its children) may not have been
16893                // stateful before applying the tint, so let's try again.
16894                if (mBackground.isStateful()) {
16895                    mBackground.setState(getDrawableState());
16896                }
16897            }
16898        }
16899    }
16900
16901    /**
16902     * Returns the drawable used as the foreground of this View. The
16903     * foreground drawable, if non-null, is always drawn on top of the view's content.
16904     *
16905     * @return a Drawable or null if no foreground was set
16906     *
16907     * @see #onDrawForeground(Canvas)
16908     */
16909    public Drawable getForeground() {
16910        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16911    }
16912
16913    /**
16914     * Supply a Drawable that is to be rendered on top of all of the content in the view.
16915     *
16916     * @param foreground the Drawable to be drawn on top of the children
16917     *
16918     * @attr ref android.R.styleable#View_foreground
16919     */
16920    public void setForeground(Drawable foreground) {
16921        if (mForegroundInfo == null) {
16922            if (foreground == null) {
16923                // Nothing to do.
16924                return;
16925            }
16926            mForegroundInfo = new ForegroundInfo();
16927        }
16928
16929        if (foreground == mForegroundInfo.mDrawable) {
16930            // Nothing to do
16931            return;
16932        }
16933
16934        if (mForegroundInfo.mDrawable != null) {
16935            mForegroundInfo.mDrawable.setCallback(null);
16936            unscheduleDrawable(mForegroundInfo.mDrawable);
16937        }
16938
16939        mForegroundInfo.mDrawable = foreground;
16940        mForegroundInfo.mBoundsChanged = true;
16941        if (foreground != null) {
16942            setWillNotDraw(false);
16943            foreground.setCallback(this);
16944            foreground.setLayoutDirection(getLayoutDirection());
16945            if (foreground.isStateful()) {
16946                foreground.setState(getDrawableState());
16947            }
16948            applyForegroundTint();
16949        }
16950        requestLayout();
16951        invalidate();
16952    }
16953
16954    /**
16955     * Magic bit used to support features of framework-internal window decor implementation details.
16956     * This used to live exclusively in FrameLayout.
16957     *
16958     * @return true if the foreground should draw inside the padding region or false
16959     *         if it should draw inset by the view's padding
16960     * @hide internal use only; only used by FrameLayout and internal screen layouts.
16961     */
16962    public boolean isForegroundInsidePadding() {
16963        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
16964    }
16965
16966    /**
16967     * Describes how the foreground is positioned.
16968     *
16969     * @return foreground gravity.
16970     *
16971     * @see #setForegroundGravity(int)
16972     *
16973     * @attr ref android.R.styleable#View_foregroundGravity
16974     */
16975    public int getForegroundGravity() {
16976        return mForegroundInfo != null ? mForegroundInfo.mGravity
16977                : Gravity.START | Gravity.TOP;
16978    }
16979
16980    /**
16981     * Describes how the foreground is positioned. Defaults to START and TOP.
16982     *
16983     * @param gravity see {@link android.view.Gravity}
16984     *
16985     * @see #getForegroundGravity()
16986     *
16987     * @attr ref android.R.styleable#View_foregroundGravity
16988     */
16989    public void setForegroundGravity(int gravity) {
16990        if (mForegroundInfo == null) {
16991            mForegroundInfo = new ForegroundInfo();
16992        }
16993
16994        if (mForegroundInfo.mGravity != gravity) {
16995            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
16996                gravity |= Gravity.START;
16997            }
16998
16999            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
17000                gravity |= Gravity.TOP;
17001            }
17002
17003            mForegroundInfo.mGravity = gravity;
17004            requestLayout();
17005        }
17006    }
17007
17008    /**
17009     * Applies a tint to the foreground drawable. Does not modify the current tint
17010     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17011     * <p>
17012     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
17013     * mutate the drawable and apply the specified tint and tint mode using
17014     * {@link Drawable#setTintList(ColorStateList)}.
17015     *
17016     * @param tint the tint to apply, may be {@code null} to clear tint
17017     *
17018     * @attr ref android.R.styleable#View_foregroundTint
17019     * @see #getForegroundTintList()
17020     * @see Drawable#setTintList(ColorStateList)
17021     */
17022    public void setForegroundTintList(@Nullable ColorStateList tint) {
17023        if (mForegroundInfo == null) {
17024            mForegroundInfo = new ForegroundInfo();
17025        }
17026        if (mForegroundInfo.mTintInfo == null) {
17027            mForegroundInfo.mTintInfo = new TintInfo();
17028        }
17029        mForegroundInfo.mTintInfo.mTintList = tint;
17030        mForegroundInfo.mTintInfo.mHasTintList = true;
17031
17032        applyForegroundTint();
17033    }
17034
17035    /**
17036     * Return the tint applied to the foreground drawable, if specified.
17037     *
17038     * @return the tint applied to the foreground drawable
17039     * @attr ref android.R.styleable#View_foregroundTint
17040     * @see #setForegroundTintList(ColorStateList)
17041     */
17042    @Nullable
17043    public ColorStateList getForegroundTintList() {
17044        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17045                ? mForegroundInfo.mTintInfo.mTintList : null;
17046    }
17047
17048    /**
17049     * Specifies the blending mode used to apply the tint specified by
17050     * {@link #setForegroundTintList(ColorStateList)}} to the background
17051     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17052     *
17053     * @param tintMode the blending mode used to apply the tint, may be
17054     *                 {@code null} to clear tint
17055     * @attr ref android.R.styleable#View_foregroundTintMode
17056     * @see #getForegroundTintMode()
17057     * @see Drawable#setTintMode(PorterDuff.Mode)
17058     */
17059    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17060        if (mBackgroundTint == null) {
17061            mBackgroundTint = new TintInfo();
17062        }
17063        mBackgroundTint.mTintMode = tintMode;
17064        mBackgroundTint.mHasTintMode = true;
17065
17066        applyBackgroundTint();
17067    }
17068
17069    /**
17070     * Return the blending mode used to apply the tint to the foreground
17071     * drawable, if specified.
17072     *
17073     * @return the blending mode used to apply the tint to the foreground
17074     *         drawable
17075     * @attr ref android.R.styleable#View_foregroundTintMode
17076     * @see #setBackgroundTintMode(PorterDuff.Mode)
17077     */
17078    @Nullable
17079    public PorterDuff.Mode getForegroundTintMode() {
17080        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17081                ? mForegroundInfo.mTintInfo.mTintMode : null;
17082    }
17083
17084    private void applyForegroundTint() {
17085        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17086                && mForegroundInfo.mTintInfo != null) {
17087            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17088            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17089                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17090
17091                if (tintInfo.mHasTintList) {
17092                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17093                }
17094
17095                if (tintInfo.mHasTintMode) {
17096                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17097                }
17098
17099                // The drawable (or one of its children) may not have been
17100                // stateful before applying the tint, so let's try again.
17101                if (mForegroundInfo.mDrawable.isStateful()) {
17102                    mForegroundInfo.mDrawable.setState(getDrawableState());
17103                }
17104            }
17105        }
17106    }
17107
17108    /**
17109     * Draw any foreground content for this view.
17110     *
17111     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17112     * drawable or other view-specific decorations. The foreground is drawn on top of the
17113     * primary view content.</p>
17114     *
17115     * @param canvas canvas to draw into
17116     */
17117    public void onDrawForeground(Canvas canvas) {
17118        onDrawScrollBars(canvas);
17119
17120        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17121        if (foreground != null) {
17122            if (mForegroundInfo.mBoundsChanged) {
17123                mForegroundInfo.mBoundsChanged = false;
17124                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17125                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17126
17127                if (mForegroundInfo.mInsidePadding) {
17128                    selfBounds.set(0, 0, getWidth(), getHeight());
17129                } else {
17130                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17131                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17132                }
17133
17134                final int ld = getLayoutDirection();
17135                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17136                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17137                foreground.setBounds(overlayBounds);
17138            }
17139
17140            foreground.draw(canvas);
17141        }
17142    }
17143
17144    /**
17145     * Sets the padding. The view may add on the space required to display
17146     * the scrollbars, depending on the style and visibility of the scrollbars.
17147     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17148     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17149     * from the values set in this call.
17150     *
17151     * @attr ref android.R.styleable#View_padding
17152     * @attr ref android.R.styleable#View_paddingBottom
17153     * @attr ref android.R.styleable#View_paddingLeft
17154     * @attr ref android.R.styleable#View_paddingRight
17155     * @attr ref android.R.styleable#View_paddingTop
17156     * @param left the left padding in pixels
17157     * @param top the top padding in pixels
17158     * @param right the right padding in pixels
17159     * @param bottom the bottom padding in pixels
17160     */
17161    public void setPadding(int left, int top, int right, int bottom) {
17162        resetResolvedPaddingInternal();
17163
17164        mUserPaddingStart = UNDEFINED_PADDING;
17165        mUserPaddingEnd = UNDEFINED_PADDING;
17166
17167        mUserPaddingLeftInitial = left;
17168        mUserPaddingRightInitial = right;
17169
17170        mLeftPaddingDefined = true;
17171        mRightPaddingDefined = true;
17172
17173        internalSetPadding(left, top, right, bottom);
17174    }
17175
17176    /**
17177     * @hide
17178     */
17179    protected void internalSetPadding(int left, int top, int right, int bottom) {
17180        mUserPaddingLeft = left;
17181        mUserPaddingRight = right;
17182        mUserPaddingBottom = bottom;
17183
17184        final int viewFlags = mViewFlags;
17185        boolean changed = false;
17186
17187        // Common case is there are no scroll bars.
17188        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17189            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17190                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17191                        ? 0 : getVerticalScrollbarWidth();
17192                switch (mVerticalScrollbarPosition) {
17193                    case SCROLLBAR_POSITION_DEFAULT:
17194                        if (isLayoutRtl()) {
17195                            left += offset;
17196                        } else {
17197                            right += offset;
17198                        }
17199                        break;
17200                    case SCROLLBAR_POSITION_RIGHT:
17201                        right += offset;
17202                        break;
17203                    case SCROLLBAR_POSITION_LEFT:
17204                        left += offset;
17205                        break;
17206                }
17207            }
17208            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17209                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17210                        ? 0 : getHorizontalScrollbarHeight();
17211            }
17212        }
17213
17214        if (mPaddingLeft != left) {
17215            changed = true;
17216            mPaddingLeft = left;
17217        }
17218        if (mPaddingTop != top) {
17219            changed = true;
17220            mPaddingTop = top;
17221        }
17222        if (mPaddingRight != right) {
17223            changed = true;
17224            mPaddingRight = right;
17225        }
17226        if (mPaddingBottom != bottom) {
17227            changed = true;
17228            mPaddingBottom = bottom;
17229        }
17230
17231        if (changed) {
17232            requestLayout();
17233            invalidateOutline();
17234        }
17235    }
17236
17237    /**
17238     * Sets the relative padding. The view may add on the space required to display
17239     * the scrollbars, depending on the style and visibility of the scrollbars.
17240     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17241     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17242     * from the values set in this call.
17243     *
17244     * @attr ref android.R.styleable#View_padding
17245     * @attr ref android.R.styleable#View_paddingBottom
17246     * @attr ref android.R.styleable#View_paddingStart
17247     * @attr ref android.R.styleable#View_paddingEnd
17248     * @attr ref android.R.styleable#View_paddingTop
17249     * @param start the start padding in pixels
17250     * @param top the top padding in pixels
17251     * @param end the end padding in pixels
17252     * @param bottom the bottom padding in pixels
17253     */
17254    public void setPaddingRelative(int start, int top, int end, int bottom) {
17255        resetResolvedPaddingInternal();
17256
17257        mUserPaddingStart = start;
17258        mUserPaddingEnd = end;
17259        mLeftPaddingDefined = true;
17260        mRightPaddingDefined = true;
17261
17262        switch(getLayoutDirection()) {
17263            case LAYOUT_DIRECTION_RTL:
17264                mUserPaddingLeftInitial = end;
17265                mUserPaddingRightInitial = start;
17266                internalSetPadding(end, top, start, bottom);
17267                break;
17268            case LAYOUT_DIRECTION_LTR:
17269            default:
17270                mUserPaddingLeftInitial = start;
17271                mUserPaddingRightInitial = end;
17272                internalSetPadding(start, top, end, bottom);
17273        }
17274    }
17275
17276    /**
17277     * Returns the top padding of this view.
17278     *
17279     * @return the top padding in pixels
17280     */
17281    public int getPaddingTop() {
17282        return mPaddingTop;
17283    }
17284
17285    /**
17286     * Returns the bottom padding of this view. If there are inset and enabled
17287     * scrollbars, this value may include the space required to display the
17288     * scrollbars as well.
17289     *
17290     * @return the bottom padding in pixels
17291     */
17292    public int getPaddingBottom() {
17293        return mPaddingBottom;
17294    }
17295
17296    /**
17297     * Returns the left padding of this view. If there are inset and enabled
17298     * scrollbars, this value may include the space required to display the
17299     * scrollbars as well.
17300     *
17301     * @return the left padding in pixels
17302     */
17303    public int getPaddingLeft() {
17304        if (!isPaddingResolved()) {
17305            resolvePadding();
17306        }
17307        return mPaddingLeft;
17308    }
17309
17310    /**
17311     * Returns the start padding of this view depending on its resolved layout direction.
17312     * If there are inset and enabled scrollbars, this value may include the space
17313     * required to display the scrollbars as well.
17314     *
17315     * @return the start padding in pixels
17316     */
17317    public int getPaddingStart() {
17318        if (!isPaddingResolved()) {
17319            resolvePadding();
17320        }
17321        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17322                mPaddingRight : mPaddingLeft;
17323    }
17324
17325    /**
17326     * Returns the right padding of this view. If there are inset and enabled
17327     * scrollbars, this value may include the space required to display the
17328     * scrollbars as well.
17329     *
17330     * @return the right padding in pixels
17331     */
17332    public int getPaddingRight() {
17333        if (!isPaddingResolved()) {
17334            resolvePadding();
17335        }
17336        return mPaddingRight;
17337    }
17338
17339    /**
17340     * Returns the end padding of this view depending on its resolved layout direction.
17341     * If there are inset and enabled scrollbars, this value may include the space
17342     * required to display the scrollbars as well.
17343     *
17344     * @return the end padding in pixels
17345     */
17346    public int getPaddingEnd() {
17347        if (!isPaddingResolved()) {
17348            resolvePadding();
17349        }
17350        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17351                mPaddingLeft : mPaddingRight;
17352    }
17353
17354    /**
17355     * Return if the padding has been set through relative values
17356     * {@link #setPaddingRelative(int, int, int, int)} or through
17357     * @attr ref android.R.styleable#View_paddingStart or
17358     * @attr ref android.R.styleable#View_paddingEnd
17359     *
17360     * @return true if the padding is relative or false if it is not.
17361     */
17362    public boolean isPaddingRelative() {
17363        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17364    }
17365
17366    Insets computeOpticalInsets() {
17367        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17368    }
17369
17370    /**
17371     * @hide
17372     */
17373    public void resetPaddingToInitialValues() {
17374        if (isRtlCompatibilityMode()) {
17375            mPaddingLeft = mUserPaddingLeftInitial;
17376            mPaddingRight = mUserPaddingRightInitial;
17377            return;
17378        }
17379        if (isLayoutRtl()) {
17380            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17381            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17382        } else {
17383            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17384            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17385        }
17386    }
17387
17388    /**
17389     * @hide
17390     */
17391    public Insets getOpticalInsets() {
17392        if (mLayoutInsets == null) {
17393            mLayoutInsets = computeOpticalInsets();
17394        }
17395        return mLayoutInsets;
17396    }
17397
17398    /**
17399     * Set this view's optical insets.
17400     *
17401     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17402     * property. Views that compute their own optical insets should call it as part of measurement.
17403     * This method does not request layout. If you are setting optical insets outside of
17404     * measure/layout itself you will want to call requestLayout() yourself.
17405     * </p>
17406     * @hide
17407     */
17408    public void setOpticalInsets(Insets insets) {
17409        mLayoutInsets = insets;
17410    }
17411
17412    /**
17413     * Changes the selection state of this view. A view can be selected or not.
17414     * Note that selection is not the same as focus. Views are typically
17415     * selected in the context of an AdapterView like ListView or GridView;
17416     * the selected view is the view that is highlighted.
17417     *
17418     * @param selected true if the view must be selected, false otherwise
17419     */
17420    public void setSelected(boolean selected) {
17421        //noinspection DoubleNegation
17422        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17423            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17424            if (!selected) resetPressedState();
17425            invalidate(true);
17426            refreshDrawableState();
17427            dispatchSetSelected(selected);
17428            if (selected) {
17429                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17430            } else {
17431                notifyViewAccessibilityStateChangedIfNeeded(
17432                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17433            }
17434        }
17435    }
17436
17437    /**
17438     * Dispatch setSelected to all of this View's children.
17439     *
17440     * @see #setSelected(boolean)
17441     *
17442     * @param selected The new selected state
17443     */
17444    protected void dispatchSetSelected(boolean selected) {
17445    }
17446
17447    /**
17448     * Indicates the selection state of this view.
17449     *
17450     * @return true if the view is selected, false otherwise
17451     */
17452    @ViewDebug.ExportedProperty
17453    public boolean isSelected() {
17454        return (mPrivateFlags & PFLAG_SELECTED) != 0;
17455    }
17456
17457    /**
17458     * Changes the activated state of this view. A view can be activated or not.
17459     * Note that activation is not the same as selection.  Selection is
17460     * a transient property, representing the view (hierarchy) the user is
17461     * currently interacting with.  Activation is a longer-term state that the
17462     * user can move views in and out of.  For example, in a list view with
17463     * single or multiple selection enabled, the views in the current selection
17464     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
17465     * here.)  The activated state is propagated down to children of the view it
17466     * is set on.
17467     *
17468     * @param activated true if the view must be activated, false otherwise
17469     */
17470    public void setActivated(boolean activated) {
17471        //noinspection DoubleNegation
17472        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
17473            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
17474            invalidate(true);
17475            refreshDrawableState();
17476            dispatchSetActivated(activated);
17477        }
17478    }
17479
17480    /**
17481     * Dispatch setActivated to all of this View's children.
17482     *
17483     * @see #setActivated(boolean)
17484     *
17485     * @param activated The new activated state
17486     */
17487    protected void dispatchSetActivated(boolean activated) {
17488    }
17489
17490    /**
17491     * Indicates the activation state of this view.
17492     *
17493     * @return true if the view is activated, false otherwise
17494     */
17495    @ViewDebug.ExportedProperty
17496    public boolean isActivated() {
17497        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
17498    }
17499
17500    /**
17501     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
17502     * observer can be used to get notifications when global events, like
17503     * layout, happen.
17504     *
17505     * The returned ViewTreeObserver observer is not guaranteed to remain
17506     * valid for the lifetime of this View. If the caller of this method keeps
17507     * a long-lived reference to ViewTreeObserver, it should always check for
17508     * the return value of {@link ViewTreeObserver#isAlive()}.
17509     *
17510     * @return The ViewTreeObserver for this view's hierarchy.
17511     */
17512    public ViewTreeObserver getViewTreeObserver() {
17513        if (mAttachInfo != null) {
17514            return mAttachInfo.mTreeObserver;
17515        }
17516        if (mFloatingTreeObserver == null) {
17517            mFloatingTreeObserver = new ViewTreeObserver();
17518        }
17519        return mFloatingTreeObserver;
17520    }
17521
17522    /**
17523     * <p>Finds the topmost view in the current view hierarchy.</p>
17524     *
17525     * @return the topmost view containing this view
17526     */
17527    public View getRootView() {
17528        if (mAttachInfo != null) {
17529            final View v = mAttachInfo.mRootView;
17530            if (v != null) {
17531                return v;
17532            }
17533        }
17534
17535        View parent = this;
17536
17537        while (parent.mParent != null && parent.mParent instanceof View) {
17538            parent = (View) parent.mParent;
17539        }
17540
17541        return parent;
17542    }
17543
17544    /**
17545     * Transforms a motion event from view-local coordinates to on-screen
17546     * coordinates.
17547     *
17548     * @param ev the view-local motion event
17549     * @return false if the transformation could not be applied
17550     * @hide
17551     */
17552    public boolean toGlobalMotionEvent(MotionEvent ev) {
17553        final AttachInfo info = mAttachInfo;
17554        if (info == null) {
17555            return false;
17556        }
17557
17558        final Matrix m = info.mTmpMatrix;
17559        m.set(Matrix.IDENTITY_MATRIX);
17560        transformMatrixToGlobal(m);
17561        ev.transform(m);
17562        return true;
17563    }
17564
17565    /**
17566     * Transforms a motion event from on-screen coordinates to view-local
17567     * coordinates.
17568     *
17569     * @param ev the on-screen motion event
17570     * @return false if the transformation could not be applied
17571     * @hide
17572     */
17573    public boolean toLocalMotionEvent(MotionEvent ev) {
17574        final AttachInfo info = mAttachInfo;
17575        if (info == null) {
17576            return false;
17577        }
17578
17579        final Matrix m = info.mTmpMatrix;
17580        m.set(Matrix.IDENTITY_MATRIX);
17581        transformMatrixToLocal(m);
17582        ev.transform(m);
17583        return true;
17584    }
17585
17586    /**
17587     * Modifies the input matrix such that it maps view-local coordinates to
17588     * on-screen coordinates.
17589     *
17590     * @param m input matrix to modify
17591     * @hide
17592     */
17593    public void transformMatrixToGlobal(Matrix m) {
17594        final ViewParent parent = mParent;
17595        if (parent instanceof View) {
17596            final View vp = (View) parent;
17597            vp.transformMatrixToGlobal(m);
17598            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
17599        } else if (parent instanceof ViewRootImpl) {
17600            final ViewRootImpl vr = (ViewRootImpl) parent;
17601            vr.transformMatrixToGlobal(m);
17602            m.preTranslate(0, -vr.mCurScrollY);
17603        }
17604
17605        m.preTranslate(mLeft, mTop);
17606
17607        if (!hasIdentityMatrix()) {
17608            m.preConcat(getMatrix());
17609        }
17610    }
17611
17612    /**
17613     * Modifies the input matrix such that it maps on-screen coordinates to
17614     * view-local coordinates.
17615     *
17616     * @param m input matrix to modify
17617     * @hide
17618     */
17619    public void transformMatrixToLocal(Matrix m) {
17620        final ViewParent parent = mParent;
17621        if (parent instanceof View) {
17622            final View vp = (View) parent;
17623            vp.transformMatrixToLocal(m);
17624            m.postTranslate(vp.mScrollX, vp.mScrollY);
17625        } else if (parent instanceof ViewRootImpl) {
17626            final ViewRootImpl vr = (ViewRootImpl) parent;
17627            vr.transformMatrixToLocal(m);
17628            m.postTranslate(0, vr.mCurScrollY);
17629        }
17630
17631        m.postTranslate(-mLeft, -mTop);
17632
17633        if (!hasIdentityMatrix()) {
17634            m.postConcat(getInverseMatrix());
17635        }
17636    }
17637
17638    /**
17639     * @hide
17640     */
17641    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17642            @ViewDebug.IntToString(from = 0, to = "x"),
17643            @ViewDebug.IntToString(from = 1, to = "y")
17644    })
17645    public int[] getLocationOnScreen() {
17646        int[] location = new int[2];
17647        getLocationOnScreen(location);
17648        return location;
17649    }
17650
17651    /**
17652     * <p>Computes the coordinates of this view on the screen. The argument
17653     * must be an array of two integers. After the method returns, the array
17654     * contains the x and y location in that order.</p>
17655     *
17656     * @param location an array of two integers in which to hold the coordinates
17657     */
17658    public void getLocationOnScreen(@Size(2) int[] location) {
17659        getLocationInWindow(location);
17660
17661        final AttachInfo info = mAttachInfo;
17662        if (info != null) {
17663            location[0] += info.mWindowLeft;
17664            location[1] += info.mWindowTop;
17665        }
17666    }
17667
17668    /**
17669     * <p>Computes the coordinates of this view in its window. The argument
17670     * must be an array of two integers. After the method returns, the array
17671     * contains the x and y location in that order.</p>
17672     *
17673     * @param location an array of two integers in which to hold the coordinates
17674     */
17675    public void getLocationInWindow(@Size(2) int[] location) {
17676        if (location == null || location.length < 2) {
17677            throw new IllegalArgumentException("location must be an array of two integers");
17678        }
17679
17680        if (mAttachInfo == null) {
17681            // When the view is not attached to a window, this method does not make sense
17682            location[0] = location[1] = 0;
17683            return;
17684        }
17685
17686        float[] position = mAttachInfo.mTmpTransformLocation;
17687        position[0] = position[1] = 0.0f;
17688
17689        if (!hasIdentityMatrix()) {
17690            getMatrix().mapPoints(position);
17691        }
17692
17693        position[0] += mLeft;
17694        position[1] += mTop;
17695
17696        ViewParent viewParent = mParent;
17697        while (viewParent instanceof View) {
17698            final View view = (View) viewParent;
17699
17700            position[0] -= view.mScrollX;
17701            position[1] -= view.mScrollY;
17702
17703            if (!view.hasIdentityMatrix()) {
17704                view.getMatrix().mapPoints(position);
17705            }
17706
17707            position[0] += view.mLeft;
17708            position[1] += view.mTop;
17709
17710            viewParent = view.mParent;
17711         }
17712
17713        if (viewParent instanceof ViewRootImpl) {
17714            // *cough*
17715            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17716            position[1] -= vr.mCurScrollY;
17717        }
17718
17719        location[0] = (int) (position[0] + 0.5f);
17720        location[1] = (int) (position[1] + 0.5f);
17721    }
17722
17723    /**
17724     * {@hide}
17725     * @param id the id of the view to be found
17726     * @return the view of the specified id, null if cannot be found
17727     */
17728    protected View findViewTraversal(@IdRes int id) {
17729        if (id == mID) {
17730            return this;
17731        }
17732        return null;
17733    }
17734
17735    /**
17736     * {@hide}
17737     * @param tag the tag of the view to be found
17738     * @return the view of specified tag, null if cannot be found
17739     */
17740    protected View findViewWithTagTraversal(Object tag) {
17741        if (tag != null && tag.equals(mTag)) {
17742            return this;
17743        }
17744        return null;
17745    }
17746
17747    /**
17748     * {@hide}
17749     * @param predicate The predicate to evaluate.
17750     * @param childToSkip If not null, ignores this child during the recursive traversal.
17751     * @return The first view that matches the predicate or null.
17752     */
17753    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17754        if (predicate.apply(this)) {
17755            return this;
17756        }
17757        return null;
17758    }
17759
17760    /**
17761     * Look for a child view with the given id.  If this view has the given
17762     * id, return this view.
17763     *
17764     * @param id The id to search for.
17765     * @return The view that has the given id in the hierarchy or null
17766     */
17767    @Nullable
17768    public final View findViewById(@IdRes int id) {
17769        if (id < 0) {
17770            return null;
17771        }
17772        return findViewTraversal(id);
17773    }
17774
17775    /**
17776     * Finds a view by its unuque and stable accessibility id.
17777     *
17778     * @param accessibilityId The searched accessibility id.
17779     * @return The found view.
17780     */
17781    final View findViewByAccessibilityId(int accessibilityId) {
17782        if (accessibilityId < 0) {
17783            return null;
17784        }
17785        return findViewByAccessibilityIdTraversal(accessibilityId);
17786    }
17787
17788    /**
17789     * Performs the traversal to find a view by its unuque and stable accessibility id.
17790     *
17791     * <strong>Note:</strong>This method does not stop at the root namespace
17792     * boundary since the user can touch the screen at an arbitrary location
17793     * potentially crossing the root namespace bounday which will send an
17794     * accessibility event to accessibility services and they should be able
17795     * to obtain the event source. Also accessibility ids are guaranteed to be
17796     * unique in the window.
17797     *
17798     * @param accessibilityId The accessibility id.
17799     * @return The found view.
17800     *
17801     * @hide
17802     */
17803    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17804        if (getAccessibilityViewId() == accessibilityId) {
17805            return this;
17806        }
17807        return null;
17808    }
17809
17810    /**
17811     * Look for a child view with the given tag.  If this view has the given
17812     * tag, return this view.
17813     *
17814     * @param tag The tag to search for, using "tag.equals(getTag())".
17815     * @return The View that has the given tag in the hierarchy or null
17816     */
17817    public final View findViewWithTag(Object tag) {
17818        if (tag == null) {
17819            return null;
17820        }
17821        return findViewWithTagTraversal(tag);
17822    }
17823
17824    /**
17825     * {@hide}
17826     * Look for a child view that matches the specified predicate.
17827     * If this view matches the predicate, return this view.
17828     *
17829     * @param predicate The predicate to evaluate.
17830     * @return The first view that matches the predicate or null.
17831     */
17832    public final View findViewByPredicate(Predicate<View> predicate) {
17833        return findViewByPredicateTraversal(predicate, null);
17834    }
17835
17836    /**
17837     * {@hide}
17838     * Look for a child view that matches the specified predicate,
17839     * starting with the specified view and its descendents and then
17840     * recusively searching the ancestors and siblings of that view
17841     * until this view is reached.
17842     *
17843     * This method is useful in cases where the predicate does not match
17844     * a single unique view (perhaps multiple views use the same id)
17845     * and we are trying to find the view that is "closest" in scope to the
17846     * starting view.
17847     *
17848     * @param start The view to start from.
17849     * @param predicate The predicate to evaluate.
17850     * @return The first view that matches the predicate or null.
17851     */
17852    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17853        View childToSkip = null;
17854        for (;;) {
17855            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17856            if (view != null || start == this) {
17857                return view;
17858            }
17859
17860            ViewParent parent = start.getParent();
17861            if (parent == null || !(parent instanceof View)) {
17862                return null;
17863            }
17864
17865            childToSkip = start;
17866            start = (View) parent;
17867        }
17868    }
17869
17870    /**
17871     * Sets the identifier for this view. The identifier does not have to be
17872     * unique in this view's hierarchy. The identifier should be a positive
17873     * number.
17874     *
17875     * @see #NO_ID
17876     * @see #getId()
17877     * @see #findViewById(int)
17878     *
17879     * @param id a number used to identify the view
17880     *
17881     * @attr ref android.R.styleable#View_id
17882     */
17883    public void setId(@IdRes int id) {
17884        mID = id;
17885        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17886            mID = generateViewId();
17887        }
17888    }
17889
17890    /**
17891     * {@hide}
17892     *
17893     * @param isRoot true if the view belongs to the root namespace, false
17894     *        otherwise
17895     */
17896    public void setIsRootNamespace(boolean isRoot) {
17897        if (isRoot) {
17898            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17899        } else {
17900            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17901        }
17902    }
17903
17904    /**
17905     * {@hide}
17906     *
17907     * @return true if the view belongs to the root namespace, false otherwise
17908     */
17909    public boolean isRootNamespace() {
17910        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17911    }
17912
17913    /**
17914     * Returns this view's identifier.
17915     *
17916     * @return a positive integer used to identify the view or {@link #NO_ID}
17917     *         if the view has no ID
17918     *
17919     * @see #setId(int)
17920     * @see #findViewById(int)
17921     * @attr ref android.R.styleable#View_id
17922     */
17923    @IdRes
17924    @ViewDebug.CapturedViewProperty
17925    public int getId() {
17926        return mID;
17927    }
17928
17929    /**
17930     * Returns this view's tag.
17931     *
17932     * @return the Object stored in this view as a tag, or {@code null} if not
17933     *         set
17934     *
17935     * @see #setTag(Object)
17936     * @see #getTag(int)
17937     */
17938    @ViewDebug.ExportedProperty
17939    public Object getTag() {
17940        return mTag;
17941    }
17942
17943    /**
17944     * Sets the tag associated with this view. A tag can be used to mark
17945     * a view in its hierarchy and does not have to be unique within the
17946     * hierarchy. Tags can also be used to store data within a view without
17947     * resorting to another data structure.
17948     *
17949     * @param tag an Object to tag the view with
17950     *
17951     * @see #getTag()
17952     * @see #setTag(int, Object)
17953     */
17954    public void setTag(final Object tag) {
17955        mTag = tag;
17956    }
17957
17958    /**
17959     * Returns the tag associated with this view and the specified key.
17960     *
17961     * @param key The key identifying the tag
17962     *
17963     * @return the Object stored in this view as a tag, or {@code null} if not
17964     *         set
17965     *
17966     * @see #setTag(int, Object)
17967     * @see #getTag()
17968     */
17969    public Object getTag(int key) {
17970        if (mKeyedTags != null) return mKeyedTags.get(key);
17971        return null;
17972    }
17973
17974    /**
17975     * Sets a tag associated with this view and a key. A tag can be used
17976     * to mark a view in its hierarchy and does not have to be unique within
17977     * the hierarchy. Tags can also be used to store data within a view
17978     * without resorting to another data structure.
17979     *
17980     * The specified key should be an id declared in the resources of the
17981     * application to ensure it is unique (see the <a
17982     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17983     * Keys identified as belonging to
17984     * the Android framework or not associated with any package will cause
17985     * an {@link IllegalArgumentException} to be thrown.
17986     *
17987     * @param key The key identifying the tag
17988     * @param tag An Object to tag the view with
17989     *
17990     * @throws IllegalArgumentException If they specified key is not valid
17991     *
17992     * @see #setTag(Object)
17993     * @see #getTag(int)
17994     */
17995    public void setTag(int key, final Object tag) {
17996        // If the package id is 0x00 or 0x01, it's either an undefined package
17997        // or a framework id
17998        if ((key >>> 24) < 2) {
17999            throw new IllegalArgumentException("The key must be an application-specific "
18000                    + "resource id.");
18001        }
18002
18003        setKeyedTag(key, tag);
18004    }
18005
18006    /**
18007     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
18008     * framework id.
18009     *
18010     * @hide
18011     */
18012    public void setTagInternal(int key, Object tag) {
18013        if ((key >>> 24) != 0x1) {
18014            throw new IllegalArgumentException("The key must be a framework-specific "
18015                    + "resource id.");
18016        }
18017
18018        setKeyedTag(key, tag);
18019    }
18020
18021    private void setKeyedTag(int key, Object tag) {
18022        if (mKeyedTags == null) {
18023            mKeyedTags = new SparseArray<Object>(2);
18024        }
18025
18026        mKeyedTags.put(key, tag);
18027    }
18028
18029    /**
18030     * Prints information about this view in the log output, with the tag
18031     * {@link #VIEW_LOG_TAG}.
18032     *
18033     * @hide
18034     */
18035    public void debug() {
18036        debug(0);
18037    }
18038
18039    /**
18040     * Prints information about this view in the log output, with the tag
18041     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18042     * indentation defined by the <code>depth</code>.
18043     *
18044     * @param depth the indentation level
18045     *
18046     * @hide
18047     */
18048    protected void debug(int depth) {
18049        String output = debugIndent(depth - 1);
18050
18051        output += "+ " + this;
18052        int id = getId();
18053        if (id != -1) {
18054            output += " (id=" + id + ")";
18055        }
18056        Object tag = getTag();
18057        if (tag != null) {
18058            output += " (tag=" + tag + ")";
18059        }
18060        Log.d(VIEW_LOG_TAG, output);
18061
18062        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18063            output = debugIndent(depth) + " FOCUSED";
18064            Log.d(VIEW_LOG_TAG, output);
18065        }
18066
18067        output = debugIndent(depth);
18068        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18069                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18070                + "} ";
18071        Log.d(VIEW_LOG_TAG, output);
18072
18073        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18074                || mPaddingBottom != 0) {
18075            output = debugIndent(depth);
18076            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18077                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18078            Log.d(VIEW_LOG_TAG, output);
18079        }
18080
18081        output = debugIndent(depth);
18082        output += "mMeasureWidth=" + mMeasuredWidth +
18083                " mMeasureHeight=" + mMeasuredHeight;
18084        Log.d(VIEW_LOG_TAG, output);
18085
18086        output = debugIndent(depth);
18087        if (mLayoutParams == null) {
18088            output += "BAD! no layout params";
18089        } else {
18090            output = mLayoutParams.debug(output);
18091        }
18092        Log.d(VIEW_LOG_TAG, output);
18093
18094        output = debugIndent(depth);
18095        output += "flags={";
18096        output += View.printFlags(mViewFlags);
18097        output += "}";
18098        Log.d(VIEW_LOG_TAG, output);
18099
18100        output = debugIndent(depth);
18101        output += "privateFlags={";
18102        output += View.printPrivateFlags(mPrivateFlags);
18103        output += "}";
18104        Log.d(VIEW_LOG_TAG, output);
18105    }
18106
18107    /**
18108     * Creates a string of whitespaces used for indentation.
18109     *
18110     * @param depth the indentation level
18111     * @return a String containing (depth * 2 + 3) * 2 white spaces
18112     *
18113     * @hide
18114     */
18115    protected static String debugIndent(int depth) {
18116        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18117        for (int i = 0; i < (depth * 2) + 3; i++) {
18118            spaces.append(' ').append(' ');
18119        }
18120        return spaces.toString();
18121    }
18122
18123    /**
18124     * <p>Return the offset of the widget's text baseline from the widget's top
18125     * boundary. If this widget does not support baseline alignment, this
18126     * method returns -1. </p>
18127     *
18128     * @return the offset of the baseline within the widget's bounds or -1
18129     *         if baseline alignment is not supported
18130     */
18131    @ViewDebug.ExportedProperty(category = "layout")
18132    public int getBaseline() {
18133        return -1;
18134    }
18135
18136    /**
18137     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18138     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18139     * a layout pass.
18140     *
18141     * @return whether the view hierarchy is currently undergoing a layout pass
18142     */
18143    public boolean isInLayout() {
18144        ViewRootImpl viewRoot = getViewRootImpl();
18145        return (viewRoot != null && viewRoot.isInLayout());
18146    }
18147
18148    /**
18149     * Call this when something has changed which has invalidated the
18150     * layout of this view. This will schedule a layout pass of the view
18151     * tree. This should not be called while the view hierarchy is currently in a layout
18152     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18153     * end of the current layout pass (and then layout will run again) or after the current
18154     * frame is drawn and the next layout occurs.
18155     *
18156     * <p>Subclasses which override this method should call the superclass method to
18157     * handle possible request-during-layout errors correctly.</p>
18158     */
18159    @CallSuper
18160    public void requestLayout() {
18161        if (mMeasureCache != null) mMeasureCache.clear();
18162
18163        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18164            // Only trigger request-during-layout logic if this is the view requesting it,
18165            // not the views in its parent hierarchy
18166            ViewRootImpl viewRoot = getViewRootImpl();
18167            if (viewRoot != null && viewRoot.isInLayout()) {
18168                if (!viewRoot.requestLayoutDuringLayout(this)) {
18169                    return;
18170                }
18171            }
18172            mAttachInfo.mViewRequestingLayout = this;
18173        }
18174
18175        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18176        mPrivateFlags |= PFLAG_INVALIDATED;
18177
18178        if (mParent != null && !mParent.isLayoutRequested()) {
18179            mParent.requestLayout();
18180        }
18181        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18182            mAttachInfo.mViewRequestingLayout = null;
18183        }
18184    }
18185
18186    /**
18187     * Forces this view to be laid out during the next layout pass.
18188     * This method does not call requestLayout() or forceLayout()
18189     * on the parent.
18190     */
18191    public void forceLayout() {
18192        if (mMeasureCache != null) mMeasureCache.clear();
18193
18194        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18195        mPrivateFlags |= PFLAG_INVALIDATED;
18196    }
18197
18198    /**
18199     * <p>
18200     * This is called to find out how big a view should be. The parent
18201     * supplies constraint information in the width and height parameters.
18202     * </p>
18203     *
18204     * <p>
18205     * The actual measurement work of a view is performed in
18206     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18207     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18208     * </p>
18209     *
18210     *
18211     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18212     *        parent
18213     * @param heightMeasureSpec Vertical space requirements as imposed by the
18214     *        parent
18215     *
18216     * @see #onMeasure(int, int)
18217     */
18218    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18219        boolean optical = isLayoutModeOptical(this);
18220        if (optical != isLayoutModeOptical(mParent)) {
18221            Insets insets = getOpticalInsets();
18222            int oWidth  = insets.left + insets.right;
18223            int oHeight = insets.top  + insets.bottom;
18224            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18225            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18226        }
18227
18228        // Suppress sign extension for the low bytes
18229        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18230        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18231
18232        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18233        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18234                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18235        final boolean matchingSize = isExactly &&
18236                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18237                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18238        if (forceLayout || !matchingSize &&
18239                (widthMeasureSpec != mOldWidthMeasureSpec ||
18240                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18241
18242            // first clears the measured dimension flag
18243            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18244
18245            resolveRtlPropertiesIfNeeded();
18246
18247            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18248            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18249                // measure ourselves, this should set the measured dimension flag back
18250                onMeasure(widthMeasureSpec, heightMeasureSpec);
18251                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18252            } else {
18253                long value = mMeasureCache.valueAt(cacheIndex);
18254                // Casting a long to int drops the high 32 bits, no mask needed
18255                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18256                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18257            }
18258
18259            // flag not set, setMeasuredDimension() was not invoked, we raise
18260            // an exception to warn the developer
18261            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18262                throw new IllegalStateException("View with id " + getId() + ": "
18263                        + getClass().getName() + "#onMeasure() did not set the"
18264                        + " measured dimension by calling"
18265                        + " setMeasuredDimension()");
18266            }
18267
18268            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18269        }
18270
18271        mOldWidthMeasureSpec = widthMeasureSpec;
18272        mOldHeightMeasureSpec = heightMeasureSpec;
18273
18274        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18275                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18276    }
18277
18278    /**
18279     * <p>
18280     * Measure the view and its content to determine the measured width and the
18281     * measured height. This method is invoked by {@link #measure(int, int)} and
18282     * should be overridden by subclasses to provide accurate and efficient
18283     * measurement of their contents.
18284     * </p>
18285     *
18286     * <p>
18287     * <strong>CONTRACT:</strong> When overriding this method, you
18288     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18289     * measured width and height of this view. Failure to do so will trigger an
18290     * <code>IllegalStateException</code>, thrown by
18291     * {@link #measure(int, int)}. Calling the superclass'
18292     * {@link #onMeasure(int, int)} is a valid use.
18293     * </p>
18294     *
18295     * <p>
18296     * The base class implementation of measure defaults to the background size,
18297     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18298     * override {@link #onMeasure(int, int)} to provide better measurements of
18299     * their content.
18300     * </p>
18301     *
18302     * <p>
18303     * If this method is overridden, it is the subclass's responsibility to make
18304     * sure the measured height and width are at least the view's minimum height
18305     * and width ({@link #getSuggestedMinimumHeight()} and
18306     * {@link #getSuggestedMinimumWidth()}).
18307     * </p>
18308     *
18309     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18310     *                         The requirements are encoded with
18311     *                         {@link android.view.View.MeasureSpec}.
18312     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18313     *                         The requirements are encoded with
18314     *                         {@link android.view.View.MeasureSpec}.
18315     *
18316     * @see #getMeasuredWidth()
18317     * @see #getMeasuredHeight()
18318     * @see #setMeasuredDimension(int, int)
18319     * @see #getSuggestedMinimumHeight()
18320     * @see #getSuggestedMinimumWidth()
18321     * @see android.view.View.MeasureSpec#getMode(int)
18322     * @see android.view.View.MeasureSpec#getSize(int)
18323     */
18324    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18325        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18326                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18327    }
18328
18329    /**
18330     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18331     * measured width and measured height. Failing to do so will trigger an
18332     * exception at measurement time.</p>
18333     *
18334     * @param measuredWidth The measured width of this view.  May be a complex
18335     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18336     * {@link #MEASURED_STATE_TOO_SMALL}.
18337     * @param measuredHeight The measured height of this view.  May be a complex
18338     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18339     * {@link #MEASURED_STATE_TOO_SMALL}.
18340     */
18341    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18342        boolean optical = isLayoutModeOptical(this);
18343        if (optical != isLayoutModeOptical(mParent)) {
18344            Insets insets = getOpticalInsets();
18345            int opticalWidth  = insets.left + insets.right;
18346            int opticalHeight = insets.top  + insets.bottom;
18347
18348            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18349            measuredHeight += optical ? opticalHeight : -opticalHeight;
18350        }
18351        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18352    }
18353
18354    /**
18355     * Sets the measured dimension without extra processing for things like optical bounds.
18356     * Useful for reapplying consistent values that have already been cooked with adjustments
18357     * for optical bounds, etc. such as those from the measurement cache.
18358     *
18359     * @param measuredWidth The measured width of this view.  May be a complex
18360     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18361     * {@link #MEASURED_STATE_TOO_SMALL}.
18362     * @param measuredHeight The measured height of this view.  May be a complex
18363     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18364     * {@link #MEASURED_STATE_TOO_SMALL}.
18365     */
18366    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18367        mMeasuredWidth = measuredWidth;
18368        mMeasuredHeight = measuredHeight;
18369
18370        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18371    }
18372
18373    /**
18374     * Merge two states as returned by {@link #getMeasuredState()}.
18375     * @param curState The current state as returned from a view or the result
18376     * of combining multiple views.
18377     * @param newState The new view state to combine.
18378     * @return Returns a new integer reflecting the combination of the two
18379     * states.
18380     */
18381    public static int combineMeasuredStates(int curState, int newState) {
18382        return curState | newState;
18383    }
18384
18385    /**
18386     * Version of {@link #resolveSizeAndState(int, int, int)}
18387     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18388     */
18389    public static int resolveSize(int size, int measureSpec) {
18390        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18391    }
18392
18393    /**
18394     * Utility to reconcile a desired size and state, with constraints imposed
18395     * by a MeasureSpec. Will take the desired size, unless a different size
18396     * is imposed by the constraints. The returned value is a compound integer,
18397     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18398     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18399     * resulting size is smaller than the size the view wants to be.
18400     *
18401     * @param size How big the view wants to be.
18402     * @param measureSpec Constraints imposed by the parent.
18403     * @param childMeasuredState Size information bit mask for the view's
18404     *                           children.
18405     * @return Size information bit mask as defined by
18406     *         {@link #MEASURED_SIZE_MASK} and
18407     *         {@link #MEASURED_STATE_TOO_SMALL}.
18408     */
18409    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18410        final int specMode = MeasureSpec.getMode(measureSpec);
18411        final int specSize = MeasureSpec.getSize(measureSpec);
18412        final int result;
18413        switch (specMode) {
18414            case MeasureSpec.AT_MOST:
18415                if (specSize < size) {
18416                    result = specSize | MEASURED_STATE_TOO_SMALL;
18417                } else {
18418                    result = size;
18419                }
18420                break;
18421            case MeasureSpec.EXACTLY:
18422                result = specSize;
18423                break;
18424            case MeasureSpec.UNSPECIFIED:
18425            default:
18426                result = size;
18427        }
18428        return result | (childMeasuredState & MEASURED_STATE_MASK);
18429    }
18430
18431    /**
18432     * Utility to return a default size. Uses the supplied size if the
18433     * MeasureSpec imposed no constraints. Will get larger if allowed
18434     * by the MeasureSpec.
18435     *
18436     * @param size Default size for this view
18437     * @param measureSpec Constraints imposed by the parent
18438     * @return The size this view should be.
18439     */
18440    public static int getDefaultSize(int size, int measureSpec) {
18441        int result = size;
18442        int specMode = MeasureSpec.getMode(measureSpec);
18443        int specSize = MeasureSpec.getSize(measureSpec);
18444
18445        switch (specMode) {
18446        case MeasureSpec.UNSPECIFIED:
18447            result = size;
18448            break;
18449        case MeasureSpec.AT_MOST:
18450        case MeasureSpec.EXACTLY:
18451            result = specSize;
18452            break;
18453        }
18454        return result;
18455    }
18456
18457    /**
18458     * Returns the suggested minimum height that the view should use. This
18459     * returns the maximum of the view's minimum height
18460     * and the background's minimum height
18461     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
18462     * <p>
18463     * When being used in {@link #onMeasure(int, int)}, the caller should still
18464     * ensure the returned height is within the requirements of the parent.
18465     *
18466     * @return The suggested minimum height of the view.
18467     */
18468    protected int getSuggestedMinimumHeight() {
18469        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
18470
18471    }
18472
18473    /**
18474     * Returns the suggested minimum width that the view should use. This
18475     * returns the maximum of the view's minimum width)
18476     * and the background's minimum width
18477     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
18478     * <p>
18479     * When being used in {@link #onMeasure(int, int)}, the caller should still
18480     * ensure the returned width is within the requirements of the parent.
18481     *
18482     * @return The suggested minimum width of the view.
18483     */
18484    protected int getSuggestedMinimumWidth() {
18485        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
18486    }
18487
18488    /**
18489     * Returns the minimum height of the view.
18490     *
18491     * @return the minimum height the view will try to be.
18492     *
18493     * @see #setMinimumHeight(int)
18494     *
18495     * @attr ref android.R.styleable#View_minHeight
18496     */
18497    public int getMinimumHeight() {
18498        return mMinHeight;
18499    }
18500
18501    /**
18502     * Sets the minimum height of the view. It is not guaranteed the view will
18503     * be able to achieve this minimum height (for example, if its parent layout
18504     * constrains it with less available height).
18505     *
18506     * @param minHeight The minimum height the view will try to be.
18507     *
18508     * @see #getMinimumHeight()
18509     *
18510     * @attr ref android.R.styleable#View_minHeight
18511     */
18512    public void setMinimumHeight(int minHeight) {
18513        mMinHeight = minHeight;
18514        requestLayout();
18515    }
18516
18517    /**
18518     * Returns the minimum width of the view.
18519     *
18520     * @return the minimum width the view will try to be.
18521     *
18522     * @see #setMinimumWidth(int)
18523     *
18524     * @attr ref android.R.styleable#View_minWidth
18525     */
18526    public int getMinimumWidth() {
18527        return mMinWidth;
18528    }
18529
18530    /**
18531     * Sets the minimum width of the view. It is not guaranteed the view will
18532     * be able to achieve this minimum width (for example, if its parent layout
18533     * constrains it with less available width).
18534     *
18535     * @param minWidth The minimum width the view will try to be.
18536     *
18537     * @see #getMinimumWidth()
18538     *
18539     * @attr ref android.R.styleable#View_minWidth
18540     */
18541    public void setMinimumWidth(int minWidth) {
18542        mMinWidth = minWidth;
18543        requestLayout();
18544
18545    }
18546
18547    /**
18548     * Get the animation currently associated with this view.
18549     *
18550     * @return The animation that is currently playing or
18551     *         scheduled to play for this view.
18552     */
18553    public Animation getAnimation() {
18554        return mCurrentAnimation;
18555    }
18556
18557    /**
18558     * Start the specified animation now.
18559     *
18560     * @param animation the animation to start now
18561     */
18562    public void startAnimation(Animation animation) {
18563        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
18564        setAnimation(animation);
18565        invalidateParentCaches();
18566        invalidate(true);
18567    }
18568
18569    /**
18570     * Cancels any animations for this view.
18571     */
18572    public void clearAnimation() {
18573        if (mCurrentAnimation != null) {
18574            mCurrentAnimation.detach();
18575        }
18576        mCurrentAnimation = null;
18577        invalidateParentIfNeeded();
18578    }
18579
18580    /**
18581     * Sets the next animation to play for this view.
18582     * If you want the animation to play immediately, use
18583     * {@link #startAnimation(android.view.animation.Animation)} instead.
18584     * This method provides allows fine-grained
18585     * control over the start time and invalidation, but you
18586     * must make sure that 1) the animation has a start time set, and
18587     * 2) the view's parent (which controls animations on its children)
18588     * will be invalidated when the animation is supposed to
18589     * start.
18590     *
18591     * @param animation The next animation, or null.
18592     */
18593    public void setAnimation(Animation animation) {
18594        mCurrentAnimation = animation;
18595
18596        if (animation != null) {
18597            // If the screen is off assume the animation start time is now instead of
18598            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
18599            // would cause the animation to start when the screen turns back on
18600            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
18601                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
18602                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
18603            }
18604            animation.reset();
18605        }
18606    }
18607
18608    /**
18609     * Invoked by a parent ViewGroup to notify the start of the animation
18610     * currently associated with this view. If you override this method,
18611     * always call super.onAnimationStart();
18612     *
18613     * @see #setAnimation(android.view.animation.Animation)
18614     * @see #getAnimation()
18615     */
18616    @CallSuper
18617    protected void onAnimationStart() {
18618        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18619    }
18620
18621    /**
18622     * Invoked by a parent ViewGroup to notify the end of the animation
18623     * currently associated with this view. If you override this method,
18624     * always call super.onAnimationEnd();
18625     *
18626     * @see #setAnimation(android.view.animation.Animation)
18627     * @see #getAnimation()
18628     */
18629    @CallSuper
18630    protected void onAnimationEnd() {
18631        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18632    }
18633
18634    /**
18635     * Invoked if there is a Transform that involves alpha. Subclass that can
18636     * draw themselves with the specified alpha should return true, and then
18637     * respect that alpha when their onDraw() is called. If this returns false
18638     * then the view may be redirected to draw into an offscreen buffer to
18639     * fulfill the request, which will look fine, but may be slower than if the
18640     * subclass handles it internally. The default implementation returns false.
18641     *
18642     * @param alpha The alpha (0..255) to apply to the view's drawing
18643     * @return true if the view can draw with the specified alpha.
18644     */
18645    protected boolean onSetAlpha(int alpha) {
18646        return false;
18647    }
18648
18649    /**
18650     * This is used by the RootView to perform an optimization when
18651     * the view hierarchy contains one or several SurfaceView.
18652     * SurfaceView is always considered transparent, but its children are not,
18653     * therefore all View objects remove themselves from the global transparent
18654     * region (passed as a parameter to this function).
18655     *
18656     * @param region The transparent region for this ViewAncestor (window).
18657     *
18658     * @return Returns true if the effective visibility of the view at this
18659     * point is opaque, regardless of the transparent region; returns false
18660     * if it is possible for underlying windows to be seen behind the view.
18661     *
18662     * {@hide}
18663     */
18664    public boolean gatherTransparentRegion(Region region) {
18665        final AttachInfo attachInfo = mAttachInfo;
18666        if (region != null && attachInfo != null) {
18667            final int pflags = mPrivateFlags;
18668            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18669                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18670                // remove it from the transparent region.
18671                final int[] location = attachInfo.mTransparentLocation;
18672                getLocationInWindow(location);
18673                region.op(location[0], location[1], location[0] + mRight - mLeft,
18674                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18675            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18676                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18677                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18678                // exists, so we remove the background drawable's non-transparent
18679                // parts from this transparent region.
18680                applyDrawableToTransparentRegion(mBackground, region);
18681            }
18682            final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18683            if (foreground != null) {
18684                applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
18685            }
18686        }
18687        return true;
18688    }
18689
18690    /**
18691     * Play a sound effect for this view.
18692     *
18693     * <p>The framework will play sound effects for some built in actions, such as
18694     * clicking, but you may wish to play these effects in your widget,
18695     * for instance, for internal navigation.
18696     *
18697     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18698     * {@link #isSoundEffectsEnabled()} is true.
18699     *
18700     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18701     */
18702    public void playSoundEffect(int soundConstant) {
18703        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18704            return;
18705        }
18706        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18707    }
18708
18709    /**
18710     * BZZZTT!!1!
18711     *
18712     * <p>Provide haptic feedback to the user for this view.
18713     *
18714     * <p>The framework will provide haptic feedback for some built in actions,
18715     * such as long presses, but you may wish to provide feedback for your
18716     * own widget.
18717     *
18718     * <p>The feedback will only be performed if
18719     * {@link #isHapticFeedbackEnabled()} is true.
18720     *
18721     * @param feedbackConstant One of the constants defined in
18722     * {@link HapticFeedbackConstants}
18723     */
18724    public boolean performHapticFeedback(int feedbackConstant) {
18725        return performHapticFeedback(feedbackConstant, 0);
18726    }
18727
18728    /**
18729     * BZZZTT!!1!
18730     *
18731     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18732     *
18733     * @param feedbackConstant One of the constants defined in
18734     * {@link HapticFeedbackConstants}
18735     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18736     */
18737    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18738        if (mAttachInfo == null) {
18739            return false;
18740        }
18741        //noinspection SimplifiableIfStatement
18742        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18743                && !isHapticFeedbackEnabled()) {
18744            return false;
18745        }
18746        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18747                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18748    }
18749
18750    /**
18751     * Request that the visibility of the status bar or other screen/window
18752     * decorations be changed.
18753     *
18754     * <p>This method is used to put the over device UI into temporary modes
18755     * where the user's attention is focused more on the application content,
18756     * by dimming or hiding surrounding system affordances.  This is typically
18757     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18758     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18759     * to be placed behind the action bar (and with these flags other system
18760     * affordances) so that smooth transitions between hiding and showing them
18761     * can be done.
18762     *
18763     * <p>Two representative examples of the use of system UI visibility is
18764     * implementing a content browsing application (like a magazine reader)
18765     * and a video playing application.
18766     *
18767     * <p>The first code shows a typical implementation of a View in a content
18768     * browsing application.  In this implementation, the application goes
18769     * into a content-oriented mode by hiding the status bar and action bar,
18770     * and putting the navigation elements into lights out mode.  The user can
18771     * then interact with content while in this mode.  Such an application should
18772     * provide an easy way for the user to toggle out of the mode (such as to
18773     * check information in the status bar or access notifications).  In the
18774     * implementation here, this is done simply by tapping on the content.
18775     *
18776     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18777     *      content}
18778     *
18779     * <p>This second code sample shows a typical implementation of a View
18780     * in a video playing application.  In this situation, while the video is
18781     * playing the application would like to go into a complete full-screen mode,
18782     * to use as much of the display as possible for the video.  When in this state
18783     * the user can not interact with the application; the system intercepts
18784     * touching on the screen to pop the UI out of full screen mode.  See
18785     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18786     *
18787     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18788     *      content}
18789     *
18790     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18791     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18792     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18793     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18794     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18795     */
18796    public void setSystemUiVisibility(int visibility) {
18797        if (visibility != mSystemUiVisibility) {
18798            mSystemUiVisibility = visibility;
18799            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18800                mParent.recomputeViewAttributes(this);
18801            }
18802        }
18803    }
18804
18805    /**
18806     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18807     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18808     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18809     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18810     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18811     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18812     */
18813    public int getSystemUiVisibility() {
18814        return mSystemUiVisibility;
18815    }
18816
18817    /**
18818     * Returns the current system UI visibility that is currently set for
18819     * the entire window.  This is the combination of the
18820     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18821     * views in the window.
18822     */
18823    public int getWindowSystemUiVisibility() {
18824        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18825    }
18826
18827    /**
18828     * Override to find out when the window's requested system UI visibility
18829     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18830     * This is different from the callbacks received through
18831     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18832     * in that this is only telling you about the local request of the window,
18833     * not the actual values applied by the system.
18834     */
18835    public void onWindowSystemUiVisibilityChanged(int visible) {
18836    }
18837
18838    /**
18839     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18840     * the view hierarchy.
18841     */
18842    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18843        onWindowSystemUiVisibilityChanged(visible);
18844    }
18845
18846    /**
18847     * Set a listener to receive callbacks when the visibility of the system bar changes.
18848     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18849     */
18850    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18851        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18852        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18853            mParent.recomputeViewAttributes(this);
18854        }
18855    }
18856
18857    /**
18858     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18859     * the view hierarchy.
18860     */
18861    public void dispatchSystemUiVisibilityChanged(int visibility) {
18862        ListenerInfo li = mListenerInfo;
18863        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18864            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18865                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18866        }
18867    }
18868
18869    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18870        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18871        if (val != mSystemUiVisibility) {
18872            setSystemUiVisibility(val);
18873            return true;
18874        }
18875        return false;
18876    }
18877
18878    /** @hide */
18879    public void setDisabledSystemUiVisibility(int flags) {
18880        if (mAttachInfo != null) {
18881            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18882                mAttachInfo.mDisabledSystemUiVisibility = flags;
18883                if (mParent != null) {
18884                    mParent.recomputeViewAttributes(this);
18885                }
18886            }
18887        }
18888    }
18889
18890    /**
18891     * Creates an image that the system displays during the drag and drop
18892     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18893     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18894     * appearance as the given View. The default also positions the center of the drag shadow
18895     * directly under the touch point. If no View is provided (the constructor with no parameters
18896     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18897     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
18898     * default is an invisible drag shadow.
18899     * <p>
18900     * You are not required to use the View you provide to the constructor as the basis of the
18901     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18902     * anything you want as the drag shadow.
18903     * </p>
18904     * <p>
18905     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18906     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18907     *  size and position of the drag shadow. It uses this data to construct a
18908     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18909     *  so that your application can draw the shadow image in the Canvas.
18910     * </p>
18911     *
18912     * <div class="special reference">
18913     * <h3>Developer Guides</h3>
18914     * <p>For a guide to implementing drag and drop features, read the
18915     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18916     * </div>
18917     */
18918    public static class DragShadowBuilder {
18919        private final WeakReference<View> mView;
18920
18921        /**
18922         * Constructs a shadow image builder based on a View. By default, the resulting drag
18923         * shadow will have the same appearance and dimensions as the View, with the touch point
18924         * over the center of the View.
18925         * @param view A View. Any View in scope can be used.
18926         */
18927        public DragShadowBuilder(View view) {
18928            mView = new WeakReference<View>(view);
18929        }
18930
18931        /**
18932         * Construct a shadow builder object with no associated View.  This
18933         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18934         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18935         * to supply the drag shadow's dimensions and appearance without
18936         * reference to any View object. If they are not overridden, then the result is an
18937         * invisible drag shadow.
18938         */
18939        public DragShadowBuilder() {
18940            mView = new WeakReference<View>(null);
18941        }
18942
18943        /**
18944         * Returns the View object that had been passed to the
18945         * {@link #View.DragShadowBuilder(View)}
18946         * constructor.  If that View parameter was {@code null} or if the
18947         * {@link #View.DragShadowBuilder()}
18948         * constructor was used to instantiate the builder object, this method will return
18949         * null.
18950         *
18951         * @return The View object associate with this builder object.
18952         */
18953        @SuppressWarnings({"JavadocReference"})
18954        final public View getView() {
18955            return mView.get();
18956        }
18957
18958        /**
18959         * Provides the metrics for the shadow image. These include the dimensions of
18960         * the shadow image, and the point within that shadow that should
18961         * be centered under the touch location while dragging.
18962         * <p>
18963         * The default implementation sets the dimensions of the shadow to be the
18964         * same as the dimensions of the View itself and centers the shadow under
18965         * the touch point.
18966         * </p>
18967         *
18968         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18969         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18970         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18971         * image.
18972         *
18973         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18974         * shadow image that should be underneath the touch point during the drag and drop
18975         * operation. Your application must set {@link android.graphics.Point#x} to the
18976         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18977         */
18978        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18979            final View view = mView.get();
18980            if (view != null) {
18981                shadowSize.set(view.getWidth(), view.getHeight());
18982                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18983            } else {
18984                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18985            }
18986        }
18987
18988        /**
18989         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18990         * based on the dimensions it received from the
18991         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18992         *
18993         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18994         */
18995        public void onDrawShadow(Canvas canvas) {
18996            final View view = mView.get();
18997            if (view != null) {
18998                view.draw(canvas);
18999            } else {
19000                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
19001            }
19002        }
19003    }
19004
19005    /**
19006     * Starts a drag and drop operation. When your application calls this method, it passes a
19007     * {@link android.view.View.DragShadowBuilder} object to the system. The
19008     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
19009     * to get metrics for the drag shadow, and then calls the object's
19010     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
19011     * <p>
19012     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
19013     *  drag events to all the View objects in your application that are currently visible. It does
19014     *  this either by calling the View object's drag listener (an implementation of
19015     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
19016     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
19017     *  Both are passed a {@link android.view.DragEvent} object that has a
19018     *  {@link android.view.DragEvent#getAction()} value of
19019     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
19020     * </p>
19021     * <p>
19022     * Your application can invoke startDrag() on any attached View object. The View object does not
19023     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
19024     * be related to the View the user selected for dragging.
19025     * </p>
19026     * @param data A {@link android.content.ClipData} object pointing to the data to be
19027     * transferred by the drag and drop operation.
19028     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19029     * drag shadow.
19030     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19031     * drop operation. This Object is put into every DragEvent object sent by the system during the
19032     * current drag.
19033     * <p>
19034     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19035     * to the target Views. For example, it can contain flags that differentiate between a
19036     * a copy operation and a move operation.
19037     * </p>
19038     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19039     * so the parameter should be set to 0.
19040     * @return {@code true} if the method completes successfully, or
19041     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19042     * do a drag, and so no drag operation is in progress.
19043     */
19044    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19045            Object myLocalState, int flags) {
19046        if (ViewDebug.DEBUG_DRAG) {
19047            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19048        }
19049        boolean okay = false;
19050
19051        Point shadowSize = new Point();
19052        Point shadowTouchPoint = new Point();
19053        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19054
19055        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19056                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19057            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19058        }
19059
19060        if (ViewDebug.DEBUG_DRAG) {
19061            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19062                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19063        }
19064        Surface surface = new Surface();
19065        try {
19066            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19067                    flags, shadowSize.x, shadowSize.y, surface);
19068            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19069                    + " surface=" + surface);
19070            if (token != null) {
19071                Canvas canvas = surface.lockCanvas(null);
19072                try {
19073                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19074                    shadowBuilder.onDrawShadow(canvas);
19075                } finally {
19076                    surface.unlockCanvasAndPost(canvas);
19077                }
19078
19079                final ViewRootImpl root = getViewRootImpl();
19080
19081                // Cache the local state object for delivery with DragEvents
19082                root.setLocalDragState(myLocalState);
19083
19084                // repurpose 'shadowSize' for the last touch point
19085                root.getLastTouchPoint(shadowSize);
19086
19087                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19088                        shadowSize.x, shadowSize.y,
19089                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19090                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19091
19092                // Off and running!  Release our local surface instance; the drag
19093                // shadow surface is now managed by the system process.
19094                surface.release();
19095            }
19096        } catch (Exception e) {
19097            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19098            surface.destroy();
19099        }
19100
19101        return okay;
19102    }
19103
19104    /**
19105     * Handles drag events sent by the system following a call to
19106     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19107     *<p>
19108     * When the system calls this method, it passes a
19109     * {@link android.view.DragEvent} object. A call to
19110     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19111     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19112     * operation.
19113     * @param event The {@link android.view.DragEvent} sent by the system.
19114     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19115     * in DragEvent, indicating the type of drag event represented by this object.
19116     * @return {@code true} if the method was successful, otherwise {@code false}.
19117     * <p>
19118     *  The method should return {@code true} in response to an action type of
19119     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19120     *  operation.
19121     * </p>
19122     * <p>
19123     *  The method should also return {@code true} in response to an action type of
19124     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19125     *  {@code false} if it didn't.
19126     * </p>
19127     */
19128    public boolean onDragEvent(DragEvent event) {
19129        return false;
19130    }
19131
19132    /**
19133     * Detects if this View is enabled and has a drag event listener.
19134     * If both are true, then it calls the drag event listener with the
19135     * {@link android.view.DragEvent} it received. If the drag event listener returns
19136     * {@code true}, then dispatchDragEvent() returns {@code true}.
19137     * <p>
19138     * For all other cases, the method calls the
19139     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19140     * method and returns its result.
19141     * </p>
19142     * <p>
19143     * This ensures that a drag event is always consumed, even if the View does not have a drag
19144     * event listener. However, if the View has a listener and the listener returns true, then
19145     * onDragEvent() is not called.
19146     * </p>
19147     */
19148    public boolean dispatchDragEvent(DragEvent event) {
19149        ListenerInfo li = mListenerInfo;
19150        //noinspection SimplifiableIfStatement
19151        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19152                && li.mOnDragListener.onDrag(this, event)) {
19153            return true;
19154        }
19155        return onDragEvent(event);
19156    }
19157
19158    boolean canAcceptDrag() {
19159        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19160    }
19161
19162    /**
19163     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19164     * it is ever exposed at all.
19165     * @hide
19166     */
19167    public void onCloseSystemDialogs(String reason) {
19168    }
19169
19170    /**
19171     * Given a Drawable whose bounds have been set to draw into this view,
19172     * update a Region being computed for
19173     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19174     * that any non-transparent parts of the Drawable are removed from the
19175     * given transparent region.
19176     *
19177     * @param dr The Drawable whose transparency is to be applied to the region.
19178     * @param region A Region holding the current transparency information,
19179     * where any parts of the region that are set are considered to be
19180     * transparent.  On return, this region will be modified to have the
19181     * transparency information reduced by the corresponding parts of the
19182     * Drawable that are not transparent.
19183     * {@hide}
19184     */
19185    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19186        if (DBG) {
19187            Log.i("View", "Getting transparent region for: " + this);
19188        }
19189        final Region r = dr.getTransparentRegion();
19190        final Rect db = dr.getBounds();
19191        final AttachInfo attachInfo = mAttachInfo;
19192        if (r != null && attachInfo != null) {
19193            final int w = getRight()-getLeft();
19194            final int h = getBottom()-getTop();
19195            if (db.left > 0) {
19196                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19197                r.op(0, 0, db.left, h, Region.Op.UNION);
19198            }
19199            if (db.right < w) {
19200                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19201                r.op(db.right, 0, w, h, Region.Op.UNION);
19202            }
19203            if (db.top > 0) {
19204                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19205                r.op(0, 0, w, db.top, Region.Op.UNION);
19206            }
19207            if (db.bottom < h) {
19208                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19209                r.op(0, db.bottom, w, h, Region.Op.UNION);
19210            }
19211            final int[] location = attachInfo.mTransparentLocation;
19212            getLocationInWindow(location);
19213            r.translate(location[0], location[1]);
19214            region.op(r, Region.Op.INTERSECT);
19215        } else {
19216            region.op(db, Region.Op.DIFFERENCE);
19217        }
19218    }
19219
19220    private void checkForLongClick(int delayOffset) {
19221        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19222            mHasPerformedLongPress = false;
19223
19224            if (mPendingCheckForLongPress == null) {
19225                mPendingCheckForLongPress = new CheckForLongPress();
19226            }
19227            mPendingCheckForLongPress.rememberWindowAttachCount();
19228            postDelayed(mPendingCheckForLongPress,
19229                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19230        }
19231    }
19232
19233    /**
19234     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19235     * LayoutInflater} class, which provides a full range of options for view inflation.
19236     *
19237     * @param context The Context object for your activity or application.
19238     * @param resource The resource ID to inflate
19239     * @param root A view group that will be the parent.  Used to properly inflate the
19240     * layout_* parameters.
19241     * @see LayoutInflater
19242     */
19243    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19244        LayoutInflater factory = LayoutInflater.from(context);
19245        return factory.inflate(resource, root);
19246    }
19247
19248    /**
19249     * Scroll the view with standard behavior for scrolling beyond the normal
19250     * content boundaries. Views that call this method should override
19251     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19252     * results of an over-scroll operation.
19253     *
19254     * Views can use this method to handle any touch or fling-based scrolling.
19255     *
19256     * @param deltaX Change in X in pixels
19257     * @param deltaY Change in Y in pixels
19258     * @param scrollX Current X scroll value in pixels before applying deltaX
19259     * @param scrollY Current Y scroll value in pixels before applying deltaY
19260     * @param scrollRangeX Maximum content scroll range along the X axis
19261     * @param scrollRangeY Maximum content scroll range along the Y axis
19262     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19263     *          along the X axis.
19264     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19265     *          along the Y axis.
19266     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19267     * @return true if scrolling was clamped to an over-scroll boundary along either
19268     *          axis, false otherwise.
19269     */
19270    @SuppressWarnings({"UnusedParameters"})
19271    protected boolean overScrollBy(int deltaX, int deltaY,
19272            int scrollX, int scrollY,
19273            int scrollRangeX, int scrollRangeY,
19274            int maxOverScrollX, int maxOverScrollY,
19275            boolean isTouchEvent) {
19276        final int overScrollMode = mOverScrollMode;
19277        final boolean canScrollHorizontal =
19278                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19279        final boolean canScrollVertical =
19280                computeVerticalScrollRange() > computeVerticalScrollExtent();
19281        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19282                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19283        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19284                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19285
19286        int newScrollX = scrollX + deltaX;
19287        if (!overScrollHorizontal) {
19288            maxOverScrollX = 0;
19289        }
19290
19291        int newScrollY = scrollY + deltaY;
19292        if (!overScrollVertical) {
19293            maxOverScrollY = 0;
19294        }
19295
19296        // Clamp values if at the limits and record
19297        final int left = -maxOverScrollX;
19298        final int right = maxOverScrollX + scrollRangeX;
19299        final int top = -maxOverScrollY;
19300        final int bottom = maxOverScrollY + scrollRangeY;
19301
19302        boolean clampedX = false;
19303        if (newScrollX > right) {
19304            newScrollX = right;
19305            clampedX = true;
19306        } else if (newScrollX < left) {
19307            newScrollX = left;
19308            clampedX = true;
19309        }
19310
19311        boolean clampedY = false;
19312        if (newScrollY > bottom) {
19313            newScrollY = bottom;
19314            clampedY = true;
19315        } else if (newScrollY < top) {
19316            newScrollY = top;
19317            clampedY = true;
19318        }
19319
19320        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19321
19322        return clampedX || clampedY;
19323    }
19324
19325    /**
19326     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19327     * respond to the results of an over-scroll operation.
19328     *
19329     * @param scrollX New X scroll value in pixels
19330     * @param scrollY New Y scroll value in pixels
19331     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19332     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19333     */
19334    protected void onOverScrolled(int scrollX, int scrollY,
19335            boolean clampedX, boolean clampedY) {
19336        // Intentionally empty.
19337    }
19338
19339    /**
19340     * Returns the over-scroll mode for this view. The result will be
19341     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19342     * (allow over-scrolling only if the view content is larger than the container),
19343     * or {@link #OVER_SCROLL_NEVER}.
19344     *
19345     * @return This view's over-scroll mode.
19346     */
19347    public int getOverScrollMode() {
19348        return mOverScrollMode;
19349    }
19350
19351    /**
19352     * Set the over-scroll mode for this view. Valid over-scroll modes are
19353     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19354     * (allow over-scrolling only if the view content is larger than the container),
19355     * or {@link #OVER_SCROLL_NEVER}.
19356     *
19357     * Setting the over-scroll mode of a view will have an effect only if the
19358     * view is capable of scrolling.
19359     *
19360     * @param overScrollMode The new over-scroll mode for this view.
19361     */
19362    public void setOverScrollMode(int overScrollMode) {
19363        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19364                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19365                overScrollMode != OVER_SCROLL_NEVER) {
19366            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19367        }
19368        mOverScrollMode = overScrollMode;
19369    }
19370
19371    /**
19372     * Enable or disable nested scrolling for this view.
19373     *
19374     * <p>If this property is set to true the view will be permitted to initiate nested
19375     * scrolling operations with a compatible parent view in the current hierarchy. If this
19376     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19377     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19378     * the nested scroll.</p>
19379     *
19380     * @param enabled true to enable nested scrolling, false to disable
19381     *
19382     * @see #isNestedScrollingEnabled()
19383     */
19384    public void setNestedScrollingEnabled(boolean enabled) {
19385        if (enabled) {
19386            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19387        } else {
19388            stopNestedScroll();
19389            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19390        }
19391    }
19392
19393    /**
19394     * Returns true if nested scrolling is enabled for this view.
19395     *
19396     * <p>If nested scrolling is enabled and this View class implementation supports it,
19397     * this view will act as a nested scrolling child view when applicable, forwarding data
19398     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19399     * parent.</p>
19400     *
19401     * @return true if nested scrolling is enabled
19402     *
19403     * @see #setNestedScrollingEnabled(boolean)
19404     */
19405    public boolean isNestedScrollingEnabled() {
19406        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19407                PFLAG3_NESTED_SCROLLING_ENABLED;
19408    }
19409
19410    /**
19411     * Begin a nestable scroll operation along the given axes.
19412     *
19413     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19414     *
19415     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19416     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19417     * In the case of touch scrolling the nested scroll will be terminated automatically in
19418     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19419     * In the event of programmatic scrolling the caller must explicitly call
19420     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19421     *
19422     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19423     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19424     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19425     *
19426     * <p>At each incremental step of the scroll the caller should invoke
19427     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19428     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19429     * parent at least partially consumed the scroll and the caller should adjust the amount it
19430     * scrolls by.</p>
19431     *
19432     * <p>After applying the remainder of the scroll delta the caller should invoke
19433     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19434     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19435     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19436     * </p>
19437     *
19438     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19439     *             {@link #SCROLL_AXIS_VERTICAL}.
19440     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19441     *         the current gesture.
19442     *
19443     * @see #stopNestedScroll()
19444     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19445     * @see #dispatchNestedScroll(int, int, int, int, int[])
19446     */
19447    public boolean startNestedScroll(int axes) {
19448        if (hasNestedScrollingParent()) {
19449            // Already in progress
19450            return true;
19451        }
19452        if (isNestedScrollingEnabled()) {
19453            ViewParent p = getParent();
19454            View child = this;
19455            while (p != null) {
19456                try {
19457                    if (p.onStartNestedScroll(child, this, axes)) {
19458                        mNestedScrollingParent = p;
19459                        p.onNestedScrollAccepted(child, this, axes);
19460                        return true;
19461                    }
19462                } catch (AbstractMethodError e) {
19463                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
19464                            "method onStartNestedScroll", e);
19465                    // Allow the search upward to continue
19466                }
19467                if (p instanceof View) {
19468                    child = (View) p;
19469                }
19470                p = p.getParent();
19471            }
19472        }
19473        return false;
19474    }
19475
19476    /**
19477     * Stop a nested scroll in progress.
19478     *
19479     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
19480     *
19481     * @see #startNestedScroll(int)
19482     */
19483    public void stopNestedScroll() {
19484        if (mNestedScrollingParent != null) {
19485            mNestedScrollingParent.onStopNestedScroll(this);
19486            mNestedScrollingParent = null;
19487        }
19488    }
19489
19490    /**
19491     * Returns true if this view has a nested scrolling parent.
19492     *
19493     * <p>The presence of a nested scrolling parent indicates that this view has initiated
19494     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
19495     *
19496     * @return whether this view has a nested scrolling parent
19497     */
19498    public boolean hasNestedScrollingParent() {
19499        return mNestedScrollingParent != null;
19500    }
19501
19502    /**
19503     * Dispatch one step of a nested scroll in progress.
19504     *
19505     * <p>Implementations of views that support nested scrolling should call this to report
19506     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
19507     * is not currently in progress or nested scrolling is not
19508     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
19509     *
19510     * <p>Compatible View implementations should also call
19511     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
19512     * consuming a component of the scroll event themselves.</p>
19513     *
19514     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
19515     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
19516     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
19517     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
19518     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19519     *                       in local view coordinates of this view from before this operation
19520     *                       to after it completes. View implementations may use this to adjust
19521     *                       expected input coordinate tracking.
19522     * @return true if the event was dispatched, false if it could not be dispatched.
19523     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19524     */
19525    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
19526            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
19527        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19528            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
19529                int startX = 0;
19530                int startY = 0;
19531                if (offsetInWindow != null) {
19532                    getLocationInWindow(offsetInWindow);
19533                    startX = offsetInWindow[0];
19534                    startY = offsetInWindow[1];
19535                }
19536
19537                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
19538                        dxUnconsumed, dyUnconsumed);
19539
19540                if (offsetInWindow != null) {
19541                    getLocationInWindow(offsetInWindow);
19542                    offsetInWindow[0] -= startX;
19543                    offsetInWindow[1] -= startY;
19544                }
19545                return true;
19546            } else if (offsetInWindow != null) {
19547                // No motion, no dispatch. Keep offsetInWindow up to date.
19548                offsetInWindow[0] = 0;
19549                offsetInWindow[1] = 0;
19550            }
19551        }
19552        return false;
19553    }
19554
19555    /**
19556     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
19557     *
19558     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
19559     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
19560     * scrolling operation to consume some or all of the scroll operation before the child view
19561     * consumes it.</p>
19562     *
19563     * @param dx Horizontal scroll distance in pixels
19564     * @param dy Vertical scroll distance in pixels
19565     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
19566     *                 and consumed[1] the consumed dy.
19567     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19568     *                       in local view coordinates of this view from before this operation
19569     *                       to after it completes. View implementations may use this to adjust
19570     *                       expected input coordinate tracking.
19571     * @return true if the parent consumed some or all of the scroll delta
19572     * @see #dispatchNestedScroll(int, int, int, int, int[])
19573     */
19574    public boolean dispatchNestedPreScroll(int dx, int dy,
19575            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
19576        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19577            if (dx != 0 || dy != 0) {
19578                int startX = 0;
19579                int startY = 0;
19580                if (offsetInWindow != null) {
19581                    getLocationInWindow(offsetInWindow);
19582                    startX = offsetInWindow[0];
19583                    startY = offsetInWindow[1];
19584                }
19585
19586                if (consumed == null) {
19587                    if (mTempNestedScrollConsumed == null) {
19588                        mTempNestedScrollConsumed = new int[2];
19589                    }
19590                    consumed = mTempNestedScrollConsumed;
19591                }
19592                consumed[0] = 0;
19593                consumed[1] = 0;
19594                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
19595
19596                if (offsetInWindow != null) {
19597                    getLocationInWindow(offsetInWindow);
19598                    offsetInWindow[0] -= startX;
19599                    offsetInWindow[1] -= startY;
19600                }
19601                return consumed[0] != 0 || consumed[1] != 0;
19602            } else if (offsetInWindow != null) {
19603                offsetInWindow[0] = 0;
19604                offsetInWindow[1] = 0;
19605            }
19606        }
19607        return false;
19608    }
19609
19610    /**
19611     * Dispatch a fling to a nested scrolling parent.
19612     *
19613     * <p>This method should be used to indicate that a nested scrolling child has detected
19614     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
19615     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19616     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19617     * along a scrollable axis.</p>
19618     *
19619     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19620     * its own content, it can use this method to delegate the fling to its nested scrolling
19621     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19622     *
19623     * @param velocityX Horizontal fling velocity in pixels per second
19624     * @param velocityY Vertical fling velocity in pixels per second
19625     * @param consumed true if the child consumed the fling, false otherwise
19626     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19627     */
19628    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19629        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19630            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19631        }
19632        return false;
19633    }
19634
19635    /**
19636     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19637     *
19638     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19639     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19640     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19641     * before the child view consumes it. If this method returns <code>true</code>, a nested
19642     * parent view consumed the fling and this view should not scroll as a result.</p>
19643     *
19644     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19645     * the fling at a time. If a parent view consumed the fling this method will return false.
19646     * Custom view implementations should account for this in two ways:</p>
19647     *
19648     * <ul>
19649     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19650     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19651     *     position regardless.</li>
19652     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19653     *     even to settle back to a valid idle position.</li>
19654     * </ul>
19655     *
19656     * <p>Views should also not offer fling velocities to nested parent views along an axis
19657     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19658     * should not offer a horizontal fling velocity to its parents since scrolling along that
19659     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19660     *
19661     * @param velocityX Horizontal fling velocity in pixels per second
19662     * @param velocityY Vertical fling velocity in pixels per second
19663     * @return true if a nested scrolling parent consumed the fling
19664     */
19665    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19666        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19667            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19668        }
19669        return false;
19670    }
19671
19672    /**
19673     * Gets a scale factor that determines the distance the view should scroll
19674     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19675     * @return The vertical scroll scale factor.
19676     * @hide
19677     */
19678    protected float getVerticalScrollFactor() {
19679        if (mVerticalScrollFactor == 0) {
19680            TypedValue outValue = new TypedValue();
19681            if (!mContext.getTheme().resolveAttribute(
19682                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19683                throw new IllegalStateException(
19684                        "Expected theme to define listPreferredItemHeight.");
19685            }
19686            mVerticalScrollFactor = outValue.getDimension(
19687                    mContext.getResources().getDisplayMetrics());
19688        }
19689        return mVerticalScrollFactor;
19690    }
19691
19692    /**
19693     * Gets a scale factor that determines the distance the view should scroll
19694     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19695     * @return The horizontal scroll scale factor.
19696     * @hide
19697     */
19698    protected float getHorizontalScrollFactor() {
19699        // TODO: Should use something else.
19700        return getVerticalScrollFactor();
19701    }
19702
19703    /**
19704     * Return the value specifying the text direction or policy that was set with
19705     * {@link #setTextDirection(int)}.
19706     *
19707     * @return the defined text direction. It can be one of:
19708     *
19709     * {@link #TEXT_DIRECTION_INHERIT},
19710     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19711     * {@link #TEXT_DIRECTION_ANY_RTL},
19712     * {@link #TEXT_DIRECTION_LTR},
19713     * {@link #TEXT_DIRECTION_RTL},
19714     * {@link #TEXT_DIRECTION_LOCALE},
19715     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19716     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19717     *
19718     * @attr ref android.R.styleable#View_textDirection
19719     *
19720     * @hide
19721     */
19722    @ViewDebug.ExportedProperty(category = "text", mapping = {
19723            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19724            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19725            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19726            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19727            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19728            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19729            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19730            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19731    })
19732    public int getRawTextDirection() {
19733        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19734    }
19735
19736    /**
19737     * Set the text direction.
19738     *
19739     * @param textDirection the direction to set. Should be one of:
19740     *
19741     * {@link #TEXT_DIRECTION_INHERIT},
19742     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19743     * {@link #TEXT_DIRECTION_ANY_RTL},
19744     * {@link #TEXT_DIRECTION_LTR},
19745     * {@link #TEXT_DIRECTION_RTL},
19746     * {@link #TEXT_DIRECTION_LOCALE}
19747     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19748     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
19749     *
19750     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19751     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19752     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19753     *
19754     * @attr ref android.R.styleable#View_textDirection
19755     */
19756    public void setTextDirection(int textDirection) {
19757        if (getRawTextDirection() != textDirection) {
19758            // Reset the current text direction and the resolved one
19759            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19760            resetResolvedTextDirection();
19761            // Set the new text direction
19762            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19763            // Do resolution
19764            resolveTextDirection();
19765            // Notify change
19766            onRtlPropertiesChanged(getLayoutDirection());
19767            // Refresh
19768            requestLayout();
19769            invalidate(true);
19770        }
19771    }
19772
19773    /**
19774     * Return the resolved text direction.
19775     *
19776     * @return the resolved text direction. Returns one of:
19777     *
19778     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19779     * {@link #TEXT_DIRECTION_ANY_RTL},
19780     * {@link #TEXT_DIRECTION_LTR},
19781     * {@link #TEXT_DIRECTION_RTL},
19782     * {@link #TEXT_DIRECTION_LOCALE},
19783     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19784     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19785     *
19786     * @attr ref android.R.styleable#View_textDirection
19787     */
19788    @ViewDebug.ExportedProperty(category = "text", mapping = {
19789            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19790            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19791            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19792            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19793            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19794            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19795            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19796            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19797    })
19798    public int getTextDirection() {
19799        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19800    }
19801
19802    /**
19803     * Resolve the text direction.
19804     *
19805     * @return true if resolution has been done, false otherwise.
19806     *
19807     * @hide
19808     */
19809    public boolean resolveTextDirection() {
19810        // Reset any previous text direction resolution
19811        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19812
19813        if (hasRtlSupport()) {
19814            // Set resolved text direction flag depending on text direction flag
19815            final int textDirection = getRawTextDirection();
19816            switch(textDirection) {
19817                case TEXT_DIRECTION_INHERIT:
19818                    if (!canResolveTextDirection()) {
19819                        // We cannot do the resolution if there is no parent, so use the default one
19820                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19821                        // Resolution will need to happen again later
19822                        return false;
19823                    }
19824
19825                    // Parent has not yet resolved, so we still return the default
19826                    try {
19827                        if (!mParent.isTextDirectionResolved()) {
19828                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19829                            // Resolution will need to happen again later
19830                            return false;
19831                        }
19832                    } catch (AbstractMethodError e) {
19833                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19834                                " does not fully implement ViewParent", e);
19835                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19836                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19837                        return true;
19838                    }
19839
19840                    // Set current resolved direction to the same value as the parent's one
19841                    int parentResolvedDirection;
19842                    try {
19843                        parentResolvedDirection = mParent.getTextDirection();
19844                    } catch (AbstractMethodError e) {
19845                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19846                                " does not fully implement ViewParent", e);
19847                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19848                    }
19849                    switch (parentResolvedDirection) {
19850                        case TEXT_DIRECTION_FIRST_STRONG:
19851                        case TEXT_DIRECTION_ANY_RTL:
19852                        case TEXT_DIRECTION_LTR:
19853                        case TEXT_DIRECTION_RTL:
19854                        case TEXT_DIRECTION_LOCALE:
19855                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
19856                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
19857                            mPrivateFlags2 |=
19858                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19859                            break;
19860                        default:
19861                            // Default resolved direction is "first strong" heuristic
19862                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19863                    }
19864                    break;
19865                case TEXT_DIRECTION_FIRST_STRONG:
19866                case TEXT_DIRECTION_ANY_RTL:
19867                case TEXT_DIRECTION_LTR:
19868                case TEXT_DIRECTION_RTL:
19869                case TEXT_DIRECTION_LOCALE:
19870                case TEXT_DIRECTION_FIRST_STRONG_LTR:
19871                case TEXT_DIRECTION_FIRST_STRONG_RTL:
19872                    // Resolved direction is the same as text direction
19873                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19874                    break;
19875                default:
19876                    // Default resolved direction is "first strong" heuristic
19877                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19878            }
19879        } else {
19880            // Default resolved direction is "first strong" heuristic
19881            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19882        }
19883
19884        // Set to resolved
19885        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19886        return true;
19887    }
19888
19889    /**
19890     * Check if text direction resolution can be done.
19891     *
19892     * @return true if text direction resolution can be done otherwise return false.
19893     */
19894    public boolean canResolveTextDirection() {
19895        switch (getRawTextDirection()) {
19896            case TEXT_DIRECTION_INHERIT:
19897                if (mParent != null) {
19898                    try {
19899                        return mParent.canResolveTextDirection();
19900                    } catch (AbstractMethodError e) {
19901                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19902                                " does not fully implement ViewParent", e);
19903                    }
19904                }
19905                return false;
19906
19907            default:
19908                return true;
19909        }
19910    }
19911
19912    /**
19913     * Reset resolved text direction. Text direction will be resolved during a call to
19914     * {@link #onMeasure(int, int)}.
19915     *
19916     * @hide
19917     */
19918    public void resetResolvedTextDirection() {
19919        // Reset any previous text direction resolution
19920        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19921        // Set to default value
19922        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19923    }
19924
19925    /**
19926     * @return true if text direction is inherited.
19927     *
19928     * @hide
19929     */
19930    public boolean isTextDirectionInherited() {
19931        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19932    }
19933
19934    /**
19935     * @return true if text direction is resolved.
19936     */
19937    public boolean isTextDirectionResolved() {
19938        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19939    }
19940
19941    /**
19942     * Return the value specifying the text alignment or policy that was set with
19943     * {@link #setTextAlignment(int)}.
19944     *
19945     * @return the defined text alignment. It can be one of:
19946     *
19947     * {@link #TEXT_ALIGNMENT_INHERIT},
19948     * {@link #TEXT_ALIGNMENT_GRAVITY},
19949     * {@link #TEXT_ALIGNMENT_CENTER},
19950     * {@link #TEXT_ALIGNMENT_TEXT_START},
19951     * {@link #TEXT_ALIGNMENT_TEXT_END},
19952     * {@link #TEXT_ALIGNMENT_VIEW_START},
19953     * {@link #TEXT_ALIGNMENT_VIEW_END}
19954     *
19955     * @attr ref android.R.styleable#View_textAlignment
19956     *
19957     * @hide
19958     */
19959    @ViewDebug.ExportedProperty(category = "text", mapping = {
19960            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19961            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19962            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19963            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19964            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19965            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19966            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19967    })
19968    @TextAlignment
19969    public int getRawTextAlignment() {
19970        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19971    }
19972
19973    /**
19974     * Set the text alignment.
19975     *
19976     * @param textAlignment The text alignment to set. Should be one of
19977     *
19978     * {@link #TEXT_ALIGNMENT_INHERIT},
19979     * {@link #TEXT_ALIGNMENT_GRAVITY},
19980     * {@link #TEXT_ALIGNMENT_CENTER},
19981     * {@link #TEXT_ALIGNMENT_TEXT_START},
19982     * {@link #TEXT_ALIGNMENT_TEXT_END},
19983     * {@link #TEXT_ALIGNMENT_VIEW_START},
19984     * {@link #TEXT_ALIGNMENT_VIEW_END}
19985     *
19986     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19987     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19988     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19989     *
19990     * @attr ref android.R.styleable#View_textAlignment
19991     */
19992    public void setTextAlignment(@TextAlignment int textAlignment) {
19993        if (textAlignment != getRawTextAlignment()) {
19994            // Reset the current and resolved text alignment
19995            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19996            resetResolvedTextAlignment();
19997            // Set the new text alignment
19998            mPrivateFlags2 |=
19999                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
20000            // Do resolution
20001            resolveTextAlignment();
20002            // Notify change
20003            onRtlPropertiesChanged(getLayoutDirection());
20004            // Refresh
20005            requestLayout();
20006            invalidate(true);
20007        }
20008    }
20009
20010    /**
20011     * Return the resolved text alignment.
20012     *
20013     * @return the resolved text alignment. Returns one of:
20014     *
20015     * {@link #TEXT_ALIGNMENT_GRAVITY},
20016     * {@link #TEXT_ALIGNMENT_CENTER},
20017     * {@link #TEXT_ALIGNMENT_TEXT_START},
20018     * {@link #TEXT_ALIGNMENT_TEXT_END},
20019     * {@link #TEXT_ALIGNMENT_VIEW_START},
20020     * {@link #TEXT_ALIGNMENT_VIEW_END}
20021     *
20022     * @attr ref android.R.styleable#View_textAlignment
20023     */
20024    @ViewDebug.ExportedProperty(category = "text", mapping = {
20025            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20026            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20027            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20028            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20029            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20030            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20031            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20032    })
20033    @TextAlignment
20034    public int getTextAlignment() {
20035        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20036                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20037    }
20038
20039    /**
20040     * Resolve the text alignment.
20041     *
20042     * @return true if resolution has been done, false otherwise.
20043     *
20044     * @hide
20045     */
20046    public boolean resolveTextAlignment() {
20047        // Reset any previous text alignment resolution
20048        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20049
20050        if (hasRtlSupport()) {
20051            // Set resolved text alignment flag depending on text alignment flag
20052            final int textAlignment = getRawTextAlignment();
20053            switch (textAlignment) {
20054                case TEXT_ALIGNMENT_INHERIT:
20055                    // Check if we can resolve the text alignment
20056                    if (!canResolveTextAlignment()) {
20057                        // We cannot do the resolution if there is no parent so use the default
20058                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20059                        // Resolution will need to happen again later
20060                        return false;
20061                    }
20062
20063                    // Parent has not yet resolved, so we still return the default
20064                    try {
20065                        if (!mParent.isTextAlignmentResolved()) {
20066                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20067                            // Resolution will need to happen again later
20068                            return false;
20069                        }
20070                    } catch (AbstractMethodError e) {
20071                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20072                                " does not fully implement ViewParent", e);
20073                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20074                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20075                        return true;
20076                    }
20077
20078                    int parentResolvedTextAlignment;
20079                    try {
20080                        parentResolvedTextAlignment = mParent.getTextAlignment();
20081                    } catch (AbstractMethodError e) {
20082                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20083                                " does not fully implement ViewParent", e);
20084                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20085                    }
20086                    switch (parentResolvedTextAlignment) {
20087                        case TEXT_ALIGNMENT_GRAVITY:
20088                        case TEXT_ALIGNMENT_TEXT_START:
20089                        case TEXT_ALIGNMENT_TEXT_END:
20090                        case TEXT_ALIGNMENT_CENTER:
20091                        case TEXT_ALIGNMENT_VIEW_START:
20092                        case TEXT_ALIGNMENT_VIEW_END:
20093                            // Resolved text alignment is the same as the parent resolved
20094                            // text alignment
20095                            mPrivateFlags2 |=
20096                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20097                            break;
20098                        default:
20099                            // Use default resolved text alignment
20100                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20101                    }
20102                    break;
20103                case TEXT_ALIGNMENT_GRAVITY:
20104                case TEXT_ALIGNMENT_TEXT_START:
20105                case TEXT_ALIGNMENT_TEXT_END:
20106                case TEXT_ALIGNMENT_CENTER:
20107                case TEXT_ALIGNMENT_VIEW_START:
20108                case TEXT_ALIGNMENT_VIEW_END:
20109                    // Resolved text alignment is the same as text alignment
20110                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20111                    break;
20112                default:
20113                    // Use default resolved text alignment
20114                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20115            }
20116        } else {
20117            // Use default resolved text alignment
20118            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20119        }
20120
20121        // Set the resolved
20122        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20123        return true;
20124    }
20125
20126    /**
20127     * Check if text alignment resolution can be done.
20128     *
20129     * @return true if text alignment resolution can be done otherwise return false.
20130     */
20131    public boolean canResolveTextAlignment() {
20132        switch (getRawTextAlignment()) {
20133            case TEXT_DIRECTION_INHERIT:
20134                if (mParent != null) {
20135                    try {
20136                        return mParent.canResolveTextAlignment();
20137                    } catch (AbstractMethodError e) {
20138                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20139                                " does not fully implement ViewParent", e);
20140                    }
20141                }
20142                return false;
20143
20144            default:
20145                return true;
20146        }
20147    }
20148
20149    /**
20150     * Reset resolved text alignment. Text alignment will be resolved during a call to
20151     * {@link #onMeasure(int, int)}.
20152     *
20153     * @hide
20154     */
20155    public void resetResolvedTextAlignment() {
20156        // Reset any previous text alignment resolution
20157        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20158        // Set to default
20159        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20160    }
20161
20162    /**
20163     * @return true if text alignment is inherited.
20164     *
20165     * @hide
20166     */
20167    public boolean isTextAlignmentInherited() {
20168        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20169    }
20170
20171    /**
20172     * @return true if text alignment is resolved.
20173     */
20174    public boolean isTextAlignmentResolved() {
20175        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20176    }
20177
20178    /**
20179     * Generate a value suitable for use in {@link #setId(int)}.
20180     * This value will not collide with ID values generated at build time by aapt for R.id.
20181     *
20182     * @return a generated ID value
20183     */
20184    public static int generateViewId() {
20185        for (;;) {
20186            final int result = sNextGeneratedId.get();
20187            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20188            int newValue = result + 1;
20189            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20190            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20191                return result;
20192            }
20193        }
20194    }
20195
20196    /**
20197     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20198     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20199     *                           a normal View or a ViewGroup with
20200     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20201     * @hide
20202     */
20203    public void captureTransitioningViews(List<View> transitioningViews) {
20204        if (getVisibility() == View.VISIBLE) {
20205            transitioningViews.add(this);
20206        }
20207    }
20208
20209    /**
20210     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20211     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20212     * @hide
20213     */
20214    public void findNamedViews(Map<String, View> namedElements) {
20215        if (getVisibility() == VISIBLE || mGhostView != null) {
20216            String transitionName = getTransitionName();
20217            if (transitionName != null) {
20218                namedElements.put(transitionName, this);
20219            }
20220        }
20221    }
20222
20223    //
20224    // Properties
20225    //
20226    /**
20227     * A Property wrapper around the <code>alpha</code> functionality handled by the
20228     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20229     */
20230    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20231        @Override
20232        public void setValue(View object, float value) {
20233            object.setAlpha(value);
20234        }
20235
20236        @Override
20237        public Float get(View object) {
20238            return object.getAlpha();
20239        }
20240    };
20241
20242    /**
20243     * A Property wrapper around the <code>translationX</code> functionality handled by the
20244     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20245     */
20246    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20247        @Override
20248        public void setValue(View object, float value) {
20249            object.setTranslationX(value);
20250        }
20251
20252                @Override
20253        public Float get(View object) {
20254            return object.getTranslationX();
20255        }
20256    };
20257
20258    /**
20259     * A Property wrapper around the <code>translationY</code> functionality handled by the
20260     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20261     */
20262    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20263        @Override
20264        public void setValue(View object, float value) {
20265            object.setTranslationY(value);
20266        }
20267
20268        @Override
20269        public Float get(View object) {
20270            return object.getTranslationY();
20271        }
20272    };
20273
20274    /**
20275     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20276     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20277     */
20278    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20279        @Override
20280        public void setValue(View object, float value) {
20281            object.setTranslationZ(value);
20282        }
20283
20284        @Override
20285        public Float get(View object) {
20286            return object.getTranslationZ();
20287        }
20288    };
20289
20290    /**
20291     * A Property wrapper around the <code>x</code> functionality handled by the
20292     * {@link View#setX(float)} and {@link View#getX()} methods.
20293     */
20294    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20295        @Override
20296        public void setValue(View object, float value) {
20297            object.setX(value);
20298        }
20299
20300        @Override
20301        public Float get(View object) {
20302            return object.getX();
20303        }
20304    };
20305
20306    /**
20307     * A Property wrapper around the <code>y</code> functionality handled by the
20308     * {@link View#setY(float)} and {@link View#getY()} methods.
20309     */
20310    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20311        @Override
20312        public void setValue(View object, float value) {
20313            object.setY(value);
20314        }
20315
20316        @Override
20317        public Float get(View object) {
20318            return object.getY();
20319        }
20320    };
20321
20322    /**
20323     * A Property wrapper around the <code>z</code> functionality handled by the
20324     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20325     */
20326    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20327        @Override
20328        public void setValue(View object, float value) {
20329            object.setZ(value);
20330        }
20331
20332        @Override
20333        public Float get(View object) {
20334            return object.getZ();
20335        }
20336    };
20337
20338    /**
20339     * A Property wrapper around the <code>rotation</code> functionality handled by the
20340     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20341     */
20342    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20343        @Override
20344        public void setValue(View object, float value) {
20345            object.setRotation(value);
20346        }
20347
20348        @Override
20349        public Float get(View object) {
20350            return object.getRotation();
20351        }
20352    };
20353
20354    /**
20355     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20356     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20357     */
20358    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20359        @Override
20360        public void setValue(View object, float value) {
20361            object.setRotationX(value);
20362        }
20363
20364        @Override
20365        public Float get(View object) {
20366            return object.getRotationX();
20367        }
20368    };
20369
20370    /**
20371     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20372     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20373     */
20374    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20375        @Override
20376        public void setValue(View object, float value) {
20377            object.setRotationY(value);
20378        }
20379
20380        @Override
20381        public Float get(View object) {
20382            return object.getRotationY();
20383        }
20384    };
20385
20386    /**
20387     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20388     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20389     */
20390    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20391        @Override
20392        public void setValue(View object, float value) {
20393            object.setScaleX(value);
20394        }
20395
20396        @Override
20397        public Float get(View object) {
20398            return object.getScaleX();
20399        }
20400    };
20401
20402    /**
20403     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20404     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20405     */
20406    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20407        @Override
20408        public void setValue(View object, float value) {
20409            object.setScaleY(value);
20410        }
20411
20412        @Override
20413        public Float get(View object) {
20414            return object.getScaleY();
20415        }
20416    };
20417
20418    /**
20419     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20420     * Each MeasureSpec represents a requirement for either the width or the height.
20421     * A MeasureSpec is comprised of a size and a mode. There are three possible
20422     * modes:
20423     * <dl>
20424     * <dt>UNSPECIFIED</dt>
20425     * <dd>
20426     * The parent has not imposed any constraint on the child. It can be whatever size
20427     * it wants.
20428     * </dd>
20429     *
20430     * <dt>EXACTLY</dt>
20431     * <dd>
20432     * The parent has determined an exact size for the child. The child is going to be
20433     * given those bounds regardless of how big it wants to be.
20434     * </dd>
20435     *
20436     * <dt>AT_MOST</dt>
20437     * <dd>
20438     * The child can be as large as it wants up to the specified size.
20439     * </dd>
20440     * </dl>
20441     *
20442     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20443     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20444     */
20445    public static class MeasureSpec {
20446        private static final int MODE_SHIFT = 30;
20447        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20448
20449        /**
20450         * Measure specification mode: The parent has not imposed any constraint
20451         * on the child. It can be whatever size it wants.
20452         */
20453        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
20454
20455        /**
20456         * Measure specification mode: The parent has determined an exact size
20457         * for the child. The child is going to be given those bounds regardless
20458         * of how big it wants to be.
20459         */
20460        public static final int EXACTLY     = 1 << MODE_SHIFT;
20461
20462        /**
20463         * Measure specification mode: The child can be as large as it wants up
20464         * to the specified size.
20465         */
20466        public static final int AT_MOST     = 2 << MODE_SHIFT;
20467
20468        /**
20469         * Creates a measure specification based on the supplied size and mode.
20470         *
20471         * The mode must always be one of the following:
20472         * <ul>
20473         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
20474         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
20475         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
20476         * </ul>
20477         *
20478         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
20479         * implementation was such that the order of arguments did not matter
20480         * and overflow in either value could impact the resulting MeasureSpec.
20481         * {@link android.widget.RelativeLayout} was affected by this bug.
20482         * Apps targeting API levels greater than 17 will get the fixed, more strict
20483         * behavior.</p>
20484         *
20485         * @param size the size of the measure specification
20486         * @param mode the mode of the measure specification
20487         * @return the measure specification based on size and mode
20488         */
20489        public static int makeMeasureSpec(int size, int mode) {
20490            if (sUseBrokenMakeMeasureSpec) {
20491                return size + mode;
20492            } else {
20493                return (size & ~MODE_MASK) | (mode & MODE_MASK);
20494            }
20495        }
20496
20497        /**
20498         * Extracts the mode from the supplied measure specification.
20499         *
20500         * @param measureSpec the measure specification to extract the mode from
20501         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
20502         *         {@link android.view.View.MeasureSpec#AT_MOST} or
20503         *         {@link android.view.View.MeasureSpec#EXACTLY}
20504         */
20505        public static int getMode(int measureSpec) {
20506            return (measureSpec & MODE_MASK);
20507        }
20508
20509        /**
20510         * Extracts the size from the supplied measure specification.
20511         *
20512         * @param measureSpec the measure specification to extract the size from
20513         * @return the size in pixels defined in the supplied measure specification
20514         */
20515        public static int getSize(int measureSpec) {
20516            return (measureSpec & ~MODE_MASK);
20517        }
20518
20519        static int adjust(int measureSpec, int delta) {
20520            final int mode = getMode(measureSpec);
20521            int size = getSize(measureSpec);
20522            if (mode == UNSPECIFIED) {
20523                // No need to adjust size for UNSPECIFIED mode.
20524                return makeMeasureSpec(size, UNSPECIFIED);
20525            }
20526            size += delta;
20527            if (size < 0) {
20528                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
20529                        ") spec: " + toString(measureSpec) + " delta: " + delta);
20530                size = 0;
20531            }
20532            return makeMeasureSpec(size, mode);
20533        }
20534
20535        /**
20536         * Returns a String representation of the specified measure
20537         * specification.
20538         *
20539         * @param measureSpec the measure specification to convert to a String
20540         * @return a String with the following format: "MeasureSpec: MODE SIZE"
20541         */
20542        public static String toString(int measureSpec) {
20543            int mode = getMode(measureSpec);
20544            int size = getSize(measureSpec);
20545
20546            StringBuilder sb = new StringBuilder("MeasureSpec: ");
20547
20548            if (mode == UNSPECIFIED)
20549                sb.append("UNSPECIFIED ");
20550            else if (mode == EXACTLY)
20551                sb.append("EXACTLY ");
20552            else if (mode == AT_MOST)
20553                sb.append("AT_MOST ");
20554            else
20555                sb.append(mode).append(" ");
20556
20557            sb.append(size);
20558            return sb.toString();
20559        }
20560    }
20561
20562    private final class CheckForLongPress implements Runnable {
20563        private int mOriginalWindowAttachCount;
20564
20565        @Override
20566        public void run() {
20567            if (isPressed() && (mParent != null)
20568                    && mOriginalWindowAttachCount == mWindowAttachCount) {
20569                if (performLongClick()) {
20570                    mHasPerformedLongPress = true;
20571                }
20572            }
20573        }
20574
20575        public void rememberWindowAttachCount() {
20576            mOriginalWindowAttachCount = mWindowAttachCount;
20577        }
20578    }
20579
20580    private final class CheckForTap implements Runnable {
20581        public float x;
20582        public float y;
20583
20584        @Override
20585        public void run() {
20586            mPrivateFlags &= ~PFLAG_PREPRESSED;
20587            setPressed(true, x, y);
20588            checkForLongClick(ViewConfiguration.getTapTimeout());
20589        }
20590    }
20591
20592    private final class PerformClick implements Runnable {
20593        @Override
20594        public void run() {
20595            performClick();
20596        }
20597    }
20598
20599    /** @hide */
20600    public void hackTurnOffWindowResizeAnim(boolean off) {
20601        mAttachInfo.mTurnOffWindowResizeAnim = off;
20602    }
20603
20604    /**
20605     * This method returns a ViewPropertyAnimator object, which can be used to animate
20606     * specific properties on this View.
20607     *
20608     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
20609     */
20610    public ViewPropertyAnimator animate() {
20611        if (mAnimator == null) {
20612            mAnimator = new ViewPropertyAnimator(this);
20613        }
20614        return mAnimator;
20615    }
20616
20617    /**
20618     * Sets the name of the View to be used to identify Views in Transitions.
20619     * Names should be unique in the View hierarchy.
20620     *
20621     * @param transitionName The name of the View to uniquely identify it for Transitions.
20622     */
20623    public final void setTransitionName(String transitionName) {
20624        mTransitionName = transitionName;
20625    }
20626
20627    /**
20628     * Returns the name of the View to be used to identify Views in Transitions.
20629     * Names should be unique in the View hierarchy.
20630     *
20631     * <p>This returns null if the View has not been given a name.</p>
20632     *
20633     * @return The name used of the View to be used to identify Views in Transitions or null
20634     * if no name has been given.
20635     */
20636    @ViewDebug.ExportedProperty
20637    public String getTransitionName() {
20638        return mTransitionName;
20639    }
20640
20641    /**
20642     * Interface definition for a callback to be invoked when a hardware key event is
20643     * dispatched to this view. The callback will be invoked before the key event is
20644     * given to the view. This is only useful for hardware keyboards; a software input
20645     * method has no obligation to trigger this listener.
20646     */
20647    public interface OnKeyListener {
20648        /**
20649         * Called when a hardware key is dispatched to a view. This allows listeners to
20650         * get a chance to respond before the target view.
20651         * <p>Key presses in software keyboards will generally NOT trigger this method,
20652         * although some may elect to do so in some situations. Do not assume a
20653         * software input method has to be key-based; even if it is, it may use key presses
20654         * in a different way than you expect, so there is no way to reliably catch soft
20655         * input key presses.
20656         *
20657         * @param v The view the key has been dispatched to.
20658         * @param keyCode The code for the physical key that was pressed
20659         * @param event The KeyEvent object containing full information about
20660         *        the event.
20661         * @return True if the listener has consumed the event, false otherwise.
20662         */
20663        boolean onKey(View v, int keyCode, KeyEvent event);
20664    }
20665
20666    /**
20667     * Interface definition for a callback to be invoked when a touch event is
20668     * dispatched to this view. The callback will be invoked before the touch
20669     * event is given to the view.
20670     */
20671    public interface OnTouchListener {
20672        /**
20673         * Called when a touch event is dispatched to a view. This allows listeners to
20674         * get a chance to respond before the target view.
20675         *
20676         * @param v The view the touch event has been dispatched to.
20677         * @param event The MotionEvent object containing full information about
20678         *        the event.
20679         * @return True if the listener has consumed the event, false otherwise.
20680         */
20681        boolean onTouch(View v, MotionEvent event);
20682    }
20683
20684    /**
20685     * Interface definition for a callback to be invoked when a hover event is
20686     * dispatched to this view. The callback will be invoked before the hover
20687     * event is given to the view.
20688     */
20689    public interface OnHoverListener {
20690        /**
20691         * Called when a hover event is dispatched to a view. This allows listeners to
20692         * get a chance to respond before the target view.
20693         *
20694         * @param v The view the hover event has been dispatched to.
20695         * @param event The MotionEvent object containing full information about
20696         *        the event.
20697         * @return True if the listener has consumed the event, false otherwise.
20698         */
20699        boolean onHover(View v, MotionEvent event);
20700    }
20701
20702    /**
20703     * Interface definition for a callback to be invoked when a generic motion event is
20704     * dispatched to this view. The callback will be invoked before the generic motion
20705     * event is given to the view.
20706     */
20707    public interface OnGenericMotionListener {
20708        /**
20709         * Called when a generic motion event is dispatched to a view. This allows listeners to
20710         * get a chance to respond before the target view.
20711         *
20712         * @param v The view the generic motion event has been dispatched to.
20713         * @param event The MotionEvent object containing full information about
20714         *        the event.
20715         * @return True if the listener has consumed the event, false otherwise.
20716         */
20717        boolean onGenericMotion(View v, MotionEvent event);
20718    }
20719
20720    /**
20721     * Interface definition for a callback to be invoked when a view has been clicked and held.
20722     */
20723    public interface OnLongClickListener {
20724        /**
20725         * Called when a view has been clicked and held.
20726         *
20727         * @param v The view that was clicked and held.
20728         *
20729         * @return true if the callback consumed the long click, false otherwise.
20730         */
20731        boolean onLongClick(View v);
20732    }
20733
20734    /**
20735     * Interface definition for a callback to be invoked when a drag is being dispatched
20736     * to this view.  The callback will be invoked before the hosting view's own
20737     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20738     * onDrag(event) behavior, it should return 'false' from this callback.
20739     *
20740     * <div class="special reference">
20741     * <h3>Developer Guides</h3>
20742     * <p>For a guide to implementing drag and drop features, read the
20743     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20744     * </div>
20745     */
20746    public interface OnDragListener {
20747        /**
20748         * Called when a drag event is dispatched to a view. This allows listeners
20749         * to get a chance to override base View behavior.
20750         *
20751         * @param v The View that received the drag event.
20752         * @param event The {@link android.view.DragEvent} object for the drag event.
20753         * @return {@code true} if the drag event was handled successfully, or {@code false}
20754         * if the drag event was not handled. Note that {@code false} will trigger the View
20755         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20756         */
20757        boolean onDrag(View v, DragEvent event);
20758    }
20759
20760    /**
20761     * Interface definition for a callback to be invoked when the focus state of
20762     * a view changed.
20763     */
20764    public interface OnFocusChangeListener {
20765        /**
20766         * Called when the focus state of a view has changed.
20767         *
20768         * @param v The view whose state has changed.
20769         * @param hasFocus The new focus state of v.
20770         */
20771        void onFocusChange(View v, boolean hasFocus);
20772    }
20773
20774    /**
20775     * Interface definition for a callback to be invoked when a view is clicked.
20776     */
20777    public interface OnClickListener {
20778        /**
20779         * Called when a view has been clicked.
20780         *
20781         * @param v The view that was clicked.
20782         */
20783        void onClick(View v);
20784    }
20785
20786    /**
20787     * Interface definition for a callback to be invoked when the context menu
20788     * for this view is being built.
20789     */
20790    public interface OnCreateContextMenuListener {
20791        /**
20792         * Called when the context menu for this view is being built. It is not
20793         * safe to hold onto the menu after this method returns.
20794         *
20795         * @param menu The context menu that is being built
20796         * @param v The view for which the context menu is being built
20797         * @param menuInfo Extra information about the item for which the
20798         *            context menu should be shown. This information will vary
20799         *            depending on the class of v.
20800         */
20801        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20802    }
20803
20804    /**
20805     * Interface definition for a callback to be invoked when the status bar changes
20806     * visibility.  This reports <strong>global</strong> changes to the system UI
20807     * state, not what the application is requesting.
20808     *
20809     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20810     */
20811    public interface OnSystemUiVisibilityChangeListener {
20812        /**
20813         * Called when the status bar changes visibility because of a call to
20814         * {@link View#setSystemUiVisibility(int)}.
20815         *
20816         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20817         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20818         * This tells you the <strong>global</strong> state of these UI visibility
20819         * flags, not what your app is currently applying.
20820         */
20821        public void onSystemUiVisibilityChange(int visibility);
20822    }
20823
20824    /**
20825     * Interface definition for a callback to be invoked when this view is attached
20826     * or detached from its window.
20827     */
20828    public interface OnAttachStateChangeListener {
20829        /**
20830         * Called when the view is attached to a window.
20831         * @param v The view that was attached
20832         */
20833        public void onViewAttachedToWindow(View v);
20834        /**
20835         * Called when the view is detached from a window.
20836         * @param v The view that was detached
20837         */
20838        public void onViewDetachedFromWindow(View v);
20839    }
20840
20841    /**
20842     * Listener for applying window insets on a view in a custom way.
20843     *
20844     * <p>Apps may choose to implement this interface if they want to apply custom policy
20845     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20846     * is set, its
20847     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20848     * method will be called instead of the View's own
20849     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20850     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20851     * the View's normal behavior as part of its own.</p>
20852     */
20853    public interface OnApplyWindowInsetsListener {
20854        /**
20855         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20856         * on a View, this listener method will be called instead of the view's own
20857         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20858         *
20859         * @param v The view applying window insets
20860         * @param insets The insets to apply
20861         * @return The insets supplied, minus any insets that were consumed
20862         */
20863        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20864    }
20865
20866    private final class UnsetPressedState implements Runnable {
20867        @Override
20868        public void run() {
20869            setPressed(false);
20870        }
20871    }
20872
20873    /**
20874     * Base class for derived classes that want to save and restore their own
20875     * state in {@link android.view.View#onSaveInstanceState()}.
20876     */
20877    public static class BaseSavedState extends AbsSavedState {
20878        String mStartActivityRequestWhoSaved;
20879
20880        /**
20881         * Constructor used when reading from a parcel. Reads the state of the superclass.
20882         *
20883         * @param source
20884         */
20885        public BaseSavedState(Parcel source) {
20886            super(source);
20887            mStartActivityRequestWhoSaved = source.readString();
20888        }
20889
20890        /**
20891         * Constructor called by derived classes when creating their SavedState objects
20892         *
20893         * @param superState The state of the superclass of this view
20894         */
20895        public BaseSavedState(Parcelable superState) {
20896            super(superState);
20897        }
20898
20899        @Override
20900        public void writeToParcel(Parcel out, int flags) {
20901            super.writeToParcel(out, flags);
20902            out.writeString(mStartActivityRequestWhoSaved);
20903        }
20904
20905        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20906                new Parcelable.Creator<BaseSavedState>() {
20907            public BaseSavedState createFromParcel(Parcel in) {
20908                return new BaseSavedState(in);
20909            }
20910
20911            public BaseSavedState[] newArray(int size) {
20912                return new BaseSavedState[size];
20913            }
20914        };
20915    }
20916
20917    /**
20918     * A set of information given to a view when it is attached to its parent
20919     * window.
20920     */
20921    final static class AttachInfo {
20922        interface Callbacks {
20923            void playSoundEffect(int effectId);
20924            boolean performHapticFeedback(int effectId, boolean always);
20925        }
20926
20927        /**
20928         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20929         * to a Handler. This class contains the target (View) to invalidate and
20930         * the coordinates of the dirty rectangle.
20931         *
20932         * For performance purposes, this class also implements a pool of up to
20933         * POOL_LIMIT objects that get reused. This reduces memory allocations
20934         * whenever possible.
20935         */
20936        static class InvalidateInfo {
20937            private static final int POOL_LIMIT = 10;
20938
20939            private static final SynchronizedPool<InvalidateInfo> sPool =
20940                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20941
20942            View target;
20943
20944            int left;
20945            int top;
20946            int right;
20947            int bottom;
20948
20949            public static InvalidateInfo obtain() {
20950                InvalidateInfo instance = sPool.acquire();
20951                return (instance != null) ? instance : new InvalidateInfo();
20952            }
20953
20954            public void recycle() {
20955                target = null;
20956                sPool.release(this);
20957            }
20958        }
20959
20960        final IWindowSession mSession;
20961
20962        final IWindow mWindow;
20963
20964        final IBinder mWindowToken;
20965
20966        final Display mDisplay;
20967
20968        final Callbacks mRootCallbacks;
20969
20970        IWindowId mIWindowId;
20971        WindowId mWindowId;
20972
20973        /**
20974         * The top view of the hierarchy.
20975         */
20976        View mRootView;
20977
20978        IBinder mPanelParentWindowToken;
20979
20980        boolean mHardwareAccelerated;
20981        boolean mHardwareAccelerationRequested;
20982        HardwareRenderer mHardwareRenderer;
20983        List<RenderNode> mPendingAnimatingRenderNodes;
20984
20985        /**
20986         * The state of the display to which the window is attached, as reported
20987         * by {@link Display#getState()}.  Note that the display state constants
20988         * declared by {@link Display} do not exactly line up with the screen state
20989         * constants declared by {@link View} (there are more display states than
20990         * screen states).
20991         */
20992        int mDisplayState = Display.STATE_UNKNOWN;
20993
20994        /**
20995         * Scale factor used by the compatibility mode
20996         */
20997        float mApplicationScale;
20998
20999        /**
21000         * Indicates whether the application is in compatibility mode
21001         */
21002        boolean mScalingRequired;
21003
21004        /**
21005         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
21006         */
21007        boolean mTurnOffWindowResizeAnim;
21008
21009        /**
21010         * Left position of this view's window
21011         */
21012        int mWindowLeft;
21013
21014        /**
21015         * Top position of this view's window
21016         */
21017        int mWindowTop;
21018
21019        /**
21020         * Indicates whether views need to use 32-bit drawing caches
21021         */
21022        boolean mUse32BitDrawingCache;
21023
21024        /**
21025         * For windows that are full-screen but using insets to layout inside
21026         * of the screen areas, these are the current insets to appear inside
21027         * the overscan area of the display.
21028         */
21029        final Rect mOverscanInsets = new Rect();
21030
21031        /**
21032         * For windows that are full-screen but using insets to layout inside
21033         * of the screen decorations, these are the current insets for the
21034         * content of the window.
21035         */
21036        final Rect mContentInsets = new Rect();
21037
21038        /**
21039         * For windows that are full-screen but using insets to layout inside
21040         * of the screen decorations, these are the current insets for the
21041         * actual visible parts of the window.
21042         */
21043        final Rect mVisibleInsets = new Rect();
21044
21045        /**
21046         * For windows that are full-screen but using insets to layout inside
21047         * of the screen decorations, these are the current insets for the
21048         * stable system windows.
21049         */
21050        final Rect mStableInsets = new Rect();
21051
21052        /**
21053         * The internal insets given by this window.  This value is
21054         * supplied by the client (through
21055         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21056         * be given to the window manager when changed to be used in laying
21057         * out windows behind it.
21058         */
21059        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21060                = new ViewTreeObserver.InternalInsetsInfo();
21061
21062        /**
21063         * Set to true when mGivenInternalInsets is non-empty.
21064         */
21065        boolean mHasNonEmptyGivenInternalInsets;
21066
21067        /**
21068         * All views in the window's hierarchy that serve as scroll containers,
21069         * used to determine if the window can be resized or must be panned
21070         * to adjust for a soft input area.
21071         */
21072        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21073
21074        final KeyEvent.DispatcherState mKeyDispatchState
21075                = new KeyEvent.DispatcherState();
21076
21077        /**
21078         * Indicates whether the view's window currently has the focus.
21079         */
21080        boolean mHasWindowFocus;
21081
21082        /**
21083         * The current visibility of the window.
21084         */
21085        int mWindowVisibility;
21086
21087        /**
21088         * Indicates the time at which drawing started to occur.
21089         */
21090        long mDrawingTime;
21091
21092        /**
21093         * Indicates whether or not ignoring the DIRTY_MASK flags.
21094         */
21095        boolean mIgnoreDirtyState;
21096
21097        /**
21098         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21099         * to avoid clearing that flag prematurely.
21100         */
21101        boolean mSetIgnoreDirtyState = false;
21102
21103        /**
21104         * Indicates whether the view's window is currently in touch mode.
21105         */
21106        boolean mInTouchMode;
21107
21108        /**
21109         * Indicates whether the view has requested unbuffered input dispatching for the current
21110         * event stream.
21111         */
21112        boolean mUnbufferedDispatchRequested;
21113
21114        /**
21115         * Indicates that ViewAncestor should trigger a global layout change
21116         * the next time it performs a traversal
21117         */
21118        boolean mRecomputeGlobalAttributes;
21119
21120        /**
21121         * Always report new attributes at next traversal.
21122         */
21123        boolean mForceReportNewAttributes;
21124
21125        /**
21126         * Set during a traveral if any views want to keep the screen on.
21127         */
21128        boolean mKeepScreenOn;
21129
21130        /**
21131         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21132         */
21133        int mSystemUiVisibility;
21134
21135        /**
21136         * Hack to force certain system UI visibility flags to be cleared.
21137         */
21138        int mDisabledSystemUiVisibility;
21139
21140        /**
21141         * Last global system UI visibility reported by the window manager.
21142         */
21143        int mGlobalSystemUiVisibility;
21144
21145        /**
21146         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21147         * attached.
21148         */
21149        boolean mHasSystemUiListeners;
21150
21151        /**
21152         * Set if the window has requested to extend into the overscan region
21153         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21154         */
21155        boolean mOverscanRequested;
21156
21157        /**
21158         * Set if the visibility of any views has changed.
21159         */
21160        boolean mViewVisibilityChanged;
21161
21162        /**
21163         * Set to true if a view has been scrolled.
21164         */
21165        boolean mViewScrollChanged;
21166
21167        /**
21168         * Set to true if high contrast mode enabled
21169         */
21170        boolean mHighContrastText;
21171
21172        /**
21173         * Global to the view hierarchy used as a temporary for dealing with
21174         * x/y points in the transparent region computations.
21175         */
21176        final int[] mTransparentLocation = new int[2];
21177
21178        /**
21179         * Global to the view hierarchy used as a temporary for dealing with
21180         * x/y points in the ViewGroup.invalidateChild implementation.
21181         */
21182        final int[] mInvalidateChildLocation = new int[2];
21183
21184        /**
21185         * Global to the view hierarchy used as a temporary for dealng with
21186         * computing absolute on-screen location.
21187         */
21188        final int[] mTmpLocation = new int[2];
21189
21190        /**
21191         * Global to the view hierarchy used as a temporary for dealing with
21192         * x/y location when view is transformed.
21193         */
21194        final float[] mTmpTransformLocation = new float[2];
21195
21196        /**
21197         * The view tree observer used to dispatch global events like
21198         * layout, pre-draw, touch mode change, etc.
21199         */
21200        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21201
21202        /**
21203         * A Canvas used by the view hierarchy to perform bitmap caching.
21204         */
21205        Canvas mCanvas;
21206
21207        /**
21208         * The view root impl.
21209         */
21210        final ViewRootImpl mViewRootImpl;
21211
21212        /**
21213         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21214         * handler can be used to pump events in the UI events queue.
21215         */
21216        final Handler mHandler;
21217
21218        /**
21219         * Temporary for use in computing invalidate rectangles while
21220         * calling up the hierarchy.
21221         */
21222        final Rect mTmpInvalRect = new Rect();
21223
21224        /**
21225         * Temporary for use in computing hit areas with transformed views
21226         */
21227        final RectF mTmpTransformRect = new RectF();
21228
21229        /**
21230         * Temporary for use in computing hit areas with transformed views
21231         */
21232        final RectF mTmpTransformRect1 = new RectF();
21233
21234        /**
21235         * Temporary list of rectanges.
21236         */
21237        final List<RectF> mTmpRectList = new ArrayList<>();
21238
21239        /**
21240         * Temporary for use in transforming invalidation rect
21241         */
21242        final Matrix mTmpMatrix = new Matrix();
21243
21244        /**
21245         * Temporary for use in transforming invalidation rect
21246         */
21247        final Transformation mTmpTransformation = new Transformation();
21248
21249        /**
21250         * Temporary for use in querying outlines from OutlineProviders
21251         */
21252        final Outline mTmpOutline = new Outline();
21253
21254        /**
21255         * Temporary list for use in collecting focusable descendents of a view.
21256         */
21257        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21258
21259        /**
21260         * The id of the window for accessibility purposes.
21261         */
21262        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21263
21264        /**
21265         * Flags related to accessibility processing.
21266         *
21267         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21268         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21269         */
21270        int mAccessibilityFetchFlags;
21271
21272        /**
21273         * The drawable for highlighting accessibility focus.
21274         */
21275        Drawable mAccessibilityFocusDrawable;
21276
21277        /**
21278         * Show where the margins, bounds and layout bounds are for each view.
21279         */
21280        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21281
21282        /**
21283         * Point used to compute visible regions.
21284         */
21285        final Point mPoint = new Point();
21286
21287        /**
21288         * Used to track which View originated a requestLayout() call, used when
21289         * requestLayout() is called during layout.
21290         */
21291        View mViewRequestingLayout;
21292
21293        /**
21294         * Creates a new set of attachment information with the specified
21295         * events handler and thread.
21296         *
21297         * @param handler the events handler the view must use
21298         */
21299        AttachInfo(IWindowSession session, IWindow window, Display display,
21300                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21301            mSession = session;
21302            mWindow = window;
21303            mWindowToken = window.asBinder();
21304            mDisplay = display;
21305            mViewRootImpl = viewRootImpl;
21306            mHandler = handler;
21307            mRootCallbacks = effectPlayer;
21308        }
21309    }
21310
21311    /**
21312     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21313     * is supported. This avoids keeping too many unused fields in most
21314     * instances of View.</p>
21315     */
21316    private static class ScrollabilityCache implements Runnable {
21317
21318        /**
21319         * Scrollbars are not visible
21320         */
21321        public static final int OFF = 0;
21322
21323        /**
21324         * Scrollbars are visible
21325         */
21326        public static final int ON = 1;
21327
21328        /**
21329         * Scrollbars are fading away
21330         */
21331        public static final int FADING = 2;
21332
21333        public boolean fadeScrollBars;
21334
21335        public int fadingEdgeLength;
21336        public int scrollBarDefaultDelayBeforeFade;
21337        public int scrollBarFadeDuration;
21338
21339        public int scrollBarSize;
21340        public ScrollBarDrawable scrollBar;
21341        public float[] interpolatorValues;
21342        public View host;
21343
21344        public final Paint paint;
21345        public final Matrix matrix;
21346        public Shader shader;
21347
21348        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21349
21350        private static final float[] OPAQUE = { 255 };
21351        private static final float[] TRANSPARENT = { 0.0f };
21352
21353        /**
21354         * When fading should start. This time moves into the future every time
21355         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21356         */
21357        public long fadeStartTime;
21358
21359
21360        /**
21361         * The current state of the scrollbars: ON, OFF, or FADING
21362         */
21363        public int state = OFF;
21364
21365        private int mLastColor;
21366
21367        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21368            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21369            scrollBarSize = configuration.getScaledScrollBarSize();
21370            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21371            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21372
21373            paint = new Paint();
21374            matrix = new Matrix();
21375            // use use a height of 1, and then wack the matrix each time we
21376            // actually use it.
21377            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21378            paint.setShader(shader);
21379            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21380
21381            this.host = host;
21382        }
21383
21384        public void setFadeColor(int color) {
21385            if (color != mLastColor) {
21386                mLastColor = color;
21387
21388                if (color != 0) {
21389                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21390                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21391                    paint.setShader(shader);
21392                    // Restore the default transfer mode (src_over)
21393                    paint.setXfermode(null);
21394                } else {
21395                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21396                    paint.setShader(shader);
21397                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21398                }
21399            }
21400        }
21401
21402        public void run() {
21403            long now = AnimationUtils.currentAnimationTimeMillis();
21404            if (now >= fadeStartTime) {
21405
21406                // the animation fades the scrollbars out by changing
21407                // the opacity (alpha) from fully opaque to fully
21408                // transparent
21409                int nextFrame = (int) now;
21410                int framesCount = 0;
21411
21412                Interpolator interpolator = scrollBarInterpolator;
21413
21414                // Start opaque
21415                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21416
21417                // End transparent
21418                nextFrame += scrollBarFadeDuration;
21419                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21420
21421                state = FADING;
21422
21423                // Kick off the fade animation
21424                host.invalidate(true);
21425            }
21426        }
21427    }
21428
21429    /**
21430     * Resuable callback for sending
21431     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
21432     */
21433    private class SendViewScrolledAccessibilityEvent implements Runnable {
21434        public volatile boolean mIsPending;
21435
21436        public void run() {
21437            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
21438            mIsPending = false;
21439        }
21440    }
21441
21442    /**
21443     * <p>
21444     * This class represents a delegate that can be registered in a {@link View}
21445     * to enhance accessibility support via composition rather via inheritance.
21446     * It is specifically targeted to widget developers that extend basic View
21447     * classes i.e. classes in package android.view, that would like their
21448     * applications to be backwards compatible.
21449     * </p>
21450     * <div class="special reference">
21451     * <h3>Developer Guides</h3>
21452     * <p>For more information about making applications accessible, read the
21453     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
21454     * developer guide.</p>
21455     * </div>
21456     * <p>
21457     * A scenario in which a developer would like to use an accessibility delegate
21458     * is overriding a method introduced in a later API version then the minimal API
21459     * version supported by the application. For example, the method
21460     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
21461     * in API version 4 when the accessibility APIs were first introduced. If a
21462     * developer would like his application to run on API version 4 devices (assuming
21463     * all other APIs used by the application are version 4 or lower) and take advantage
21464     * of this method, instead of overriding the method which would break the application's
21465     * backwards compatibility, he can override the corresponding method in this
21466     * delegate and register the delegate in the target View if the API version of
21467     * the system is high enough i.e. the API version is same or higher to the API
21468     * version that introduced
21469     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
21470     * </p>
21471     * <p>
21472     * Here is an example implementation:
21473     * </p>
21474     * <code><pre><p>
21475     * if (Build.VERSION.SDK_INT >= 14) {
21476     *     // If the API version is equal of higher than the version in
21477     *     // which onInitializeAccessibilityNodeInfo was introduced we
21478     *     // register a delegate with a customized implementation.
21479     *     View view = findViewById(R.id.view_id);
21480     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
21481     *         public void onInitializeAccessibilityNodeInfo(View host,
21482     *                 AccessibilityNodeInfo info) {
21483     *             // Let the default implementation populate the info.
21484     *             super.onInitializeAccessibilityNodeInfo(host, info);
21485     *             // Set some other information.
21486     *             info.setEnabled(host.isEnabled());
21487     *         }
21488     *     });
21489     * }
21490     * </code></pre></p>
21491     * <p>
21492     * This delegate contains methods that correspond to the accessibility methods
21493     * in View. If a delegate has been specified the implementation in View hands
21494     * off handling to the corresponding method in this delegate. The default
21495     * implementation the delegate methods behaves exactly as the corresponding
21496     * method in View for the case of no accessibility delegate been set. Hence,
21497     * to customize the behavior of a View method, clients can override only the
21498     * corresponding delegate method without altering the behavior of the rest
21499     * accessibility related methods of the host view.
21500     * </p>
21501     */
21502    public static class AccessibilityDelegate {
21503
21504        /**
21505         * Sends an accessibility event of the given type. If accessibility is not
21506         * enabled this method has no effect.
21507         * <p>
21508         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
21509         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
21510         * been set.
21511         * </p>
21512         *
21513         * @param host The View hosting the delegate.
21514         * @param eventType The type of the event to send.
21515         *
21516         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
21517         */
21518        public void sendAccessibilityEvent(View host, int eventType) {
21519            host.sendAccessibilityEventInternal(eventType);
21520        }
21521
21522        /**
21523         * Performs the specified accessibility action on the view. For
21524         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
21525         * <p>
21526         * The default implementation behaves as
21527         * {@link View#performAccessibilityAction(int, Bundle)
21528         *  View#performAccessibilityAction(int, Bundle)} for the case of
21529         *  no accessibility delegate been set.
21530         * </p>
21531         *
21532         * @param action The action to perform.
21533         * @return Whether the action was performed.
21534         *
21535         * @see View#performAccessibilityAction(int, Bundle)
21536         *      View#performAccessibilityAction(int, Bundle)
21537         */
21538        public boolean performAccessibilityAction(View host, int action, Bundle args) {
21539            return host.performAccessibilityActionInternal(action, args);
21540        }
21541
21542        /**
21543         * Sends an accessibility event. This method behaves exactly as
21544         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
21545         * empty {@link AccessibilityEvent} and does not perform a check whether
21546         * accessibility is enabled.
21547         * <p>
21548         * The default implementation behaves as
21549         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21550         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
21551         * the case of no accessibility delegate been set.
21552         * </p>
21553         *
21554         * @param host The View hosting the delegate.
21555         * @param event The event to send.
21556         *
21557         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21558         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21559         */
21560        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
21561            host.sendAccessibilityEventUncheckedInternal(event);
21562        }
21563
21564        /**
21565         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
21566         * to its children for adding their text content to the event.
21567         * <p>
21568         * The default implementation behaves as
21569         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21570         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
21571         * the case of no accessibility delegate been set.
21572         * </p>
21573         *
21574         * @param host The View hosting the delegate.
21575         * @param event The event.
21576         * @return True if the event population was completed.
21577         *
21578         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21579         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21580         */
21581        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21582            return host.dispatchPopulateAccessibilityEventInternal(event);
21583        }
21584
21585        /**
21586         * Gives a chance to the host View to populate the accessibility event with its
21587         * text content.
21588         * <p>
21589         * The default implementation behaves as
21590         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
21591         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
21592         * the case of no accessibility delegate been set.
21593         * </p>
21594         *
21595         * @param host The View hosting the delegate.
21596         * @param event The accessibility event which to populate.
21597         *
21598         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
21599         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
21600         */
21601        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21602            host.onPopulateAccessibilityEventInternal(event);
21603        }
21604
21605        /**
21606         * Initializes an {@link AccessibilityEvent} with information about the
21607         * the host View which is the event source.
21608         * <p>
21609         * The default implementation behaves as
21610         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
21611         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
21612         * the case of no accessibility delegate been set.
21613         * </p>
21614         *
21615         * @param host The View hosting the delegate.
21616         * @param event The event to initialize.
21617         *
21618         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
21619         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
21620         */
21621        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
21622            host.onInitializeAccessibilityEventInternal(event);
21623        }
21624
21625        /**
21626         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
21627         * <p>
21628         * The default implementation behaves as
21629         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21630         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
21631         * the case of no accessibility delegate been set.
21632         * </p>
21633         *
21634         * @param host The View hosting the delegate.
21635         * @param info The instance to initialize.
21636         *
21637         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21638         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21639         */
21640        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21641            host.onInitializeAccessibilityNodeInfoInternal(info);
21642        }
21643
21644        /**
21645         * Called when a child of the host View has requested sending an
21646         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21647         * to augment the event.
21648         * <p>
21649         * The default implementation behaves as
21650         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21651         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21652         * the case of no accessibility delegate been set.
21653         * </p>
21654         *
21655         * @param host The View hosting the delegate.
21656         * @param child The child which requests sending the event.
21657         * @param event The event to be sent.
21658         * @return True if the event should be sent
21659         *
21660         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21661         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21662         */
21663        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21664                AccessibilityEvent event) {
21665            return host.onRequestSendAccessibilityEventInternal(child, event);
21666        }
21667
21668        /**
21669         * Gets the provider for managing a virtual view hierarchy rooted at this View
21670         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21671         * that explore the window content.
21672         * <p>
21673         * The default implementation behaves as
21674         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21675         * the case of no accessibility delegate been set.
21676         * </p>
21677         *
21678         * @return The provider.
21679         *
21680         * @see AccessibilityNodeProvider
21681         */
21682        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21683            return null;
21684        }
21685
21686        /**
21687         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21688         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21689         * This method is responsible for obtaining an accessibility node info from a
21690         * pool of reusable instances and calling
21691         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21692         * view to initialize the former.
21693         * <p>
21694         * <strong>Note:</strong> The client is responsible for recycling the obtained
21695         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21696         * creation.
21697         * </p>
21698         * <p>
21699         * The default implementation behaves as
21700         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21701         * the case of no accessibility delegate been set.
21702         * </p>
21703         * @return A populated {@link AccessibilityNodeInfo}.
21704         *
21705         * @see AccessibilityNodeInfo
21706         *
21707         * @hide
21708         */
21709        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21710            return host.createAccessibilityNodeInfoInternal();
21711        }
21712    }
21713
21714    private class MatchIdPredicate implements Predicate<View> {
21715        public int mId;
21716
21717        @Override
21718        public boolean apply(View view) {
21719            return (view.mID == mId);
21720        }
21721    }
21722
21723    private class MatchLabelForPredicate implements Predicate<View> {
21724        private int mLabeledId;
21725
21726        @Override
21727        public boolean apply(View view) {
21728            return (view.mLabelForId == mLabeledId);
21729        }
21730    }
21731
21732    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21733        private int mChangeTypes = 0;
21734        private boolean mPosted;
21735        private boolean mPostedWithDelay;
21736        private long mLastEventTimeMillis;
21737
21738        @Override
21739        public void run() {
21740            mPosted = false;
21741            mPostedWithDelay = false;
21742            mLastEventTimeMillis = SystemClock.uptimeMillis();
21743            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21744                final AccessibilityEvent event = AccessibilityEvent.obtain();
21745                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21746                event.setContentChangeTypes(mChangeTypes);
21747                sendAccessibilityEventUnchecked(event);
21748            }
21749            mChangeTypes = 0;
21750        }
21751
21752        public void runOrPost(int changeType) {
21753            mChangeTypes |= changeType;
21754
21755            // If this is a live region or the child of a live region, collect
21756            // all events from this frame and send them on the next frame.
21757            if (inLiveRegion()) {
21758                // If we're already posted with a delay, remove that.
21759                if (mPostedWithDelay) {
21760                    removeCallbacks(this);
21761                    mPostedWithDelay = false;
21762                }
21763                // Only post if we're not already posted.
21764                if (!mPosted) {
21765                    post(this);
21766                    mPosted = true;
21767                }
21768                return;
21769            }
21770
21771            if (mPosted) {
21772                return;
21773            }
21774
21775            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21776            final long minEventIntevalMillis =
21777                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21778            if (timeSinceLastMillis >= minEventIntevalMillis) {
21779                removeCallbacks(this);
21780                run();
21781            } else {
21782                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21783                mPostedWithDelay = true;
21784            }
21785        }
21786    }
21787
21788    private boolean inLiveRegion() {
21789        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21790            return true;
21791        }
21792
21793        ViewParent parent = getParent();
21794        while (parent instanceof View) {
21795            if (((View) parent).getAccessibilityLiveRegion()
21796                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21797                return true;
21798            }
21799            parent = parent.getParent();
21800        }
21801
21802        return false;
21803    }
21804
21805    /**
21806     * Dump all private flags in readable format, useful for documentation and
21807     * sanity checking.
21808     */
21809    private static void dumpFlags() {
21810        final HashMap<String, String> found = Maps.newHashMap();
21811        try {
21812            for (Field field : View.class.getDeclaredFields()) {
21813                final int modifiers = field.getModifiers();
21814                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21815                    if (field.getType().equals(int.class)) {
21816                        final int value = field.getInt(null);
21817                        dumpFlag(found, field.getName(), value);
21818                    } else if (field.getType().equals(int[].class)) {
21819                        final int[] values = (int[]) field.get(null);
21820                        for (int i = 0; i < values.length; i++) {
21821                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21822                        }
21823                    }
21824                }
21825            }
21826        } catch (IllegalAccessException e) {
21827            throw new RuntimeException(e);
21828        }
21829
21830        final ArrayList<String> keys = Lists.newArrayList();
21831        keys.addAll(found.keySet());
21832        Collections.sort(keys);
21833        for (String key : keys) {
21834            Log.d(VIEW_LOG_TAG, found.get(key));
21835        }
21836    }
21837
21838    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21839        // Sort flags by prefix, then by bits, always keeping unique keys
21840        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21841        final int prefix = name.indexOf('_');
21842        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21843        final String output = bits + " " + name;
21844        found.put(key, output);
21845    }
21846}
21847