View.java revision 2b45a16b8b0f46090c0e612ef8a3d6084997fc27
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.RevealAnimator;
21import android.animation.StateListAnimator;
22import android.animation.ValueAnimator;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.content.ClipData;
27import android.content.Context;
28import android.content.res.ColorStateList;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.content.res.TypedArray;
32import android.graphics.Bitmap;
33import android.graphics.Canvas;
34import android.graphics.Insets;
35import android.graphics.Interpolator;
36import android.graphics.LinearGradient;
37import android.graphics.Matrix;
38import android.graphics.Outline;
39import android.graphics.Paint;
40import android.graphics.PixelFormat;
41import android.graphics.Point;
42import android.graphics.PorterDuff;
43import android.graphics.PorterDuffXfermode;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.ColorDrawable;
49import android.graphics.drawable.Drawable;
50import android.hardware.display.DisplayManagerGlobal;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.RemoteException;
57import android.os.SystemClock;
58import android.os.SystemProperties;
59import android.text.TextUtils;
60import android.util.AttributeSet;
61import android.util.FloatProperty;
62import android.util.LayoutDirection;
63import android.util.Log;
64import android.util.LongSparseLongArray;
65import android.util.Pools.SynchronizedPool;
66import android.util.Property;
67import android.util.SparseArray;
68import android.util.SuperNotCalledException;
69import android.util.TypedValue;
70import android.view.ContextMenu.ContextMenuInfo;
71import android.view.AccessibilityIterators.TextSegmentIterator;
72import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
73import android.view.AccessibilityIterators.WordTextSegmentIterator;
74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
75import android.view.accessibility.AccessibilityEvent;
76import android.view.accessibility.AccessibilityEventSource;
77import android.view.accessibility.AccessibilityManager;
78import android.view.accessibility.AccessibilityNodeInfo;
79import android.view.accessibility.AccessibilityNodeProvider;
80import android.view.animation.Animation;
81import android.view.animation.AnimationUtils;
82import android.view.animation.Transformation;
83import android.view.inputmethod.EditorInfo;
84import android.view.inputmethod.InputConnection;
85import android.view.inputmethod.InputMethodManager;
86import android.widget.ScrollBarDrawable;
87
88import static android.os.Build.VERSION_CODES.*;
89import static java.lang.Math.max;
90
91import com.android.internal.R;
92import com.android.internal.util.Predicate;
93import com.android.internal.view.menu.MenuBuilder;
94
95import com.google.android.collect.Lists;
96import com.google.android.collect.Maps;
97
98import java.lang.annotation.Retention;
99import java.lang.annotation.RetentionPolicy;
100import java.lang.ref.WeakReference;
101import java.lang.reflect.Field;
102import java.lang.reflect.InvocationTargetException;
103import java.lang.reflect.Method;
104import java.lang.reflect.Modifier;
105import java.util.ArrayList;
106import java.util.Arrays;
107import java.util.Collections;
108import java.util.HashMap;
109import java.util.List;
110import java.util.Locale;
111import java.util.Map;
112import java.util.concurrent.CopyOnWriteArrayList;
113import java.util.concurrent.atomic.AtomicInteger;
114
115/**
116 * <p>
117 * This class represents the basic building block for user interface components. A View
118 * occupies a rectangular area on the screen and is responsible for drawing and
119 * event handling. View is the base class for <em>widgets</em>, which are
120 * used to create interactive UI components (buttons, text fields, etc.). The
121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
122 * are invisible containers that hold other Views (or other ViewGroups) and define
123 * their layout properties.
124 * </p>
125 *
126 * <div class="special reference">
127 * <h3>Developer Guides</h3>
128 * <p>For information about using this class to develop your application's user interface,
129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
130 * </div>
131 *
132 * <a name="Using"></a>
133 * <h3>Using Views</h3>
134 * <p>
135 * All of the views in a window are arranged in a single tree. You can add views
136 * either from code or by specifying a tree of views in one or more XML layout
137 * files. There are many specialized subclasses of views that act as controls or
138 * are capable of displaying text, images, or other content.
139 * </p>
140 * <p>
141 * Once you have created a tree of views, there are typically a few types of
142 * common operations you may wish to perform:
143 * <ul>
144 * <li><strong>Set properties:</strong> for example setting the text of a
145 * {@link android.widget.TextView}. The available properties and the methods
146 * that set them will vary among the different subclasses of views. Note that
147 * properties that are known at build time can be set in the XML layout
148 * files.</li>
149 * <li><strong>Set focus:</strong> The framework will handled moving focus in
150 * response to user input. To force focus to a specific view, call
151 * {@link #requestFocus}.</li>
152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
153 * that will be notified when something interesting happens to the view. For
154 * example, all views will let you set a listener to be notified when the view
155 * gains or loses focus. You can register such a listener using
156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
157 * Other view subclasses offer more specialized listeners. For example, a Button
158 * exposes a listener to notify clients when the button is clicked.</li>
159 * <li><strong>Set visibility:</strong> You can hide or show views using
160 * {@link #setVisibility(int)}.</li>
161 * </ul>
162 * </p>
163 * <p><em>
164 * Note: The Android framework is responsible for measuring, laying out and
165 * drawing views. You should not call methods that perform these actions on
166 * views yourself unless you are actually implementing a
167 * {@link android.view.ViewGroup}.
168 * </em></p>
169 *
170 * <a name="Lifecycle"></a>
171 * <h3>Implementing a Custom View</h3>
172 *
173 * <p>
174 * To implement a custom view, you will usually begin by providing overrides for
175 * some of the standard methods that the framework calls on all views. You do
176 * not need to override all of these methods. In fact, you can start by just
177 * overriding {@link #onDraw(android.graphics.Canvas)}.
178 * <table border="2" width="85%" align="center" cellpadding="5">
179 *     <thead>
180 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
181 *     </thead>
182 *
183 *     <tbody>
184 *     <tr>
185 *         <td rowspan="2">Creation</td>
186 *         <td>Constructors</td>
187 *         <td>There is a form of the constructor that are called when the view
188 *         is created from code and a form that is called when the view is
189 *         inflated from a layout file. The second form should parse and apply
190 *         any attributes defined in the layout file.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onFinishInflate()}</code></td>
195 *         <td>Called after a view and all of its children has been inflated
196 *         from XML.</td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td rowspan="3">Layout</td>
201 *         <td><code>{@link #onMeasure(int, int)}</code></td>
202 *         <td>Called to determine the size requirements for this view and all
203 *         of its children.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
208 *         <td>Called when this view should assign a size and position to all
209 *         of its children.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
214 *         <td>Called when the size of this view has changed.
215 *         </td>
216 *     </tr>
217 *
218 *     <tr>
219 *         <td>Drawing</td>
220 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
221 *         <td>Called when the view should render its content.
222 *         </td>
223 *     </tr>
224 *
225 *     <tr>
226 *         <td rowspan="4">Event processing</td>
227 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
228 *         <td>Called when a new hardware key event occurs.
229 *         </td>
230 *     </tr>
231 *     <tr>
232 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
233 *         <td>Called when a hardware key up event occurs.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
238 *         <td>Called when a trackball motion event occurs.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
243 *         <td>Called when a touch screen motion event occurs.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="2">Focus</td>
249 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
250 *         <td>Called when the view gains or loses focus.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
256 *         <td>Called when the window containing the view gains or loses focus.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td rowspan="3">Attaching</td>
262 *         <td><code>{@link #onAttachedToWindow()}</code></td>
263 *         <td>Called when the view is attached to a window.
264 *         </td>
265 *     </tr>
266 *
267 *     <tr>
268 *         <td><code>{@link #onDetachedFromWindow}</code></td>
269 *         <td>Called when the view is detached from its window.
270 *         </td>
271 *     </tr>
272 *
273 *     <tr>
274 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
275 *         <td>Called when the visibility of the window containing the view
276 *         has changed.
277 *         </td>
278 *     </tr>
279 *     </tbody>
280 *
281 * </table>
282 * </p>
283 *
284 * <a name="IDs"></a>
285 * <h3>IDs</h3>
286 * Views may have an integer id associated with them. These ids are typically
287 * assigned in the layout XML files, and are used to find specific views within
288 * the view tree. A common pattern is to:
289 * <ul>
290 * <li>Define a Button in the layout file and assign it a unique ID.
291 * <pre>
292 * &lt;Button
293 *     android:id="@+id/my_button"
294 *     android:layout_width="wrap_content"
295 *     android:layout_height="wrap_content"
296 *     android:text="@string/my_button_text"/&gt;
297 * </pre></li>
298 * <li>From the onCreate method of an Activity, find the Button
299 * <pre class="prettyprint">
300 *      Button myButton = (Button) findViewById(R.id.my_button);
301 * </pre></li>
302 * </ul>
303 * <p>
304 * View IDs need not be unique throughout the tree, but it is good practice to
305 * ensure that they are at least unique within the part of the tree you are
306 * searching.
307 * </p>
308 *
309 * <a name="Position"></a>
310 * <h3>Position</h3>
311 * <p>
312 * The geometry of a view is that of a rectangle. A view has a location,
313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
314 * two dimensions, expressed as a width and a height. The unit for location
315 * and dimensions is the pixel.
316 * </p>
317 *
318 * <p>
319 * It is possible to retrieve the location of a view by invoking the methods
320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
321 * coordinate of the rectangle representing the view. The latter returns the
322 * top, or Y, coordinate of the rectangle representing the view. These methods
323 * both return the location of the view relative to its parent. For instance,
324 * when getLeft() returns 20, that means the view is located 20 pixels to the
325 * right of the left edge of its direct parent.
326 * </p>
327 *
328 * <p>
329 * In addition, several convenience methods are offered to avoid unnecessary
330 * computations, namely {@link #getRight()} and {@link #getBottom()}.
331 * These methods return the coordinates of the right and bottom edges of the
332 * rectangle representing the view. For instance, calling {@link #getRight()}
333 * is similar to the following computation: <code>getLeft() + getWidth()</code>
334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
335 * </p>
336 *
337 * <a name="SizePaddingMargins"></a>
338 * <h3>Size, padding and margins</h3>
339 * <p>
340 * The size of a view is expressed with a width and a height. A view actually
341 * possess two pairs of width and height values.
342 * </p>
343 *
344 * <p>
345 * The first pair is known as <em>measured width</em> and
346 * <em>measured height</em>. These dimensions define how big a view wants to be
347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
349 * and {@link #getMeasuredHeight()}.
350 * </p>
351 *
352 * <p>
353 * The second pair is simply known as <em>width</em> and <em>height</em>, or
354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
355 * dimensions define the actual size of the view on screen, at drawing time and
356 * after layout. These values may, but do not have to, be different from the
357 * measured width and height. The width and height can be obtained by calling
358 * {@link #getWidth()} and {@link #getHeight()}.
359 * </p>
360 *
361 * <p>
362 * To measure its dimensions, a view takes into account its padding. The padding
363 * is expressed in pixels for the left, top, right and bottom parts of the view.
364 * Padding can be used to offset the content of the view by a specific amount of
365 * pixels. For instance, a left padding of 2 will push the view's content by
366 * 2 pixels to the right of the left edge. Padding can be set using the
367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
370 * {@link #getPaddingEnd()}.
371 * </p>
372 *
373 * <p>
374 * Even though a view can define a padding, it does not provide any support for
375 * margins. However, view groups provide such a support. Refer to
376 * {@link android.view.ViewGroup} and
377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
378 * </p>
379 *
380 * <a name="Layout"></a>
381 * <h3>Layout</h3>
382 * <p>
383 * Layout is a two pass process: a measure pass and a layout pass. The measuring
384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
385 * of the view tree. Each view pushes dimension specifications down the tree
386 * during the recursion. At the end of the measure pass, every view has stored
387 * its measurements. The second pass happens in
388 * {@link #layout(int,int,int,int)} and is also top-down. During
389 * this pass each parent is responsible for positioning all of its children
390 * using the sizes computed in the measure pass.
391 * </p>
392 *
393 * <p>
394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
395 * {@link #getMeasuredHeight()} values must be set, along with those for all of
396 * that view's descendants. A view's measured width and measured height values
397 * must respect the constraints imposed by the view's parents. This guarantees
398 * that at the end of the measure pass, all parents accept all of their
399 * children's measurements. A parent view may call measure() more than once on
400 * its children. For example, the parent may measure each child once with
401 * unspecified dimensions to find out how big they want to be, then call
402 * measure() on them again with actual numbers if the sum of all the children's
403 * unconstrained sizes is too big or too small.
404 * </p>
405 *
406 * <p>
407 * The measure pass uses two classes to communicate dimensions. The
408 * {@link MeasureSpec} class is used by views to tell their parents how they
409 * want to be measured and positioned. The base LayoutParams class just
410 * describes how big the view wants to be for both width and height. For each
411 * dimension, it can specify one of:
412 * <ul>
413 * <li> an exact number
414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
415 * (minus padding)
416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
417 * enclose its content (plus padding).
418 * </ul>
419 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
421 * an X and Y value.
422 * </p>
423 *
424 * <p>
425 * MeasureSpecs are used to push requirements down the tree from parent to
426 * child. A MeasureSpec can be in one of three modes:
427 * <ul>
428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
429 * of a child view. For example, a LinearLayout may call measure() on its child
430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
431 * tall the child view wants to be given a width of 240 pixels.
432 * <li>EXACTLY: This is used by the parent to impose an exact size on the
433 * child. The child must use this size, and guarantee that all of its
434 * descendants will fit within this size.
435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
436 * child. The child must guarantee that it and all of its descendants will fit
437 * within this size.
438 * </ul>
439 * </p>
440 *
441 * <p>
442 * To intiate a layout, call {@link #requestLayout}. This method is typically
443 * called by a view on itself when it believes that is can no longer fit within
444 * its current bounds.
445 * </p>
446 *
447 * <a name="Drawing"></a>
448 * <h3>Drawing</h3>
449 * <p>
450 * Drawing is handled by walking the tree and rendering each view that
451 * intersects the invalid region. Because the tree is traversed in-order,
452 * this means that parents will draw before (i.e., behind) their children, with
453 * siblings drawn in the order they appear in the tree.
454 * If you set a background drawable for a View, then the View will draw it for you
455 * before calling back to its <code>onDraw()</code> method.
456 * </p>
457 *
458 * <p>
459 * Note that the framework will not draw views that are not in the invalid region.
460 * </p>
461 *
462 * <p>
463 * To force a view to draw, call {@link #invalidate()}.
464 * </p>
465 *
466 * <a name="EventHandlingThreading"></a>
467 * <h3>Event Handling and Threading</h3>
468 * <p>
469 * The basic cycle of a view is as follows:
470 * <ol>
471 * <li>An event comes in and is dispatched to the appropriate view. The view
472 * handles the event and notifies any listeners.</li>
473 * <li>If in the course of processing the event, the view's bounds may need
474 * to be changed, the view will call {@link #requestLayout()}.</li>
475 * <li>Similarly, if in the course of processing the event the view's appearance
476 * may need to be changed, the view will call {@link #invalidate()}.</li>
477 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
478 * the framework will take care of measuring, laying out, and drawing the tree
479 * as appropriate.</li>
480 * </ol>
481 * </p>
482 *
483 * <p><em>Note: The entire view tree is single threaded. You must always be on
484 * the UI thread when calling any method on any view.</em>
485 * If you are doing work on other threads and want to update the state of a view
486 * from that thread, you should use a {@link Handler}.
487 * </p>
488 *
489 * <a name="FocusHandling"></a>
490 * <h3>Focus Handling</h3>
491 * <p>
492 * The framework will handle routine focus movement in response to user input.
493 * This includes changing the focus as views are removed or hidden, or as new
494 * views become available. Views indicate their willingness to take focus
495 * through the {@link #isFocusable} method. To change whether a view can take
496 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
497 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
498 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
499 * </p>
500 * <p>
501 * Focus movement is based on an algorithm which finds the nearest neighbor in a
502 * given direction. In rare cases, the default algorithm may not match the
503 * intended behavior of the developer. In these situations, you can provide
504 * explicit overrides by using these XML attributes in the layout file:
505 * <pre>
506 * nextFocusDown
507 * nextFocusLeft
508 * nextFocusRight
509 * nextFocusUp
510 * </pre>
511 * </p>
512 *
513 *
514 * <p>
515 * To get a particular view to take focus, call {@link #requestFocus()}.
516 * </p>
517 *
518 * <a name="TouchMode"></a>
519 * <h3>Touch Mode</h3>
520 * <p>
521 * When a user is navigating a user interface via directional keys such as a D-pad, it is
522 * necessary to give focus to actionable items such as buttons so the user can see
523 * what will take input.  If the device has touch capabilities, however, and the user
524 * begins interacting with the interface by touching it, it is no longer necessary to
525 * always highlight, or give focus to, a particular view.  This motivates a mode
526 * for interaction named 'touch mode'.
527 * </p>
528 * <p>
529 * For a touch capable device, once the user touches the screen, the device
530 * will enter touch mode.  From this point onward, only views for which
531 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
532 * Other views that are touchable, like buttons, will not take focus when touched; they will
533 * only fire the on click listeners.
534 * </p>
535 * <p>
536 * Any time a user hits a directional key, such as a D-pad direction, the view device will
537 * exit touch mode, and find a view to take focus, so that the user may resume interacting
538 * with the user interface without touching the screen again.
539 * </p>
540 * <p>
541 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
542 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
543 * </p>
544 *
545 * <a name="Scrolling"></a>
546 * <h3>Scrolling</h3>
547 * <p>
548 * The framework provides basic support for views that wish to internally
549 * scroll their content. This includes keeping track of the X and Y scroll
550 * offset as well as mechanisms for drawing scrollbars. See
551 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
552 * {@link #awakenScrollBars()} for more details.
553 * </p>
554 *
555 * <a name="Tags"></a>
556 * <h3>Tags</h3>
557 * <p>
558 * Unlike IDs, tags are not used to identify views. Tags are essentially an
559 * extra piece of information that can be associated with a view. They are most
560 * often used as a convenience to store data related to views in the views
561 * themselves rather than by putting them in a separate structure.
562 * </p>
563 *
564 * <a name="Properties"></a>
565 * <h3>Properties</h3>
566 * <p>
567 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
568 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
569 * available both in the {@link Property} form as well as in similarly-named setter/getter
570 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
571 * be used to set persistent state associated with these rendering-related properties on the view.
572 * The properties and methods can also be used in conjunction with
573 * {@link android.animation.Animator Animator}-based animations, described more in the
574 * <a href="#Animation">Animation</a> section.
575 * </p>
576 *
577 * <a name="Animation"></a>
578 * <h3>Animation</h3>
579 * <p>
580 * Starting with Android 3.0, the preferred way of animating views is to use the
581 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
582 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
583 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
584 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
585 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
586 * makes animating these View properties particularly easy and efficient.
587 * </p>
588 * <p>
589 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
590 * You can attach an {@link Animation} object to a view using
591 * {@link #setAnimation(Animation)} or
592 * {@link #startAnimation(Animation)}. The animation can alter the scale,
593 * rotation, translation and alpha of a view over time. If the animation is
594 * attached to a view that has children, the animation will affect the entire
595 * subtree rooted by that node. When an animation is started, the framework will
596 * take care of redrawing the appropriate views until the animation completes.
597 * </p>
598 *
599 * <a name="Security"></a>
600 * <h3>Security</h3>
601 * <p>
602 * Sometimes it is essential that an application be able to verify that an action
603 * is being performed with the full knowledge and consent of the user, such as
604 * granting a permission request, making a purchase or clicking on an advertisement.
605 * Unfortunately, a malicious application could try to spoof the user into
606 * performing these actions, unaware, by concealing the intended purpose of the view.
607 * As a remedy, the framework offers a touch filtering mechanism that can be used to
608 * improve the security of views that provide access to sensitive functionality.
609 * </p><p>
610 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
611 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
612 * will discard touches that are received whenever the view's window is obscured by
613 * another visible window.  As a result, the view will not receive touches whenever a
614 * toast, dialog or other window appears above the view's window.
615 * </p><p>
616 * For more fine-grained control over security, consider overriding the
617 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
618 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
619 * </p>
620 *
621 * @attr ref android.R.styleable#View_alpha
622 * @attr ref android.R.styleable#View_background
623 * @attr ref android.R.styleable#View_clickable
624 * @attr ref android.R.styleable#View_contentDescription
625 * @attr ref android.R.styleable#View_drawingCacheQuality
626 * @attr ref android.R.styleable#View_duplicateParentState
627 * @attr ref android.R.styleable#View_id
628 * @attr ref android.R.styleable#View_requiresFadingEdge
629 * @attr ref android.R.styleable#View_fadeScrollbars
630 * @attr ref android.R.styleable#View_fadingEdgeLength
631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
632 * @attr ref android.R.styleable#View_fitsSystemWindows
633 * @attr ref android.R.styleable#View_isScrollContainer
634 * @attr ref android.R.styleable#View_focusable
635 * @attr ref android.R.styleable#View_focusableInTouchMode
636 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
637 * @attr ref android.R.styleable#View_keepScreenOn
638 * @attr ref android.R.styleable#View_layerType
639 * @attr ref android.R.styleable#View_layoutDirection
640 * @attr ref android.R.styleable#View_longClickable
641 * @attr ref android.R.styleable#View_minHeight
642 * @attr ref android.R.styleable#View_minWidth
643 * @attr ref android.R.styleable#View_nextFocusDown
644 * @attr ref android.R.styleable#View_nextFocusLeft
645 * @attr ref android.R.styleable#View_nextFocusRight
646 * @attr ref android.R.styleable#View_nextFocusUp
647 * @attr ref android.R.styleable#View_onClick
648 * @attr ref android.R.styleable#View_padding
649 * @attr ref android.R.styleable#View_paddingBottom
650 * @attr ref android.R.styleable#View_paddingLeft
651 * @attr ref android.R.styleable#View_paddingRight
652 * @attr ref android.R.styleable#View_paddingTop
653 * @attr ref android.R.styleable#View_paddingStart
654 * @attr ref android.R.styleable#View_paddingEnd
655 * @attr ref android.R.styleable#View_saveEnabled
656 * @attr ref android.R.styleable#View_rotation
657 * @attr ref android.R.styleable#View_rotationX
658 * @attr ref android.R.styleable#View_rotationY
659 * @attr ref android.R.styleable#View_scaleX
660 * @attr ref android.R.styleable#View_scaleY
661 * @attr ref android.R.styleable#View_scrollX
662 * @attr ref android.R.styleable#View_scrollY
663 * @attr ref android.R.styleable#View_scrollbarSize
664 * @attr ref android.R.styleable#View_scrollbarStyle
665 * @attr ref android.R.styleable#View_scrollbars
666 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
667 * @attr ref android.R.styleable#View_scrollbarFadeDuration
668 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
669 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
670 * @attr ref android.R.styleable#View_scrollbarThumbVertical
671 * @attr ref android.R.styleable#View_scrollbarTrackVertical
672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
674 * @attr ref android.R.styleable#View_stateListAnimator
675 * @attr ref android.R.styleable#View_transitionName
676 * @attr ref android.R.styleable#View_soundEffectsEnabled
677 * @attr ref android.R.styleable#View_tag
678 * @attr ref android.R.styleable#View_textAlignment
679 * @attr ref android.R.styleable#View_textDirection
680 * @attr ref android.R.styleable#View_transformPivotX
681 * @attr ref android.R.styleable#View_transformPivotY
682 * @attr ref android.R.styleable#View_translationX
683 * @attr ref android.R.styleable#View_translationY
684 * @attr ref android.R.styleable#View_translationZ
685 * @attr ref android.R.styleable#View_visibility
686 *
687 * @see android.view.ViewGroup
688 */
689public class View implements Drawable.Callback, KeyEvent.Callback,
690        AccessibilityEventSource {
691    private static final boolean DBG = false;
692
693    /**
694     * The logging tag used by this class with android.util.Log.
695     */
696    protected static final String VIEW_LOG_TAG = "View";
697
698    /**
699     * When set to true, apps will draw debugging information about their layouts.
700     *
701     * @hide
702     */
703    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
704
705    /**
706     * Used to mark a View that has no ID.
707     */
708    public static final int NO_ID = -1;
709
710    /**
711     * Signals that compatibility booleans have been initialized according to
712     * target SDK versions.
713     */
714    private static boolean sCompatibilityDone = false;
715
716    /**
717     * Use the old (broken) way of building MeasureSpecs.
718     */
719    private static boolean sUseBrokenMakeMeasureSpec = false;
720
721    /**
722     * Ignore any optimizations using the measure cache.
723     */
724    private static boolean sIgnoreMeasureCache = false;
725
726    /**
727     * Ignore the clipBounds of this view for the children.
728     */
729    static boolean sIgnoreClipBoundsForChildren = false;
730
731    /**
732     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
733     * calling setFlags.
734     */
735    private static final int NOT_FOCUSABLE = 0x00000000;
736
737    /**
738     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
739     * setFlags.
740     */
741    private static final int FOCUSABLE = 0x00000001;
742
743    /**
744     * Mask for use with setFlags indicating bits used for focus.
745     */
746    private static final int FOCUSABLE_MASK = 0x00000001;
747
748    /**
749     * This view will adjust its padding to fit sytem windows (e.g. status bar)
750     */
751    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
752
753    /** @hide */
754    @IntDef({VISIBLE, INVISIBLE, GONE})
755    @Retention(RetentionPolicy.SOURCE)
756    public @interface Visibility {}
757
758    /**
759     * This view is visible.
760     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
761     * android:visibility}.
762     */
763    public static final int VISIBLE = 0x00000000;
764
765    /**
766     * This view is invisible, but it still takes up space for layout purposes.
767     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
768     * android:visibility}.
769     */
770    public static final int INVISIBLE = 0x00000004;
771
772    /**
773     * This view is invisible, and it doesn't take any space for layout
774     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
775     * android:visibility}.
776     */
777    public static final int GONE = 0x00000008;
778
779    /**
780     * Mask for use with setFlags indicating bits used for visibility.
781     * {@hide}
782     */
783    static final int VISIBILITY_MASK = 0x0000000C;
784
785    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
786
787    /**
788     * This view is enabled. Interpretation varies by subclass.
789     * Use with ENABLED_MASK when calling setFlags.
790     * {@hide}
791     */
792    static final int ENABLED = 0x00000000;
793
794    /**
795     * This view is disabled. Interpretation varies by subclass.
796     * Use with ENABLED_MASK when calling setFlags.
797     * {@hide}
798     */
799    static final int DISABLED = 0x00000020;
800
801   /**
802    * Mask for use with setFlags indicating bits used for indicating whether
803    * this view is enabled
804    * {@hide}
805    */
806    static final int ENABLED_MASK = 0x00000020;
807
808    /**
809     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
810     * called and further optimizations will be performed. It is okay to have
811     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
812     * {@hide}
813     */
814    static final int WILL_NOT_DRAW = 0x00000080;
815
816    /**
817     * Mask for use with setFlags indicating bits used for indicating whether
818     * this view is will draw
819     * {@hide}
820     */
821    static final int DRAW_MASK = 0x00000080;
822
823    /**
824     * <p>This view doesn't show scrollbars.</p>
825     * {@hide}
826     */
827    static final int SCROLLBARS_NONE = 0x00000000;
828
829    /**
830     * <p>This view shows horizontal scrollbars.</p>
831     * {@hide}
832     */
833    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
834
835    /**
836     * <p>This view shows vertical scrollbars.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_VERTICAL = 0x00000200;
840
841    /**
842     * <p>Mask for use with setFlags indicating bits used for indicating which
843     * scrollbars are enabled.</p>
844     * {@hide}
845     */
846    static final int SCROLLBARS_MASK = 0x00000300;
847
848    /**
849     * Indicates that the view should filter touches when its window is obscured.
850     * Refer to the class comments for more information about this security feature.
851     * {@hide}
852     */
853    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
854
855    /**
856     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
857     * that they are optional and should be skipped if the window has
858     * requested system UI flags that ignore those insets for layout.
859     */
860    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
861
862    /**
863     * <p>This view doesn't show fading edges.</p>
864     * {@hide}
865     */
866    static final int FADING_EDGE_NONE = 0x00000000;
867
868    /**
869     * <p>This view shows horizontal fading edges.</p>
870     * {@hide}
871     */
872    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
873
874    /**
875     * <p>This view shows vertical fading edges.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_VERTICAL = 0x00002000;
879
880    /**
881     * <p>Mask for use with setFlags indicating bits used for indicating which
882     * fading edges are enabled.</p>
883     * {@hide}
884     */
885    static final int FADING_EDGE_MASK = 0x00003000;
886
887    /**
888     * <p>Indicates this view can be clicked. When clickable, a View reacts
889     * to clicks by notifying the OnClickListener.<p>
890     * {@hide}
891     */
892    static final int CLICKABLE = 0x00004000;
893
894    /**
895     * <p>Indicates this view is caching its drawing into a bitmap.</p>
896     * {@hide}
897     */
898    static final int DRAWING_CACHE_ENABLED = 0x00008000;
899
900    /**
901     * <p>Indicates that no icicle should be saved for this view.<p>
902     * {@hide}
903     */
904    static final int SAVE_DISABLED = 0x000010000;
905
906    /**
907     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
908     * property.</p>
909     * {@hide}
910     */
911    static final int SAVE_DISABLED_MASK = 0x000010000;
912
913    /**
914     * <p>Indicates that no drawing cache should ever be created for this view.<p>
915     * {@hide}
916     */
917    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
918
919    /**
920     * <p>Indicates this view can take / keep focus when int touch mode.</p>
921     * {@hide}
922     */
923    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
924
925    /** @hide */
926    @Retention(RetentionPolicy.SOURCE)
927    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
928    public @interface DrawingCacheQuality {}
929
930    /**
931     * <p>Enables low quality mode for the drawing cache.</p>
932     */
933    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
934
935    /**
936     * <p>Enables high quality mode for the drawing cache.</p>
937     */
938    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
939
940    /**
941     * <p>Enables automatic quality mode for the drawing cache.</p>
942     */
943    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
944
945    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
946            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
947    };
948
949    /**
950     * <p>Mask for use with setFlags indicating bits used for the cache
951     * quality property.</p>
952     * {@hide}
953     */
954    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
955
956    /**
957     * <p>
958     * Indicates this view can be long clicked. When long clickable, a View
959     * reacts to long clicks by notifying the OnLongClickListener or showing a
960     * context menu.
961     * </p>
962     * {@hide}
963     */
964    static final int LONG_CLICKABLE = 0x00200000;
965
966    /**
967     * <p>Indicates that this view gets its drawable states from its direct parent
968     * and ignores its original internal states.</p>
969     *
970     * @hide
971     */
972    static final int DUPLICATE_PARENT_STATE = 0x00400000;
973
974    /** @hide */
975    @IntDef({
976        SCROLLBARS_INSIDE_OVERLAY,
977        SCROLLBARS_INSIDE_INSET,
978        SCROLLBARS_OUTSIDE_OVERLAY,
979        SCROLLBARS_OUTSIDE_INSET
980    })
981    @Retention(RetentionPolicy.SOURCE)
982    public @interface ScrollBarStyle {}
983
984    /**
985     * The scrollbar style to display the scrollbars inside the content area,
986     * without increasing the padding. The scrollbars will be overlaid with
987     * translucency on the view's content.
988     */
989    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
990
991    /**
992     * The scrollbar style to display the scrollbars inside the padded area,
993     * increasing the padding of the view. The scrollbars will not overlap the
994     * content area of the view.
995     */
996    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
997
998    /**
999     * The scrollbar style to display the scrollbars at the edge of the view,
1000     * without increasing the padding. The scrollbars will be overlaid with
1001     * translucency.
1002     */
1003    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1004
1005    /**
1006     * The scrollbar style to display the scrollbars at the edge of the view,
1007     * increasing the padding of the view. The scrollbars will only overlap the
1008     * background, if any.
1009     */
1010    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1011
1012    /**
1013     * Mask to check if the scrollbar style is overlay or inset.
1014     * {@hide}
1015     */
1016    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1017
1018    /**
1019     * Mask to check if the scrollbar style is inside or outside.
1020     * {@hide}
1021     */
1022    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1023
1024    /**
1025     * Mask for scrollbar style.
1026     * {@hide}
1027     */
1028    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1029
1030    /**
1031     * View flag indicating that the screen should remain on while the
1032     * window containing this view is visible to the user.  This effectively
1033     * takes care of automatically setting the WindowManager's
1034     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1035     */
1036    public static final int KEEP_SCREEN_ON = 0x04000000;
1037
1038    /**
1039     * View flag indicating whether this view should have sound effects enabled
1040     * for events such as clicking and touching.
1041     */
1042    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1043
1044    /**
1045     * View flag indicating whether this view should have haptic feedback
1046     * enabled for events such as long presses.
1047     */
1048    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1049
1050    /**
1051     * <p>Indicates that the view hierarchy should stop saving state when
1052     * it reaches this view.  If state saving is initiated immediately at
1053     * the view, it will be allowed.
1054     * {@hide}
1055     */
1056    static final int PARENT_SAVE_DISABLED = 0x20000000;
1057
1058    /**
1059     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1060     * {@hide}
1061     */
1062    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1063
1064    /** @hide */
1065    @IntDef(flag = true,
1066            value = {
1067                FOCUSABLES_ALL,
1068                FOCUSABLES_TOUCH_MODE
1069            })
1070    @Retention(RetentionPolicy.SOURCE)
1071    public @interface FocusableMode {}
1072
1073    /**
1074     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1075     * should add all focusable Views regardless if they are focusable in touch mode.
1076     */
1077    public static final int FOCUSABLES_ALL = 0x00000000;
1078
1079    /**
1080     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1081     * should add only Views focusable in touch mode.
1082     */
1083    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1084
1085    /** @hide */
1086    @IntDef({
1087            FOCUS_BACKWARD,
1088            FOCUS_FORWARD,
1089            FOCUS_LEFT,
1090            FOCUS_UP,
1091            FOCUS_RIGHT,
1092            FOCUS_DOWN
1093    })
1094    @Retention(RetentionPolicy.SOURCE)
1095    public @interface FocusDirection {}
1096
1097    /** @hide */
1098    @IntDef({
1099            FOCUS_LEFT,
1100            FOCUS_UP,
1101            FOCUS_RIGHT,
1102            FOCUS_DOWN
1103    })
1104    @Retention(RetentionPolicy.SOURCE)
1105    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1106
1107    /**
1108     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1109     * item.
1110     */
1111    public static final int FOCUS_BACKWARD = 0x00000001;
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1115     * item.
1116     */
1117    public static final int FOCUS_FORWARD = 0x00000002;
1118
1119    /**
1120     * Use with {@link #focusSearch(int)}. Move focus to the left.
1121     */
1122    public static final int FOCUS_LEFT = 0x00000011;
1123
1124    /**
1125     * Use with {@link #focusSearch(int)}. Move focus up.
1126     */
1127    public static final int FOCUS_UP = 0x00000021;
1128
1129    /**
1130     * Use with {@link #focusSearch(int)}. Move focus to the right.
1131     */
1132    public static final int FOCUS_RIGHT = 0x00000042;
1133
1134    /**
1135     * Use with {@link #focusSearch(int)}. Move focus down.
1136     */
1137    public static final int FOCUS_DOWN = 0x00000082;
1138
1139    /**
1140     * Bits of {@link #getMeasuredWidthAndState()} and
1141     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1142     */
1143    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1144
1145    /**
1146     * Bits of {@link #getMeasuredWidthAndState()} and
1147     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1148     */
1149    public static final int MEASURED_STATE_MASK = 0xff000000;
1150
1151    /**
1152     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1153     * for functions that combine both width and height into a single int,
1154     * such as {@link #getMeasuredState()} and the childState argument of
1155     * {@link #resolveSizeAndState(int, int, int)}.
1156     */
1157    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1158
1159    /**
1160     * Bit of {@link #getMeasuredWidthAndState()} and
1161     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1162     * is smaller that the space the view would like to have.
1163     */
1164    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1165
1166    /**
1167     * Base View state sets
1168     */
1169    // Singles
1170    /**
1171     * Indicates the view has no states set. States are used with
1172     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1173     * view depending on its state.
1174     *
1175     * @see android.graphics.drawable.Drawable
1176     * @see #getDrawableState()
1177     */
1178    protected static final int[] EMPTY_STATE_SET;
1179    /**
1180     * Indicates the view is enabled. States are used with
1181     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1182     * view depending on its state.
1183     *
1184     * @see android.graphics.drawable.Drawable
1185     * @see #getDrawableState()
1186     */
1187    protected static final int[] ENABLED_STATE_SET;
1188    /**
1189     * Indicates the view is focused. 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[] FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is selected. 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[] SELECTED_STATE_SET;
1206    /**
1207     * Indicates the view is pressed. 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[] PRESSED_STATE_SET;
1215    /**
1216     * Indicates the view's window has focus. 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[] WINDOW_FOCUSED_STATE_SET;
1224    // Doubles
1225    /**
1226     * Indicates the view is enabled and has the focus.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #FOCUSED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1232    /**
1233     * Indicates the view is enabled and selected.
1234     *
1235     * @see #ENABLED_STATE_SET
1236     * @see #SELECTED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_SELECTED_STATE_SET;
1239    /**
1240     * Indicates the view is enabled and that its window has focus.
1241     *
1242     * @see #ENABLED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is focused and selected.
1248     *
1249     * @see #FOCUSED_STATE_SET
1250     * @see #SELECTED_STATE_SET
1251     */
1252    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1253    /**
1254     * Indicates the view has the focus and that its window has the focus.
1255     *
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is selected and that its window has the focus.
1262     *
1263     * @see #SELECTED_STATE_SET
1264     * @see #WINDOW_FOCUSED_STATE_SET
1265     */
1266    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1267    // Triples
1268    /**
1269     * Indicates the view is enabled, focused and selected.
1270     *
1271     * @see #ENABLED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     */
1275    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1276    /**
1277     * Indicates the view is enabled, focused and its window has the focus.
1278     *
1279     * @see #ENABLED_STATE_SET
1280     * @see #FOCUSED_STATE_SET
1281     * @see #WINDOW_FOCUSED_STATE_SET
1282     */
1283    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is enabled, selected and its window has the focus.
1286     *
1287     * @see #ENABLED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is focused, selected and its window has the focus.
1294     *
1295     * @see #FOCUSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #WINDOW_FOCUSED_STATE_SET
1298     */
1299    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1300    /**
1301     * Indicates the view is enabled, focused, selected and its window
1302     * has the focus.
1303     *
1304     * @see #ENABLED_STATE_SET
1305     * @see #FOCUSED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and its window has the focus.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #WINDOW_FOCUSED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed and selected.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_SELECTED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, selected and its window has the focus.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #SELECTED_STATE_SET
1329     * @see #WINDOW_FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed and focused.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, focused and its window has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #FOCUSED_STATE_SET
1344     * @see #WINDOW_FOCUSED_STATE_SET
1345     */
1346    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1347    /**
1348     * Indicates the view is pressed, focused and selected.
1349     *
1350     * @see #PRESSED_STATE_SET
1351     * @see #SELECTED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     */
1354    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view is pressed, focused, selected and its window has the focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #FOCUSED_STATE_SET
1360     * @see #SELECTED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed and enabled.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     */
1370    protected static final int[] PRESSED_ENABLED_STATE_SET;
1371    /**
1372     * Indicates the view is pressed, enabled and its window has the focus.
1373     *
1374     * @see #PRESSED_STATE_SET
1375     * @see #ENABLED_STATE_SET
1376     * @see #WINDOW_FOCUSED_STATE_SET
1377     */
1378    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1379    /**
1380     * Indicates the view is pressed, enabled and selected.
1381     *
1382     * @see #PRESSED_STATE_SET
1383     * @see #ENABLED_STATE_SET
1384     * @see #SELECTED_STATE_SET
1385     */
1386    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1387    /**
1388     * Indicates the view is pressed, enabled, selected and its window has the
1389     * focus.
1390     *
1391     * @see #PRESSED_STATE_SET
1392     * @see #ENABLED_STATE_SET
1393     * @see #SELECTED_STATE_SET
1394     * @see #WINDOW_FOCUSED_STATE_SET
1395     */
1396    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1397    /**
1398     * Indicates the view is pressed, enabled and focused.
1399     *
1400     * @see #PRESSED_STATE_SET
1401     * @see #ENABLED_STATE_SET
1402     * @see #FOCUSED_STATE_SET
1403     */
1404    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1405    /**
1406     * Indicates the view is pressed, enabled, focused and its window has the
1407     * focus.
1408     *
1409     * @see #PRESSED_STATE_SET
1410     * @see #ENABLED_STATE_SET
1411     * @see #FOCUSED_STATE_SET
1412     * @see #WINDOW_FOCUSED_STATE_SET
1413     */
1414    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1415    /**
1416     * Indicates the view is pressed, enabled, focused and selected.
1417     *
1418     * @see #PRESSED_STATE_SET
1419     * @see #ENABLED_STATE_SET
1420     * @see #SELECTED_STATE_SET
1421     * @see #FOCUSED_STATE_SET
1422     */
1423    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1424    /**
1425     * Indicates the view is pressed, enabled, focused, selected and its window
1426     * has the focus.
1427     *
1428     * @see #PRESSED_STATE_SET
1429     * @see #ENABLED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #FOCUSED_STATE_SET
1432     * @see #WINDOW_FOCUSED_STATE_SET
1433     */
1434    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1435
1436    /**
1437     * The order here is very important to {@link #getDrawableState()}
1438     */
1439    private static final int[][] VIEW_STATE_SETS;
1440
1441    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1442    static final int VIEW_STATE_SELECTED = 1 << 1;
1443    static final int VIEW_STATE_FOCUSED = 1 << 2;
1444    static final int VIEW_STATE_ENABLED = 1 << 3;
1445    static final int VIEW_STATE_PRESSED = 1 << 4;
1446    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1447    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1448    static final int VIEW_STATE_HOVERED = 1 << 7;
1449    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1450    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1451
1452    static final int[] VIEW_STATE_IDS = new int[] {
1453        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1454        R.attr.state_selected,          VIEW_STATE_SELECTED,
1455        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1456        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1457        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1458        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1459        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1460        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1461        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1462        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1463    };
1464
1465    static {
1466        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1467            throw new IllegalStateException(
1468                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1469        }
1470        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1471        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1472            int viewState = R.styleable.ViewDrawableStates[i];
1473            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1474                if (VIEW_STATE_IDS[j] == viewState) {
1475                    orderedIds[i * 2] = viewState;
1476                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1477                }
1478            }
1479        }
1480        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1481        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1482        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1483            int numBits = Integer.bitCount(i);
1484            int[] set = new int[numBits];
1485            int pos = 0;
1486            for (int j = 0; j < orderedIds.length; j += 2) {
1487                if ((i & orderedIds[j+1]) != 0) {
1488                    set[pos++] = orderedIds[j];
1489                }
1490            }
1491            VIEW_STATE_SETS[i] = set;
1492        }
1493
1494        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1495        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1496        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1497        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1499        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1500        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1502        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1504        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1506                | VIEW_STATE_FOCUSED];
1507        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1508        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1510        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1512        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1514                | VIEW_STATE_ENABLED];
1515        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1517        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1518                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1519                | VIEW_STATE_ENABLED];
1520        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1521                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1522                | VIEW_STATE_ENABLED];
1523        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1525                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1526
1527        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1528        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1532        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1534                | VIEW_STATE_PRESSED];
1535        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1537        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1538                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1539                | VIEW_STATE_PRESSED];
1540        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1541                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1542                | VIEW_STATE_PRESSED];
1543        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1544                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1545                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1546        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1547                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1548        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1549                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1550                | VIEW_STATE_PRESSED];
1551        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1552                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1553                | VIEW_STATE_PRESSED];
1554        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1555                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1556                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1557        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1558                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1559                | VIEW_STATE_PRESSED];
1560        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1561                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1562                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1563        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1564                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1565                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1566        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1567                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1568                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1569                | VIEW_STATE_PRESSED];
1570    }
1571
1572    /**
1573     * Accessibility event types that are dispatched for text population.
1574     */
1575    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1576            AccessibilityEvent.TYPE_VIEW_CLICKED
1577            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1578            | AccessibilityEvent.TYPE_VIEW_SELECTED
1579            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1580            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1581            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1582            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1583            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1584            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1585            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1586            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1587
1588    /**
1589     * Temporary Rect currently for use in setBackground().  This will probably
1590     * be extended in the future to hold our own class with more than just
1591     * a Rect. :)
1592     */
1593    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1594
1595    /**
1596     * Map used to store views' tags.
1597     */
1598    private SparseArray<Object> mKeyedTags;
1599
1600    /**
1601     * The next available accessibility id.
1602     */
1603    private static int sNextAccessibilityViewId;
1604
1605    /**
1606     * The animation currently associated with this view.
1607     * @hide
1608     */
1609    protected Animation mCurrentAnimation = null;
1610
1611    /**
1612     * Width as measured during measure pass.
1613     * {@hide}
1614     */
1615    @ViewDebug.ExportedProperty(category = "measurement")
1616    int mMeasuredWidth;
1617
1618    /**
1619     * Height as measured during measure pass.
1620     * {@hide}
1621     */
1622    @ViewDebug.ExportedProperty(category = "measurement")
1623    int mMeasuredHeight;
1624
1625    /**
1626     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1627     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1628     * its display list. This flag, used only when hw accelerated, allows us to clear the
1629     * flag while retaining this information until it's needed (at getDisplayList() time and
1630     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1631     *
1632     * {@hide}
1633     */
1634    boolean mRecreateDisplayList = false;
1635
1636    /**
1637     * The view's identifier.
1638     * {@hide}
1639     *
1640     * @see #setId(int)
1641     * @see #getId()
1642     */
1643    @ViewDebug.ExportedProperty(resolveId = true)
1644    int mID = NO_ID;
1645
1646    /**
1647     * The stable ID of this view for accessibility purposes.
1648     */
1649    int mAccessibilityViewId = NO_ID;
1650
1651    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1652
1653    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1654
1655    /**
1656     * The view's tag.
1657     * {@hide}
1658     *
1659     * @see #setTag(Object)
1660     * @see #getTag()
1661     */
1662    protected Object mTag = null;
1663
1664    // for mPrivateFlags:
1665    /** {@hide} */
1666    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1667    /** {@hide} */
1668    static final int PFLAG_FOCUSED                     = 0x00000002;
1669    /** {@hide} */
1670    static final int PFLAG_SELECTED                    = 0x00000004;
1671    /** {@hide} */
1672    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1673    /** {@hide} */
1674    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1675    /** {@hide} */
1676    static final int PFLAG_DRAWN                       = 0x00000020;
1677    /**
1678     * When this flag is set, this view is running an animation on behalf of its
1679     * children and should therefore not cancel invalidate requests, even if they
1680     * lie outside of this view's bounds.
1681     *
1682     * {@hide}
1683     */
1684    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1685    /** {@hide} */
1686    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1687    /** {@hide} */
1688    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1689    /** {@hide} */
1690    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1691    /** {@hide} */
1692    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1693    /** {@hide} */
1694    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1695    /** {@hide} */
1696    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1697    /** {@hide} */
1698    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1699
1700    private static final int PFLAG_PRESSED             = 0x00004000;
1701
1702    /** {@hide} */
1703    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1704    /**
1705     * Flag used to indicate that this view should be drawn once more (and only once
1706     * more) after its animation has completed.
1707     * {@hide}
1708     */
1709    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1710
1711    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1712
1713    /**
1714     * Indicates that the View returned true when onSetAlpha() was called and that
1715     * the alpha must be restored.
1716     * {@hide}
1717     */
1718    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1719
1720    /**
1721     * Set by {@link #setScrollContainer(boolean)}.
1722     */
1723    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1724
1725    /**
1726     * Set by {@link #setScrollContainer(boolean)}.
1727     */
1728    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1729
1730    /**
1731     * View flag indicating whether this view was invalidated (fully or partially.)
1732     *
1733     * @hide
1734     */
1735    static final int PFLAG_DIRTY                       = 0x00200000;
1736
1737    /**
1738     * View flag indicating whether this view was invalidated by an opaque
1739     * invalidate request.
1740     *
1741     * @hide
1742     */
1743    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1744
1745    /**
1746     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1751
1752    /**
1753     * Indicates whether the background is opaque.
1754     *
1755     * @hide
1756     */
1757    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1758
1759    /**
1760     * Indicates whether the scrollbars are opaque.
1761     *
1762     * @hide
1763     */
1764    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1765
1766    /**
1767     * Indicates whether the view is opaque.
1768     *
1769     * @hide
1770     */
1771    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1772
1773    /**
1774     * Indicates a prepressed state;
1775     * the short time between ACTION_DOWN and recognizing
1776     * a 'real' press. Prepressed is used to recognize quick taps
1777     * even when they are shorter than ViewConfiguration.getTapTimeout().
1778     *
1779     * @hide
1780     */
1781    private static final int PFLAG_PREPRESSED          = 0x02000000;
1782
1783    /**
1784     * Indicates whether the view is temporarily detached.
1785     *
1786     * @hide
1787     */
1788    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1789
1790    /**
1791     * Indicates that we should awaken scroll bars once attached
1792     *
1793     * @hide
1794     */
1795    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1796
1797    /**
1798     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1799     * @hide
1800     */
1801    private static final int PFLAG_HOVERED             = 0x10000000;
1802
1803    /**
1804     * no longer needed, should be reused
1805     */
1806    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1807
1808    /** {@hide} */
1809    static final int PFLAG_ACTIVATED                   = 0x40000000;
1810
1811    /**
1812     * Indicates that this view was specifically invalidated, not just dirtied because some
1813     * child view was invalidated. The flag is used to determine when we need to recreate
1814     * a view's display list (as opposed to just returning a reference to its existing
1815     * display list).
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_INVALIDATED                 = 0x80000000;
1820
1821    /**
1822     * Masks for mPrivateFlags2, as generated by dumpFlags():
1823     *
1824     * |-------|-------|-------|-------|
1825     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1826     *                                1  PFLAG2_DRAG_HOVERED
1827     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1828     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1829     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1830     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1831     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1832     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1833     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1834     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1835     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1836     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1837     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1838     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1839     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1840     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1841     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1842     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1843     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1844     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1845     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1846     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1847     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1848     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1849     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1850     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1851     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1852     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1853     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1854     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1855     *    1                              PFLAG2_PADDING_RESOLVED
1856     *   1                               PFLAG2_DRAWABLE_RESOLVED
1857     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1858     * |-------|-------|-------|-------|
1859     */
1860
1861    /**
1862     * Indicates that this view has reported that it can accept the current drag's content.
1863     * Cleared when the drag operation concludes.
1864     * @hide
1865     */
1866    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1867
1868    /**
1869     * Indicates that this view is currently directly under the drag location in a
1870     * drag-and-drop operation involving content that it can accept.  Cleared when
1871     * the drag exits the view, or when the drag operation concludes.
1872     * @hide
1873     */
1874    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1875
1876    /** @hide */
1877    @IntDef({
1878        LAYOUT_DIRECTION_LTR,
1879        LAYOUT_DIRECTION_RTL,
1880        LAYOUT_DIRECTION_INHERIT,
1881        LAYOUT_DIRECTION_LOCALE
1882    })
1883    @Retention(RetentionPolicy.SOURCE)
1884    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1885    public @interface LayoutDir {}
1886
1887    /** @hide */
1888    @IntDef({
1889        LAYOUT_DIRECTION_LTR,
1890        LAYOUT_DIRECTION_RTL
1891    })
1892    @Retention(RetentionPolicy.SOURCE)
1893    public @interface ResolvedLayoutDir {}
1894
1895    /**
1896     * Horizontal layout direction of this view is from Left to Right.
1897     * Use with {@link #setLayoutDirection}.
1898     */
1899    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1900
1901    /**
1902     * Horizontal layout direction of this view is from Right to Left.
1903     * Use with {@link #setLayoutDirection}.
1904     */
1905    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1906
1907    /**
1908     * Horizontal layout direction of this view is inherited from its parent.
1909     * Use with {@link #setLayoutDirection}.
1910     */
1911    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1912
1913    /**
1914     * Horizontal layout direction of this view is from deduced from the default language
1915     * script for the locale. Use with {@link #setLayoutDirection}.
1916     */
1917    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1918
1919    /**
1920     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1921     * @hide
1922     */
1923    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1924
1925    /**
1926     * Mask for use with private flags indicating bits used for horizontal layout direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1933     * right-to-left direction.
1934     * @hide
1935     */
1936    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1937
1938    /**
1939     * Indicates whether the view horizontal layout direction has been resolved.
1940     * @hide
1941     */
1942    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /**
1945     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1946     * @hide
1947     */
1948    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1949            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1950
1951    /*
1952     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1953     * flag value.
1954     * @hide
1955     */
1956    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1957            LAYOUT_DIRECTION_LTR,
1958            LAYOUT_DIRECTION_RTL,
1959            LAYOUT_DIRECTION_INHERIT,
1960            LAYOUT_DIRECTION_LOCALE
1961    };
1962
1963    /**
1964     * Default horizontal layout direction.
1965     */
1966    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1967
1968    /**
1969     * Default horizontal layout direction.
1970     * @hide
1971     */
1972    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1973
1974    /**
1975     * Text direction is inherited thru {@link ViewGroup}
1976     */
1977    public static final int TEXT_DIRECTION_INHERIT = 0;
1978
1979    /**
1980     * Text direction is using "first strong algorithm". The first strong directional character
1981     * determines the paragraph direction. If there is no strong directional character, the
1982     * paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1985
1986    /**
1987     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1988     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1989     * If there are neither, the paragraph direction is the view's resolved layout direction.
1990     */
1991    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1992
1993    /**
1994     * Text direction is forced to LTR.
1995     */
1996    public static final int TEXT_DIRECTION_LTR = 3;
1997
1998    /**
1999     * Text direction is forced to RTL.
2000     */
2001    public static final int TEXT_DIRECTION_RTL = 4;
2002
2003    /**
2004     * Text direction is coming from the system Locale.
2005     */
2006    public static final int TEXT_DIRECTION_LOCALE = 5;
2007
2008    /**
2009     * Default text direction is inherited
2010     */
2011    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2012
2013    /**
2014     * Default resolved text direction
2015     * @hide
2016     */
2017    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2018
2019    /**
2020     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2021     * @hide
2022     */
2023    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2024
2025    /**
2026     * Mask for use with private flags indicating bits used for text direction.
2027     * @hide
2028     */
2029    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2030            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2031
2032    /**
2033     * Array of text direction flags for mapping attribute "textDirection" to correct
2034     * flag value.
2035     * @hide
2036     */
2037    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2038            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2039            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2040            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2041            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2042            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2043            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2044    };
2045
2046    /**
2047     * Indicates whether the view text direction has been resolved.
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2051            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2052
2053    /**
2054     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2055     * @hide
2056     */
2057    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2058
2059    /**
2060     * Mask for use with private flags indicating bits used for resolved text direction.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2064            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /**
2067     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2068     * @hide
2069     */
2070    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2071            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2072
2073    /** @hide */
2074    @IntDef({
2075        TEXT_ALIGNMENT_INHERIT,
2076        TEXT_ALIGNMENT_GRAVITY,
2077        TEXT_ALIGNMENT_CENTER,
2078        TEXT_ALIGNMENT_TEXT_START,
2079        TEXT_ALIGNMENT_TEXT_END,
2080        TEXT_ALIGNMENT_VIEW_START,
2081        TEXT_ALIGNMENT_VIEW_END
2082    })
2083    @Retention(RetentionPolicy.SOURCE)
2084    public @interface TextAlignment {}
2085
2086    /**
2087     * Default text alignment. The text alignment of this View is inherited from its parent.
2088     * Use with {@link #setTextAlignment(int)}
2089     */
2090    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2091
2092    /**
2093     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2094     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2099
2100    /**
2101     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2106
2107    /**
2108     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2113
2114    /**
2115     * Center the paragraph, e.g. ALIGN_CENTER.
2116     *
2117     * Use with {@link #setTextAlignment(int)}
2118     */
2119    public static final int TEXT_ALIGNMENT_CENTER = 4;
2120
2121    /**
2122     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2123     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2124     *
2125     * Use with {@link #setTextAlignment(int)}
2126     */
2127    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2128
2129    /**
2130     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2131     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2132     *
2133     * Use with {@link #setTextAlignment(int)}
2134     */
2135    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2136
2137    /**
2138     * Default text alignment is inherited
2139     */
2140    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2141
2142    /**
2143     * Default resolved text alignment
2144     * @hide
2145     */
2146    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2147
2148    /**
2149      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2150      * @hide
2151      */
2152    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2153
2154    /**
2155      * Mask for use with private flags indicating bits used for text alignment.
2156      * @hide
2157      */
2158    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2159
2160    /**
2161     * Array of text direction flags for mapping attribute "textAlignment" to correct
2162     * flag value.
2163     * @hide
2164     */
2165    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2166            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2168            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2169            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2170            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2171            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2172            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2173    };
2174
2175    /**
2176     * Indicates whether the view text alignment has been resolved.
2177     * @hide
2178     */
2179    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2180
2181    /**
2182     * Bit shift to get the resolved text alignment.
2183     * @hide
2184     */
2185    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2186
2187    /**
2188     * Mask for use with private flags indicating bits used for text alignment.
2189     * @hide
2190     */
2191    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2192            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2193
2194    /**
2195     * Indicates whether if the view text alignment has been resolved to gravity
2196     */
2197    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2198            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2199
2200    // Accessiblity constants for mPrivateFlags2
2201
2202    /**
2203     * Shift for the bits in {@link #mPrivateFlags2} related to the
2204     * "importantForAccessibility" attribute.
2205     */
2206    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2207
2208    /**
2209     * Automatically determine whether a view is important for accessibility.
2210     */
2211    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2212
2213    /**
2214     * The view is important for accessibility.
2215     */
2216    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2217
2218    /**
2219     * The view is not important for accessibility.
2220     */
2221    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2222
2223    /**
2224     * The view is not important for accessibility, nor are any of its
2225     * descendant views.
2226     */
2227    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2228
2229    /**
2230     * The default whether the view is important for accessibility.
2231     */
2232    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2233
2234    /**
2235     * Mask for obtainig the bits which specify how to determine
2236     * whether a view is important for accessibility.
2237     */
2238    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2239        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2240        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2241        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2242
2243    /**
2244     * Shift for the bits in {@link #mPrivateFlags2} related to the
2245     * "accessibilityLiveRegion" attribute.
2246     */
2247    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2248
2249    /**
2250     * Live region mode specifying that accessibility services should not
2251     * automatically announce changes to this view. This is the default live
2252     * region mode for most views.
2253     * <p>
2254     * Use with {@link #setAccessibilityLiveRegion(int)}.
2255     */
2256    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2257
2258    /**
2259     * Live region mode specifying that accessibility services should announce
2260     * changes to this view.
2261     * <p>
2262     * Use with {@link #setAccessibilityLiveRegion(int)}.
2263     */
2264    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2265
2266    /**
2267     * Live region mode specifying that accessibility services should interrupt
2268     * ongoing speech to immediately announce changes to this view.
2269     * <p>
2270     * Use with {@link #setAccessibilityLiveRegion(int)}.
2271     */
2272    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2273
2274    /**
2275     * The default whether the view is important for accessibility.
2276     */
2277    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2278
2279    /**
2280     * Mask for obtaining the bits which specify a view's accessibility live
2281     * region mode.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2284            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2285            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2286
2287    /**
2288     * Flag indicating whether a view has accessibility focus.
2289     */
2290    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2291
2292    /**
2293     * Flag whether the accessibility state of the subtree rooted at this view changed.
2294     */
2295    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2296
2297    /**
2298     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2299     * is used to check whether later changes to the view's transform should invalidate the
2300     * view to force the quickReject test to run again.
2301     */
2302    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2303
2304    /**
2305     * Flag indicating that start/end padding has been resolved into left/right padding
2306     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2307     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2308     * during measurement. In some special cases this is required such as when an adapter-based
2309     * view measures prospective children without attaching them to a window.
2310     */
2311    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2312
2313    /**
2314     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2315     */
2316    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2317
2318    /**
2319     * Indicates that the view is tracking some sort of transient state
2320     * that the app should not need to be aware of, but that the framework
2321     * should take special care to preserve.
2322     */
2323    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2324
2325    /**
2326     * Group of bits indicating that RTL properties resolution is done.
2327     */
2328    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2329            PFLAG2_TEXT_DIRECTION_RESOLVED |
2330            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2331            PFLAG2_PADDING_RESOLVED |
2332            PFLAG2_DRAWABLE_RESOLVED;
2333
2334    // There are a couple of flags left in mPrivateFlags2
2335
2336    /* End of masks for mPrivateFlags2 */
2337
2338    /**
2339     * Masks for mPrivateFlags3, as generated by dumpFlags():
2340     *
2341     * |-------|-------|-------|-------|
2342     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2343     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2344     *                               1   PFLAG3_IS_LAID_OUT
2345     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2346     *                             1     PFLAG3_CALLED_SUPER
2347     * |-------|-------|-------|-------|
2348     */
2349
2350    /**
2351     * Flag indicating that view has a transform animation set on it. This is used to track whether
2352     * an animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to clear its animation matrix.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2356
2357    /**
2358     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2359     * animation is cleared between successive frames, in order to tell the associated
2360     * DisplayList to restore its alpha value.
2361     */
2362    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2363
2364    /**
2365     * Flag indicating that the view has been through at least one layout since it
2366     * was last attached to a window.
2367     */
2368    static final int PFLAG3_IS_LAID_OUT = 0x4;
2369
2370    /**
2371     * Flag indicating that a call to measure() was skipped and should be done
2372     * instead when layout() is invoked.
2373     */
2374    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2375
2376    /**
2377     * Flag indicating that an overridden method correctly  called down to
2378     * the superclass implementation as required by the API spec.
2379     */
2380    static final int PFLAG3_CALLED_SUPER = 0x10;
2381
2382    @Deprecated
2383    static final int PFLAG3_OUTLINE_DEFINED = 0x20;
2384
2385    /**
2386     * Flag indicating that we're in the process of applying window insets.
2387     */
2388    static final int PFLAG3_APPLYING_INSETS = 0x40;
2389
2390    /**
2391     * Flag indicating that we're in the process of fitting system windows using the old method.
2392     */
2393    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2394
2395    /**
2396     * Flag indicating that nested scrolling is enabled for this view.
2397     * The view will optionally cooperate with views up its parent chain to allow for
2398     * integrated nested scrolling along the same axis.
2399     */
2400    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200;
2401
2402    /* End of masks for mPrivateFlags3 */
2403
2404    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2405
2406    /**
2407     * Always allow a user to over-scroll this view, provided it is a
2408     * view that can scroll.
2409     *
2410     * @see #getOverScrollMode()
2411     * @see #setOverScrollMode(int)
2412     */
2413    public static final int OVER_SCROLL_ALWAYS = 0;
2414
2415    /**
2416     * Allow a user to over-scroll this view only if the content is large
2417     * enough to meaningfully scroll, provided it is a view that can scroll.
2418     *
2419     * @see #getOverScrollMode()
2420     * @see #setOverScrollMode(int)
2421     */
2422    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2423
2424    /**
2425     * Never allow a user to over-scroll this view.
2426     *
2427     * @see #getOverScrollMode()
2428     * @see #setOverScrollMode(int)
2429     */
2430    public static final int OVER_SCROLL_NEVER = 2;
2431
2432    /**
2433     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2434     * requested the system UI (status bar) to be visible (the default).
2435     *
2436     * @see #setSystemUiVisibility(int)
2437     */
2438    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2439
2440    /**
2441     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2442     * system UI to enter an unobtrusive "low profile" mode.
2443     *
2444     * <p>This is for use in games, book readers, video players, or any other
2445     * "immersive" application where the usual system chrome is deemed too distracting.
2446     *
2447     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2448     *
2449     * @see #setSystemUiVisibility(int)
2450     */
2451    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2452
2453    /**
2454     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2455     * system navigation be temporarily hidden.
2456     *
2457     * <p>This is an even less obtrusive state than that called for by
2458     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2459     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2460     * those to disappear. This is useful (in conjunction with the
2461     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2462     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2463     * window flags) for displaying content using every last pixel on the display.
2464     *
2465     * <p>There is a limitation: because navigation controls are so important, the least user
2466     * interaction will cause them to reappear immediately.  When this happens, both
2467     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2468     * so that both elements reappear at the same time.
2469     *
2470     * @see #setSystemUiVisibility(int)
2471     */
2472    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2473
2474    /**
2475     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2476     * into the normal fullscreen mode so that its content can take over the screen
2477     * while still allowing the user to interact with the application.
2478     *
2479     * <p>This has the same visual effect as
2480     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2481     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2482     * meaning that non-critical screen decorations (such as the status bar) will be
2483     * hidden while the user is in the View's window, focusing the experience on
2484     * that content.  Unlike the window flag, if you are using ActionBar in
2485     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2486     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2487     * hide the action bar.
2488     *
2489     * <p>This approach to going fullscreen is best used over the window flag when
2490     * it is a transient state -- that is, the application does this at certain
2491     * points in its user interaction where it wants to allow the user to focus
2492     * on content, but not as a continuous state.  For situations where the application
2493     * would like to simply stay full screen the entire time (such as a game that
2494     * wants to take over the screen), the
2495     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2496     * is usually a better approach.  The state set here will be removed by the system
2497     * in various situations (such as the user moving to another application) like
2498     * the other system UI states.
2499     *
2500     * <p>When using this flag, the application should provide some easy facility
2501     * for the user to go out of it.  A common example would be in an e-book
2502     * reader, where tapping on the screen brings back whatever screen and UI
2503     * decorations that had been hidden while the user was immersed in reading
2504     * the book.
2505     *
2506     * @see #setSystemUiVisibility(int)
2507     */
2508    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2509
2510    /**
2511     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2512     * flags, we would like a stable view of the content insets given to
2513     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2514     * will always represent the worst case that the application can expect
2515     * as a continuous state.  In the stock Android UI this is the space for
2516     * the system bar, nav bar, and status bar, but not more transient elements
2517     * such as an input method.
2518     *
2519     * The stable layout your UI sees is based on the system UI modes you can
2520     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2521     * then you will get a stable layout for changes of the
2522     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2523     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2524     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2525     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2526     * with a stable layout.  (Note that you should avoid using
2527     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2528     *
2529     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2530     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2531     * then a hidden status bar will be considered a "stable" state for purposes
2532     * here.  This allows your UI to continually hide the status bar, while still
2533     * using the system UI flags to hide the action bar while still retaining
2534     * a stable layout.  Note that changing the window fullscreen flag will never
2535     * provide a stable layout for a clean transition.
2536     *
2537     * <p>If you are using ActionBar in
2538     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2539     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2540     * insets it adds to those given to the application.
2541     */
2542    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2543
2544    /**
2545     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2546     * to be layed out as if it has requested
2547     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2548     * allows it to avoid artifacts when switching in and out of that mode, at
2549     * the expense that some of its user interface may be covered by screen
2550     * decorations when they are shown.  You can perform layout of your inner
2551     * UI elements to account for the navigation system UI through the
2552     * {@link #fitSystemWindows(Rect)} method.
2553     */
2554    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2555
2556    /**
2557     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2558     * to be layed out as if it has requested
2559     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2560     * allows it to avoid artifacts when switching in and out of that mode, at
2561     * the expense that some of its user interface may be covered by screen
2562     * decorations when they are shown.  You can perform layout of your inner
2563     * UI elements to account for non-fullscreen system UI through the
2564     * {@link #fitSystemWindows(Rect)} method.
2565     */
2566    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2571     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2572     * user interaction.
2573     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2574     * has an effect when used in combination with that flag.</p>
2575     */
2576    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2577
2578    /**
2579     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2580     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2581     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2582     * experience while also hiding the system bars.  If this flag is not set,
2583     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2584     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2585     * if the user swipes from the top of the screen.
2586     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2587     * system gestures, such as swiping from the top of the screen.  These transient system bars
2588     * will overlay app’s content, may have some degree of transparency, and will automatically
2589     * hide after a short timeout.
2590     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2591     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2592     * with one or both of those flags.</p>
2593     */
2594    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2595
2596    /**
2597     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2598     */
2599    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2600
2601    /**
2602     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2603     */
2604    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2605
2606    /**
2607     * @hide
2608     *
2609     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2610     * out of the public fields to keep the undefined bits out of the developer's way.
2611     *
2612     * Flag to make the status bar not expandable.  Unless you also
2613     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2614     */
2615    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2616
2617    /**
2618     * @hide
2619     *
2620     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2621     * out of the public fields to keep the undefined bits out of the developer's way.
2622     *
2623     * Flag to hide notification icons and scrolling ticker text.
2624     */
2625    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2626
2627    /**
2628     * @hide
2629     *
2630     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2631     * out of the public fields to keep the undefined bits out of the developer's way.
2632     *
2633     * Flag to disable incoming notification alerts.  This will not block
2634     * icons, but it will block sound, vibrating and other visual or aural notifications.
2635     */
2636    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2637
2638    /**
2639     * @hide
2640     *
2641     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2642     * out of the public fields to keep the undefined bits out of the developer's way.
2643     *
2644     * Flag to hide only the scrolling ticker.  Note that
2645     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2646     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2647     */
2648    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2649
2650    /**
2651     * @hide
2652     *
2653     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2654     * out of the public fields to keep the undefined bits out of the developer's way.
2655     *
2656     * Flag to hide the center system info area.
2657     */
2658    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2659
2660    /**
2661     * @hide
2662     *
2663     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2664     * out of the public fields to keep the undefined bits out of the developer's way.
2665     *
2666     * Flag to hide only the home button.  Don't use this
2667     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2668     */
2669    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2670
2671    /**
2672     * @hide
2673     *
2674     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2675     * out of the public fields to keep the undefined bits out of the developer's way.
2676     *
2677     * Flag to hide only the back button. Don't use this
2678     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2679     */
2680    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2681
2682    /**
2683     * @hide
2684     *
2685     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2686     * out of the public fields to keep the undefined bits out of the developer's way.
2687     *
2688     * Flag to hide only the clock.  You might use this if your activity has
2689     * its own clock making the status bar's clock redundant.
2690     */
2691    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2692
2693    /**
2694     * @hide
2695     *
2696     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2697     * out of the public fields to keep the undefined bits out of the developer's way.
2698     *
2699     * Flag to hide only the recent apps button. Don't use this
2700     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2701     */
2702    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2703
2704    /**
2705     * @hide
2706     *
2707     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2708     * out of the public fields to keep the undefined bits out of the developer's way.
2709     *
2710     * Flag to disable the global search gesture. Don't use this
2711     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2712     */
2713    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2714
2715    /**
2716     * @hide
2717     *
2718     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2719     * out of the public fields to keep the undefined bits out of the developer's way.
2720     *
2721     * Flag to specify that the status bar is displayed in transient mode.
2722     */
2723    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2724
2725    /**
2726     * @hide
2727     *
2728     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2729     * out of the public fields to keep the undefined bits out of the developer's way.
2730     *
2731     * Flag to specify that the navigation bar is displayed in transient mode.
2732     */
2733    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2734
2735    /**
2736     * @hide
2737     *
2738     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2739     * out of the public fields to keep the undefined bits out of the developer's way.
2740     *
2741     * Flag to specify that the hidden status bar would like to be shown.
2742     */
2743    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2744
2745    /**
2746     * @hide
2747     *
2748     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2749     * out of the public fields to keep the undefined bits out of the developer's way.
2750     *
2751     * Flag to specify that the hidden navigation bar would like to be shown.
2752     */
2753    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2754
2755    /**
2756     * @hide
2757     *
2758     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2759     * out of the public fields to keep the undefined bits out of the developer's way.
2760     *
2761     * Flag to specify that the status bar is displayed in translucent mode.
2762     */
2763    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2769     * out of the public fields to keep the undefined bits out of the developer's way.
2770     *
2771     * Flag to specify that the navigation bar is displayed in translucent mode.
2772     */
2773    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2774
2775    /**
2776     * @hide
2777     *
2778     * Whether Recents is visible or not.
2779     */
2780    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2781
2782    /**
2783     * @hide
2784     *
2785     * Makes system ui transparent.
2786     */
2787    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2788
2789    /**
2790     * @hide
2791     */
2792    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2793
2794    /**
2795     * These are the system UI flags that can be cleared by events outside
2796     * of an application.  Currently this is just the ability to tap on the
2797     * screen while hiding the navigation bar to have it return.
2798     * @hide
2799     */
2800    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2801            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2802            | SYSTEM_UI_FLAG_FULLSCREEN;
2803
2804    /**
2805     * Flags that can impact the layout in relation to system UI.
2806     */
2807    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2808            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2809            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2810
2811    /** @hide */
2812    @IntDef(flag = true,
2813            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2814    @Retention(RetentionPolicy.SOURCE)
2815    public @interface FindViewFlags {}
2816
2817    /**
2818     * Find views that render the specified text.
2819     *
2820     * @see #findViewsWithText(ArrayList, CharSequence, int)
2821     */
2822    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2823
2824    /**
2825     * Find find views that contain the specified content description.
2826     *
2827     * @see #findViewsWithText(ArrayList, CharSequence, int)
2828     */
2829    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2830
2831    /**
2832     * Find views that contain {@link AccessibilityNodeProvider}. Such
2833     * a View is a root of virtual view hierarchy and may contain the searched
2834     * text. If this flag is set Views with providers are automatically
2835     * added and it is a responsibility of the client to call the APIs of
2836     * the provider to determine whether the virtual tree rooted at this View
2837     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2838     * representing the virtual views with this text.
2839     *
2840     * @see #findViewsWithText(ArrayList, CharSequence, int)
2841     *
2842     * @hide
2843     */
2844    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2845
2846    /**
2847     * The undefined cursor position.
2848     *
2849     * @hide
2850     */
2851    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2852
2853    /**
2854     * Indicates that the screen has changed state and is now off.
2855     *
2856     * @see #onScreenStateChanged(int)
2857     */
2858    public static final int SCREEN_STATE_OFF = 0x0;
2859
2860    /**
2861     * Indicates that the screen has changed state and is now on.
2862     *
2863     * @see #onScreenStateChanged(int)
2864     */
2865    public static final int SCREEN_STATE_ON = 0x1;
2866
2867    /**
2868     * Indicates no axis of view scrolling.
2869     */
2870    public static final int SCROLL_AXIS_NONE = 0;
2871
2872    /**
2873     * Indicates scrolling along the horizontal axis.
2874     */
2875    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2876
2877    /**
2878     * Indicates scrolling along the vertical axis.
2879     */
2880    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2881
2882    /**
2883     * Controls the over-scroll mode for this view.
2884     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2885     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2886     * and {@link #OVER_SCROLL_NEVER}.
2887     */
2888    private int mOverScrollMode;
2889
2890    /**
2891     * The parent this view is attached to.
2892     * {@hide}
2893     *
2894     * @see #getParent()
2895     */
2896    protected ViewParent mParent;
2897
2898    /**
2899     * {@hide}
2900     */
2901    AttachInfo mAttachInfo;
2902
2903    /**
2904     * {@hide}
2905     */
2906    @ViewDebug.ExportedProperty(flagMapping = {
2907        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2908                name = "FORCE_LAYOUT"),
2909        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2910                name = "LAYOUT_REQUIRED"),
2911        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2912            name = "DRAWING_CACHE_INVALID", outputIf = false),
2913        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2914        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2915        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2916        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2917    })
2918    int mPrivateFlags;
2919    int mPrivateFlags2;
2920    int mPrivateFlags3;
2921
2922    /**
2923     * This view's request for the visibility of the status bar.
2924     * @hide
2925     */
2926    @ViewDebug.ExportedProperty(flagMapping = {
2927        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2928                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2929                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2930        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2931                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2932                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2933        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2934                                equals = SYSTEM_UI_FLAG_VISIBLE,
2935                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2936    })
2937    int mSystemUiVisibility;
2938
2939    /**
2940     * Reference count for transient state.
2941     * @see #setHasTransientState(boolean)
2942     */
2943    int mTransientStateCount = 0;
2944
2945    /**
2946     * Count of how many windows this view has been attached to.
2947     */
2948    int mWindowAttachCount;
2949
2950    /**
2951     * The layout parameters associated with this view and used by the parent
2952     * {@link android.view.ViewGroup} to determine how this view should be
2953     * laid out.
2954     * {@hide}
2955     */
2956    protected ViewGroup.LayoutParams mLayoutParams;
2957
2958    /**
2959     * The view flags hold various views states.
2960     * {@hide}
2961     */
2962    @ViewDebug.ExportedProperty
2963    int mViewFlags;
2964
2965    static class TransformationInfo {
2966        /**
2967         * The transform matrix for the View. This transform is calculated internally
2968         * based on the translation, rotation, and scale properties.
2969         *
2970         * Do *not* use this variable directly; instead call getMatrix(), which will
2971         * load the value from the View's RenderNode.
2972         */
2973        private final Matrix mMatrix = new Matrix();
2974
2975        /**
2976         * The inverse transform matrix for the View. This transform is calculated
2977         * internally based on the translation, rotation, and scale properties.
2978         *
2979         * Do *not* use this variable directly; instead call getInverseMatrix(),
2980         * which will load the value from the View's RenderNode.
2981         */
2982        private Matrix mInverseMatrix;
2983
2984        /**
2985         * The opacity of the View. This is a value from 0 to 1, where 0 means
2986         * completely transparent and 1 means completely opaque.
2987         */
2988        @ViewDebug.ExportedProperty
2989        float mAlpha = 1f;
2990
2991        /**
2992         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2993         * property only used by transitions, which is composited with the other alpha
2994         * values to calculate the final visual alpha value.
2995         */
2996        float mTransitionAlpha = 1f;
2997    }
2998
2999    TransformationInfo mTransformationInfo;
3000
3001    /**
3002     * Current clip bounds. to which all drawing of this view are constrained.
3003     */
3004    Rect mClipBounds = null;
3005
3006    private boolean mLastIsOpaque;
3007
3008    /**
3009     * The distance in pixels from the left edge of this view's parent
3010     * to the left edge of this view.
3011     * {@hide}
3012     */
3013    @ViewDebug.ExportedProperty(category = "layout")
3014    protected int mLeft;
3015    /**
3016     * The distance in pixels from the left edge of this view's parent
3017     * to the right edge of this view.
3018     * {@hide}
3019     */
3020    @ViewDebug.ExportedProperty(category = "layout")
3021    protected int mRight;
3022    /**
3023     * The distance in pixels from the top edge of this view's parent
3024     * to the top edge of this view.
3025     * {@hide}
3026     */
3027    @ViewDebug.ExportedProperty(category = "layout")
3028    protected int mTop;
3029    /**
3030     * The distance in pixels from the top edge of this view's parent
3031     * to the bottom edge of this view.
3032     * {@hide}
3033     */
3034    @ViewDebug.ExportedProperty(category = "layout")
3035    protected int mBottom;
3036
3037    /**
3038     * The offset, in pixels, by which the content of this view is scrolled
3039     * horizontally.
3040     * {@hide}
3041     */
3042    @ViewDebug.ExportedProperty(category = "scrolling")
3043    protected int mScrollX;
3044    /**
3045     * The offset, in pixels, by which the content of this view is scrolled
3046     * vertically.
3047     * {@hide}
3048     */
3049    @ViewDebug.ExportedProperty(category = "scrolling")
3050    protected int mScrollY;
3051
3052    /**
3053     * The left padding in pixels, that is the distance in pixels between the
3054     * left edge of this view and the left edge of its content.
3055     * {@hide}
3056     */
3057    @ViewDebug.ExportedProperty(category = "padding")
3058    protected int mPaddingLeft = 0;
3059    /**
3060     * The right padding in pixels, that is the distance in pixels between the
3061     * right edge of this view and the right edge of its content.
3062     * {@hide}
3063     */
3064    @ViewDebug.ExportedProperty(category = "padding")
3065    protected int mPaddingRight = 0;
3066    /**
3067     * The top padding in pixels, that is the distance in pixels between the
3068     * top edge of this view and the top edge of its content.
3069     * {@hide}
3070     */
3071    @ViewDebug.ExportedProperty(category = "padding")
3072    protected int mPaddingTop;
3073    /**
3074     * The bottom padding in pixels, that is the distance in pixels between the
3075     * bottom edge of this view and the bottom edge of its content.
3076     * {@hide}
3077     */
3078    @ViewDebug.ExportedProperty(category = "padding")
3079    protected int mPaddingBottom;
3080
3081    /**
3082     * The layout insets in pixels, that is the distance in pixels between the
3083     * visible edges of this view its bounds.
3084     */
3085    private Insets mLayoutInsets;
3086
3087    /**
3088     * Briefly describes the view and is primarily used for accessibility support.
3089     */
3090    private CharSequence mContentDescription;
3091
3092    /**
3093     * Specifies the id of a view for which this view serves as a label for
3094     * accessibility purposes.
3095     */
3096    private int mLabelForId = View.NO_ID;
3097
3098    /**
3099     * Predicate for matching labeled view id with its label for
3100     * accessibility purposes.
3101     */
3102    private MatchLabelForPredicate mMatchLabelForPredicate;
3103
3104    /**
3105     * Predicate for matching a view by its id.
3106     */
3107    private MatchIdPredicate mMatchIdPredicate;
3108
3109    /**
3110     * Cache the paddingRight set by the user to append to the scrollbar's size.
3111     *
3112     * @hide
3113     */
3114    @ViewDebug.ExportedProperty(category = "padding")
3115    protected int mUserPaddingRight;
3116
3117    /**
3118     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3119     *
3120     * @hide
3121     */
3122    @ViewDebug.ExportedProperty(category = "padding")
3123    protected int mUserPaddingBottom;
3124
3125    /**
3126     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3127     *
3128     * @hide
3129     */
3130    @ViewDebug.ExportedProperty(category = "padding")
3131    protected int mUserPaddingLeft;
3132
3133    /**
3134     * Cache the paddingStart set by the user to append to the scrollbar's size.
3135     *
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    int mUserPaddingStart;
3139
3140    /**
3141     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3142     *
3143     */
3144    @ViewDebug.ExportedProperty(category = "padding")
3145    int mUserPaddingEnd;
3146
3147    /**
3148     * Cache initial left padding.
3149     *
3150     * @hide
3151     */
3152    int mUserPaddingLeftInitial;
3153
3154    /**
3155     * Cache initial right padding.
3156     *
3157     * @hide
3158     */
3159    int mUserPaddingRightInitial;
3160
3161    /**
3162     * Default undefined padding
3163     */
3164    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3165
3166    /**
3167     * Cache if a left padding has been defined
3168     */
3169    private boolean mLeftPaddingDefined = false;
3170
3171    /**
3172     * Cache if a right padding has been defined
3173     */
3174    private boolean mRightPaddingDefined = false;
3175
3176    /**
3177     * @hide
3178     */
3179    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3180    /**
3181     * @hide
3182     */
3183    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3184
3185    private LongSparseLongArray mMeasureCache;
3186
3187    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3188    private Drawable mBackground;
3189    private ColorStateList mBackgroundTint = null;
3190    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3191    private boolean mHasBackgroundTint = false;
3192
3193    /**
3194     * RenderNode used for backgrounds.
3195     * <p>
3196     * When non-null and valid, this is expected to contain an up-to-date copy
3197     * of the background drawable. It is cleared on temporary detach, and reset
3198     * on cleanup.
3199     */
3200    private RenderNode mBackgroundRenderNode;
3201
3202    private int mBackgroundResource;
3203    private boolean mBackgroundSizeChanged;
3204
3205    private String mTransitionName;
3206
3207    static class ListenerInfo {
3208        /**
3209         * Listener used to dispatch focus change events.
3210         * This field should be made private, so it is hidden from the SDK.
3211         * {@hide}
3212         */
3213        protected OnFocusChangeListener mOnFocusChangeListener;
3214
3215        /**
3216         * Listeners for layout change events.
3217         */
3218        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3219
3220        /**
3221         * Listeners for attach events.
3222         */
3223        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3224
3225        /**
3226         * Listener used to dispatch click events.
3227         * This field should be made private, so it is hidden from the SDK.
3228         * {@hide}
3229         */
3230        public OnClickListener mOnClickListener;
3231
3232        /**
3233         * Listener used to dispatch long click events.
3234         * This field should be made private, so it is hidden from the SDK.
3235         * {@hide}
3236         */
3237        protected OnLongClickListener mOnLongClickListener;
3238
3239        /**
3240         * Listener used to build the context menu.
3241         * This field should be made private, so it is hidden from the SDK.
3242         * {@hide}
3243         */
3244        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3245
3246        private OnKeyListener mOnKeyListener;
3247
3248        private OnTouchListener mOnTouchListener;
3249
3250        private OnHoverListener mOnHoverListener;
3251
3252        private OnGenericMotionListener mOnGenericMotionListener;
3253
3254        private OnDragListener mOnDragListener;
3255
3256        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3257
3258        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3259    }
3260
3261    ListenerInfo mListenerInfo;
3262
3263    /**
3264     * The application environment this view lives in.
3265     * This field should be made private, so it is hidden from the SDK.
3266     * {@hide}
3267     */
3268    protected Context mContext;
3269
3270    private final Resources mResources;
3271
3272    private ScrollabilityCache mScrollCache;
3273
3274    private int[] mDrawableState = null;
3275
3276    @Deprecated
3277    private Outline mOutline;
3278    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3279
3280    /**
3281     * Animator that automatically runs based on state changes.
3282     */
3283    private StateListAnimator mStateListAnimator;
3284
3285    /**
3286     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3287     * the user may specify which view to go to next.
3288     */
3289    private int mNextFocusLeftId = View.NO_ID;
3290
3291    /**
3292     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3293     * the user may specify which view to go to next.
3294     */
3295    private int mNextFocusRightId = View.NO_ID;
3296
3297    /**
3298     * When this view has focus and the next focus is {@link #FOCUS_UP},
3299     * the user may specify which view to go to next.
3300     */
3301    private int mNextFocusUpId = View.NO_ID;
3302
3303    /**
3304     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3305     * the user may specify which view to go to next.
3306     */
3307    private int mNextFocusDownId = View.NO_ID;
3308
3309    /**
3310     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3311     * the user may specify which view to go to next.
3312     */
3313    int mNextFocusForwardId = View.NO_ID;
3314
3315    private CheckForLongPress mPendingCheckForLongPress;
3316    private CheckForTap mPendingCheckForTap = null;
3317    private PerformClick mPerformClick;
3318    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3319
3320    private UnsetPressedState mUnsetPressedState;
3321
3322    /**
3323     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3324     * up event while a long press is invoked as soon as the long press duration is reached, so
3325     * a long press could be performed before the tap is checked, in which case the tap's action
3326     * should not be invoked.
3327     */
3328    private boolean mHasPerformedLongPress;
3329
3330    /**
3331     * The minimum height of the view. We'll try our best to have the height
3332     * of this view to at least this amount.
3333     */
3334    @ViewDebug.ExportedProperty(category = "measurement")
3335    private int mMinHeight;
3336
3337    /**
3338     * The minimum width of the view. We'll try our best to have the width
3339     * of this view to at least this amount.
3340     */
3341    @ViewDebug.ExportedProperty(category = "measurement")
3342    private int mMinWidth;
3343
3344    /**
3345     * The delegate to handle touch events that are physically in this view
3346     * but should be handled by another view.
3347     */
3348    private TouchDelegate mTouchDelegate = null;
3349
3350    /**
3351     * Solid color to use as a background when creating the drawing cache. Enables
3352     * the cache to use 16 bit bitmaps instead of 32 bit.
3353     */
3354    private int mDrawingCacheBackgroundColor = 0;
3355
3356    /**
3357     * Special tree observer used when mAttachInfo is null.
3358     */
3359    private ViewTreeObserver mFloatingTreeObserver;
3360
3361    /**
3362     * Cache the touch slop from the context that created the view.
3363     */
3364    private int mTouchSlop;
3365
3366    /**
3367     * Object that handles automatic animation of view properties.
3368     */
3369    private ViewPropertyAnimator mAnimator = null;
3370
3371    /**
3372     * Flag indicating that a drag can cross window boundaries.  When
3373     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3374     * with this flag set, all visible applications will be able to participate
3375     * in the drag operation and receive the dragged content.
3376     *
3377     * @hide
3378     */
3379    public static final int DRAG_FLAG_GLOBAL = 1;
3380
3381    /**
3382     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3383     */
3384    private float mVerticalScrollFactor;
3385
3386    /**
3387     * Position of the vertical scroll bar.
3388     */
3389    private int mVerticalScrollbarPosition;
3390
3391    /**
3392     * Position the scroll bar at the default position as determined by the system.
3393     */
3394    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3395
3396    /**
3397     * Position the scroll bar along the left edge.
3398     */
3399    public static final int SCROLLBAR_POSITION_LEFT = 1;
3400
3401    /**
3402     * Position the scroll bar along the right edge.
3403     */
3404    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3405
3406    /**
3407     * Indicates that the view does not have a layer.
3408     *
3409     * @see #getLayerType()
3410     * @see #setLayerType(int, android.graphics.Paint)
3411     * @see #LAYER_TYPE_SOFTWARE
3412     * @see #LAYER_TYPE_HARDWARE
3413     */
3414    public static final int LAYER_TYPE_NONE = 0;
3415
3416    /**
3417     * <p>Indicates that the view has a software layer. A software layer is backed
3418     * by a bitmap and causes the view to be rendered using Android's software
3419     * rendering pipeline, even if hardware acceleration is enabled.</p>
3420     *
3421     * <p>Software layers have various usages:</p>
3422     * <p>When the application is not using hardware acceleration, a software layer
3423     * is useful to apply a specific color filter and/or blending mode and/or
3424     * translucency to a view and all its children.</p>
3425     * <p>When the application is using hardware acceleration, a software layer
3426     * is useful to render drawing primitives not supported by the hardware
3427     * accelerated pipeline. It can also be used to cache a complex view tree
3428     * into a texture and reduce the complexity of drawing operations. For instance,
3429     * when animating a complex view tree with a translation, a software layer can
3430     * be used to render the view tree only once.</p>
3431     * <p>Software layers should be avoided when the affected view tree updates
3432     * often. Every update will require to re-render the software layer, which can
3433     * potentially be slow (particularly when hardware acceleration is turned on
3434     * since the layer will have to be uploaded into a hardware texture after every
3435     * update.)</p>
3436     *
3437     * @see #getLayerType()
3438     * @see #setLayerType(int, android.graphics.Paint)
3439     * @see #LAYER_TYPE_NONE
3440     * @see #LAYER_TYPE_HARDWARE
3441     */
3442    public static final int LAYER_TYPE_SOFTWARE = 1;
3443
3444    /**
3445     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3446     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3447     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3448     * rendering pipeline, but only if hardware acceleration is turned on for the
3449     * view hierarchy. When hardware acceleration is turned off, hardware layers
3450     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3451     *
3452     * <p>A hardware layer is useful to apply a specific color filter and/or
3453     * blending mode and/or translucency to a view and all its children.</p>
3454     * <p>A hardware layer can be used to cache a complex view tree into a
3455     * texture and reduce the complexity of drawing operations. For instance,
3456     * when animating a complex view tree with a translation, a hardware layer can
3457     * be used to render the view tree only once.</p>
3458     * <p>A hardware layer can also be used to increase the rendering quality when
3459     * rotation transformations are applied on a view. It can also be used to
3460     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3461     *
3462     * @see #getLayerType()
3463     * @see #setLayerType(int, android.graphics.Paint)
3464     * @see #LAYER_TYPE_NONE
3465     * @see #LAYER_TYPE_SOFTWARE
3466     */
3467    public static final int LAYER_TYPE_HARDWARE = 2;
3468
3469    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3470            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3471            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3472            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3473    })
3474    int mLayerType = LAYER_TYPE_NONE;
3475    Paint mLayerPaint;
3476
3477    /**
3478     * Set to true when drawing cache is enabled and cannot be created.
3479     *
3480     * @hide
3481     */
3482    public boolean mCachingFailed;
3483    private Bitmap mDrawingCache;
3484    private Bitmap mUnscaledDrawingCache;
3485
3486    /**
3487     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3488     * <p>
3489     * When non-null and valid, this is expected to contain an up-to-date copy
3490     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3491     * cleanup.
3492     */
3493    final RenderNode mRenderNode;
3494
3495    /**
3496     * Set to true when the view is sending hover accessibility events because it
3497     * is the innermost hovered view.
3498     */
3499    private boolean mSendingHoverAccessibilityEvents;
3500
3501    /**
3502     * Delegate for injecting accessibility functionality.
3503     */
3504    AccessibilityDelegate mAccessibilityDelegate;
3505
3506    /**
3507     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3508     * and add/remove objects to/from the overlay directly through the Overlay methods.
3509     */
3510    ViewOverlay mOverlay;
3511
3512    /**
3513     * The currently active parent view for receiving delegated nested scrolling events.
3514     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3515     * by {@link #stopNestedScroll()} at the same point where we clear
3516     * requestDisallowInterceptTouchEvent.
3517     */
3518    private ViewParent mNestedScrollingParent;
3519
3520    /**
3521     * Consistency verifier for debugging purposes.
3522     * @hide
3523     */
3524    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3525            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3526                    new InputEventConsistencyVerifier(this, 0) : null;
3527
3528    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3529
3530    private int[] mTempNestedScrollConsumed;
3531
3532    /**
3533     * Simple constructor to use when creating a view from code.
3534     *
3535     * @param context The Context the view is running in, through which it can
3536     *        access the current theme, resources, etc.
3537     */
3538    public View(Context context) {
3539        mContext = context;
3540        mResources = context != null ? context.getResources() : null;
3541        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3542        // Set some flags defaults
3543        mPrivateFlags2 =
3544                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3545                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3546                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3547                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3548                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3549                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3550        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3551        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3552        mUserPaddingStart = UNDEFINED_PADDING;
3553        mUserPaddingEnd = UNDEFINED_PADDING;
3554        mRenderNode = RenderNode.create(getClass().getName());
3555
3556        if (!sCompatibilityDone && context != null) {
3557            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3558
3559            // Older apps may need this compatibility hack for measurement.
3560            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3561
3562            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3563            // of whether a layout was requested on that View.
3564            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3565
3566            // Older apps may need this to ignore the clip bounds
3567            sIgnoreClipBoundsForChildren = targetSdkVersion < L;
3568
3569            sCompatibilityDone = true;
3570        }
3571    }
3572
3573    /**
3574     * Constructor that is called when inflating a view from XML. This is called
3575     * when a view is being constructed from an XML file, supplying attributes
3576     * that were specified in the XML file. This version uses a default style of
3577     * 0, so the only attribute values applied are those in the Context's Theme
3578     * and the given AttributeSet.
3579     *
3580     * <p>
3581     * The method onFinishInflate() will be called after all children have been
3582     * added.
3583     *
3584     * @param context The Context the view is running in, through which it can
3585     *        access the current theme, resources, etc.
3586     * @param attrs The attributes of the XML tag that is inflating the view.
3587     * @see #View(Context, AttributeSet, int)
3588     */
3589    public View(Context context, AttributeSet attrs) {
3590        this(context, attrs, 0);
3591    }
3592
3593    /**
3594     * Perform inflation from XML and apply a class-specific base style from a
3595     * theme attribute. This constructor of View allows subclasses to use their
3596     * own base style when they are inflating. For example, a Button class's
3597     * constructor would call this version of the super class constructor and
3598     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3599     * allows the theme's button style to modify all of the base view attributes
3600     * (in particular its background) as well as the Button class's attributes.
3601     *
3602     * @param context The Context the view is running in, through which it can
3603     *        access the current theme, resources, etc.
3604     * @param attrs The attributes of the XML tag that is inflating the view.
3605     * @param defStyleAttr An attribute in the current theme that contains a
3606     *        reference to a style resource that supplies default values for
3607     *        the view. Can be 0 to not look for defaults.
3608     * @see #View(Context, AttributeSet)
3609     */
3610    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3611        this(context, attrs, defStyleAttr, 0);
3612    }
3613
3614    /**
3615     * Perform inflation from XML and apply a class-specific base style from a
3616     * theme attribute or style resource. This constructor of View allows
3617     * subclasses to use their own base style when they are inflating.
3618     * <p>
3619     * When determining the final value of a particular attribute, there are
3620     * four inputs that come into play:
3621     * <ol>
3622     * <li>Any attribute values in the given AttributeSet.
3623     * <li>The style resource specified in the AttributeSet (named "style").
3624     * <li>The default style specified by <var>defStyleAttr</var>.
3625     * <li>The default style specified by <var>defStyleRes</var>.
3626     * <li>The base values in this theme.
3627     * </ol>
3628     * <p>
3629     * Each of these inputs is considered in-order, with the first listed taking
3630     * precedence over the following ones. In other words, if in the
3631     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3632     * , then the button's text will <em>always</em> be black, regardless of
3633     * what is specified in any of the styles.
3634     *
3635     * @param context The Context the view is running in, through which it can
3636     *        access the current theme, resources, etc.
3637     * @param attrs The attributes of the XML tag that is inflating the view.
3638     * @param defStyleAttr An attribute in the current theme that contains a
3639     *        reference to a style resource that supplies default values for
3640     *        the view. Can be 0 to not look for defaults.
3641     * @param defStyleRes A resource identifier of a style resource that
3642     *        supplies default values for the view, used only if
3643     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3644     *        to not look for defaults.
3645     * @see #View(Context, AttributeSet, int)
3646     */
3647    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3648        this(context);
3649
3650        final TypedArray a = context.obtainStyledAttributes(
3651                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3652
3653        Drawable background = null;
3654
3655        int leftPadding = -1;
3656        int topPadding = -1;
3657        int rightPadding = -1;
3658        int bottomPadding = -1;
3659        int startPadding = UNDEFINED_PADDING;
3660        int endPadding = UNDEFINED_PADDING;
3661
3662        int padding = -1;
3663
3664        int viewFlagValues = 0;
3665        int viewFlagMasks = 0;
3666
3667        boolean setScrollContainer = false;
3668
3669        int x = 0;
3670        int y = 0;
3671
3672        float tx = 0;
3673        float ty = 0;
3674        float tz = 0;
3675        float elevation = 0;
3676        float rotation = 0;
3677        float rotationX = 0;
3678        float rotationY = 0;
3679        float sx = 1f;
3680        float sy = 1f;
3681        boolean transformSet = false;
3682
3683        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3684        int overScrollMode = mOverScrollMode;
3685        boolean initializeScrollbars = false;
3686
3687        boolean startPaddingDefined = false;
3688        boolean endPaddingDefined = false;
3689        boolean leftPaddingDefined = false;
3690        boolean rightPaddingDefined = false;
3691
3692        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3693
3694        final int N = a.getIndexCount();
3695        for (int i = 0; i < N; i++) {
3696            int attr = a.getIndex(i);
3697            switch (attr) {
3698                case com.android.internal.R.styleable.View_background:
3699                    background = a.getDrawable(attr);
3700                    break;
3701                case com.android.internal.R.styleable.View_padding:
3702                    padding = a.getDimensionPixelSize(attr, -1);
3703                    mUserPaddingLeftInitial = padding;
3704                    mUserPaddingRightInitial = padding;
3705                    leftPaddingDefined = true;
3706                    rightPaddingDefined = true;
3707                    break;
3708                 case com.android.internal.R.styleable.View_paddingLeft:
3709                    leftPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingLeftInitial = leftPadding;
3711                    leftPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingTop:
3714                    topPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingRight:
3717                    rightPadding = a.getDimensionPixelSize(attr, -1);
3718                    mUserPaddingRightInitial = rightPadding;
3719                    rightPaddingDefined = true;
3720                    break;
3721                case com.android.internal.R.styleable.View_paddingBottom:
3722                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3723                    break;
3724                case com.android.internal.R.styleable.View_paddingStart:
3725                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3726                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3727                    break;
3728                case com.android.internal.R.styleable.View_paddingEnd:
3729                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3730                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3731                    break;
3732                case com.android.internal.R.styleable.View_scrollX:
3733                    x = a.getDimensionPixelOffset(attr, 0);
3734                    break;
3735                case com.android.internal.R.styleable.View_scrollY:
3736                    y = a.getDimensionPixelOffset(attr, 0);
3737                    break;
3738                case com.android.internal.R.styleable.View_alpha:
3739                    setAlpha(a.getFloat(attr, 1f));
3740                    break;
3741                case com.android.internal.R.styleable.View_transformPivotX:
3742                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3743                    break;
3744                case com.android.internal.R.styleable.View_transformPivotY:
3745                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3746                    break;
3747                case com.android.internal.R.styleable.View_translationX:
3748                    tx = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_translationY:
3752                    ty = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_translationZ:
3756                    tz = a.getDimensionPixelOffset(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_elevation:
3760                    elevation = a.getDimensionPixelOffset(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotation:
3764                    rotation = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_rotationX:
3768                    rotationX = a.getFloat(attr, 0);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_rotationY:
3772                    rotationY = a.getFloat(attr, 0);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_scaleX:
3776                    sx = a.getFloat(attr, 1f);
3777                    transformSet = true;
3778                    break;
3779                case com.android.internal.R.styleable.View_scaleY:
3780                    sy = a.getFloat(attr, 1f);
3781                    transformSet = true;
3782                    break;
3783                case com.android.internal.R.styleable.View_id:
3784                    mID = a.getResourceId(attr, NO_ID);
3785                    break;
3786                case com.android.internal.R.styleable.View_tag:
3787                    mTag = a.getText(attr);
3788                    break;
3789                case com.android.internal.R.styleable.View_fitsSystemWindows:
3790                    if (a.getBoolean(attr, false)) {
3791                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3792                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3793                    }
3794                    break;
3795                case com.android.internal.R.styleable.View_focusable:
3796                    if (a.getBoolean(attr, false)) {
3797                        viewFlagValues |= FOCUSABLE;
3798                        viewFlagMasks |= FOCUSABLE_MASK;
3799                    }
3800                    break;
3801                case com.android.internal.R.styleable.View_focusableInTouchMode:
3802                    if (a.getBoolean(attr, false)) {
3803                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3804                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3805                    }
3806                    break;
3807                case com.android.internal.R.styleable.View_clickable:
3808                    if (a.getBoolean(attr, false)) {
3809                        viewFlagValues |= CLICKABLE;
3810                        viewFlagMasks |= CLICKABLE;
3811                    }
3812                    break;
3813                case com.android.internal.R.styleable.View_longClickable:
3814                    if (a.getBoolean(attr, false)) {
3815                        viewFlagValues |= LONG_CLICKABLE;
3816                        viewFlagMasks |= LONG_CLICKABLE;
3817                    }
3818                    break;
3819                case com.android.internal.R.styleable.View_saveEnabled:
3820                    if (!a.getBoolean(attr, true)) {
3821                        viewFlagValues |= SAVE_DISABLED;
3822                        viewFlagMasks |= SAVE_DISABLED_MASK;
3823                    }
3824                    break;
3825                case com.android.internal.R.styleable.View_duplicateParentState:
3826                    if (a.getBoolean(attr, false)) {
3827                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3828                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3829                    }
3830                    break;
3831                case com.android.internal.R.styleable.View_visibility:
3832                    final int visibility = a.getInt(attr, 0);
3833                    if (visibility != 0) {
3834                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3835                        viewFlagMasks |= VISIBILITY_MASK;
3836                    }
3837                    break;
3838                case com.android.internal.R.styleable.View_layoutDirection:
3839                    // Clear any layout direction flags (included resolved bits) already set
3840                    mPrivateFlags2 &=
3841                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3842                    // Set the layout direction flags depending on the value of the attribute
3843                    final int layoutDirection = a.getInt(attr, -1);
3844                    final int value = (layoutDirection != -1) ?
3845                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3846                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3847                    break;
3848                case com.android.internal.R.styleable.View_drawingCacheQuality:
3849                    final int cacheQuality = a.getInt(attr, 0);
3850                    if (cacheQuality != 0) {
3851                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3852                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3853                    }
3854                    break;
3855                case com.android.internal.R.styleable.View_contentDescription:
3856                    setContentDescription(a.getString(attr));
3857                    break;
3858                case com.android.internal.R.styleable.View_labelFor:
3859                    setLabelFor(a.getResourceId(attr, NO_ID));
3860                    break;
3861                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3862                    if (!a.getBoolean(attr, true)) {
3863                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3864                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3865                    }
3866                    break;
3867                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3868                    if (!a.getBoolean(attr, true)) {
3869                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3870                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3871                    }
3872                    break;
3873                case R.styleable.View_scrollbars:
3874                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3875                    if (scrollbars != SCROLLBARS_NONE) {
3876                        viewFlagValues |= scrollbars;
3877                        viewFlagMasks |= SCROLLBARS_MASK;
3878                        initializeScrollbars = true;
3879                    }
3880                    break;
3881                //noinspection deprecation
3882                case R.styleable.View_fadingEdge:
3883                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3884                        // Ignore the attribute starting with ICS
3885                        break;
3886                    }
3887                    // With builds < ICS, fall through and apply fading edges
3888                case R.styleable.View_requiresFadingEdge:
3889                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3890                    if (fadingEdge != FADING_EDGE_NONE) {
3891                        viewFlagValues |= fadingEdge;
3892                        viewFlagMasks |= FADING_EDGE_MASK;
3893                        initializeFadingEdgeInternal(a);
3894                    }
3895                    break;
3896                case R.styleable.View_scrollbarStyle:
3897                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3898                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3899                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3900                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3901                    }
3902                    break;
3903                case R.styleable.View_isScrollContainer:
3904                    setScrollContainer = true;
3905                    if (a.getBoolean(attr, false)) {
3906                        setScrollContainer(true);
3907                    }
3908                    break;
3909                case com.android.internal.R.styleable.View_keepScreenOn:
3910                    if (a.getBoolean(attr, false)) {
3911                        viewFlagValues |= KEEP_SCREEN_ON;
3912                        viewFlagMasks |= KEEP_SCREEN_ON;
3913                    }
3914                    break;
3915                case R.styleable.View_filterTouchesWhenObscured:
3916                    if (a.getBoolean(attr, false)) {
3917                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3918                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3919                    }
3920                    break;
3921                case R.styleable.View_nextFocusLeft:
3922                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3923                    break;
3924                case R.styleable.View_nextFocusRight:
3925                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3926                    break;
3927                case R.styleable.View_nextFocusUp:
3928                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3929                    break;
3930                case R.styleable.View_nextFocusDown:
3931                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3932                    break;
3933                case R.styleable.View_nextFocusForward:
3934                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3935                    break;
3936                case R.styleable.View_minWidth:
3937                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3938                    break;
3939                case R.styleable.View_minHeight:
3940                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3941                    break;
3942                case R.styleable.View_onClick:
3943                    if (context.isRestricted()) {
3944                        throw new IllegalStateException("The android:onClick attribute cannot "
3945                                + "be used within a restricted context");
3946                    }
3947
3948                    final String handlerName = a.getString(attr);
3949                    if (handlerName != null) {
3950                        setOnClickListener(new OnClickListener() {
3951                            private Method mHandler;
3952
3953                            public void onClick(View v) {
3954                                if (mHandler == null) {
3955                                    try {
3956                                        mHandler = getContext().getClass().getMethod(handlerName,
3957                                                View.class);
3958                                    } catch (NoSuchMethodException e) {
3959                                        int id = getId();
3960                                        String idText = id == NO_ID ? "" : " with id '"
3961                                                + getContext().getResources().getResourceEntryName(
3962                                                    id) + "'";
3963                                        throw new IllegalStateException("Could not find a method " +
3964                                                handlerName + "(View) in the activity "
3965                                                + getContext().getClass() + " for onClick handler"
3966                                                + " on view " + View.this.getClass() + idText, e);
3967                                    }
3968                                }
3969
3970                                try {
3971                                    mHandler.invoke(getContext(), View.this);
3972                                } catch (IllegalAccessException e) {
3973                                    throw new IllegalStateException("Could not execute non "
3974                                            + "public method of the activity", e);
3975                                } catch (InvocationTargetException e) {
3976                                    throw new IllegalStateException("Could not execute "
3977                                            + "method of the activity", e);
3978                                }
3979                            }
3980                        });
3981                    }
3982                    break;
3983                case R.styleable.View_overScrollMode:
3984                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3985                    break;
3986                case R.styleable.View_verticalScrollbarPosition:
3987                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3988                    break;
3989                case R.styleable.View_layerType:
3990                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3991                    break;
3992                case R.styleable.View_textDirection:
3993                    // Clear any text direction flag already set
3994                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3995                    // Set the text direction flags depending on the value of the attribute
3996                    final int textDirection = a.getInt(attr, -1);
3997                    if (textDirection != -1) {
3998                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3999                    }
4000                    break;
4001                case R.styleable.View_textAlignment:
4002                    // Clear any text alignment flag already set
4003                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4004                    // Set the text alignment flag depending on the value of the attribute
4005                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4006                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4007                    break;
4008                case R.styleable.View_importantForAccessibility:
4009                    setImportantForAccessibility(a.getInt(attr,
4010                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4011                    break;
4012                case R.styleable.View_accessibilityLiveRegion:
4013                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4014                    break;
4015                case R.styleable.View_transitionName:
4016                    setTransitionName(a.getString(attr));
4017                    break;
4018                case R.styleable.View_nestedScrollingEnabled:
4019                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4020                    break;
4021                case R.styleable.View_stateListAnimator:
4022                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4023                            a.getResourceId(attr, 0)));
4024                    break;
4025                case R.styleable.View_backgroundTint:
4026                    // This will get applied later during setBackground().
4027                    mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint);
4028                    mHasBackgroundTint = true;
4029                    break;
4030                case R.styleable.View_backgroundTintMode:
4031                    // This will get applied later during setBackground().
4032                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4033                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4034                    break;
4035            }
4036        }
4037
4038        setOverScrollMode(overScrollMode);
4039
4040        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4041        // the resolved layout direction). Those cached values will be used later during padding
4042        // resolution.
4043        mUserPaddingStart = startPadding;
4044        mUserPaddingEnd = endPadding;
4045
4046        if (background != null) {
4047            setBackground(background);
4048        }
4049
4050        // setBackground above will record that padding is currently provided by the background.
4051        // If we have padding specified via xml, record that here instead and use it.
4052        mLeftPaddingDefined = leftPaddingDefined;
4053        mRightPaddingDefined = rightPaddingDefined;
4054
4055        if (padding >= 0) {
4056            leftPadding = padding;
4057            topPadding = padding;
4058            rightPadding = padding;
4059            bottomPadding = padding;
4060            mUserPaddingLeftInitial = padding;
4061            mUserPaddingRightInitial = padding;
4062        }
4063
4064        if (isRtlCompatibilityMode()) {
4065            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4066            // left / right padding are used if defined (meaning here nothing to do). If they are not
4067            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4068            // start / end and resolve them as left / right (layout direction is not taken into account).
4069            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4070            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4071            // defined.
4072            if (!mLeftPaddingDefined && startPaddingDefined) {
4073                leftPadding = startPadding;
4074            }
4075            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4076            if (!mRightPaddingDefined && endPaddingDefined) {
4077                rightPadding = endPadding;
4078            }
4079            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4080        } else {
4081            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4082            // values defined. Otherwise, left /right values are used.
4083            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4084            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4085            // defined.
4086            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4087
4088            if (mLeftPaddingDefined && !hasRelativePadding) {
4089                mUserPaddingLeftInitial = leftPadding;
4090            }
4091            if (mRightPaddingDefined && !hasRelativePadding) {
4092                mUserPaddingRightInitial = rightPadding;
4093            }
4094        }
4095
4096        internalSetPadding(
4097                mUserPaddingLeftInitial,
4098                topPadding >= 0 ? topPadding : mPaddingTop,
4099                mUserPaddingRightInitial,
4100                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4101
4102        if (viewFlagMasks != 0) {
4103            setFlags(viewFlagValues, viewFlagMasks);
4104        }
4105
4106        if (initializeScrollbars) {
4107            initializeScrollbarsInternal(a);
4108        }
4109
4110        a.recycle();
4111
4112        // Needs to be called after mViewFlags is set
4113        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4114            recomputePadding();
4115        }
4116
4117        if (x != 0 || y != 0) {
4118            scrollTo(x, y);
4119        }
4120
4121        if (transformSet) {
4122            setTranslationX(tx);
4123            setTranslationY(ty);
4124            setTranslationZ(tz);
4125            setElevation(elevation);
4126            setRotation(rotation);
4127            setRotationX(rotationX);
4128            setRotationY(rotationY);
4129            setScaleX(sx);
4130            setScaleY(sy);
4131        }
4132
4133        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4134            setScrollContainer(true);
4135        }
4136
4137        computeOpaqueFlags();
4138    }
4139
4140    /**
4141     * Non-public constructor for use in testing
4142     */
4143    View() {
4144        mResources = null;
4145        mRenderNode = RenderNode.create(getClass().getName());
4146    }
4147
4148    public String toString() {
4149        StringBuilder out = new StringBuilder(128);
4150        out.append(getClass().getName());
4151        out.append('{');
4152        out.append(Integer.toHexString(System.identityHashCode(this)));
4153        out.append(' ');
4154        switch (mViewFlags&VISIBILITY_MASK) {
4155            case VISIBLE: out.append('V'); break;
4156            case INVISIBLE: out.append('I'); break;
4157            case GONE: out.append('G'); break;
4158            default: out.append('.'); break;
4159        }
4160        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4161        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4162        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4163        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4164        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4165        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4166        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4167        out.append(' ');
4168        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4169        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4170        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4171        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4172            out.append('p');
4173        } else {
4174            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4175        }
4176        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4177        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4178        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4179        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4180        out.append(' ');
4181        out.append(mLeft);
4182        out.append(',');
4183        out.append(mTop);
4184        out.append('-');
4185        out.append(mRight);
4186        out.append(',');
4187        out.append(mBottom);
4188        final int id = getId();
4189        if (id != NO_ID) {
4190            out.append(" #");
4191            out.append(Integer.toHexString(id));
4192            final Resources r = mResources;
4193            if (Resources.resourceHasPackage(id) && r != null) {
4194                try {
4195                    String pkgname;
4196                    switch (id&0xff000000) {
4197                        case 0x7f000000:
4198                            pkgname="app";
4199                            break;
4200                        case 0x01000000:
4201                            pkgname="android";
4202                            break;
4203                        default:
4204                            pkgname = r.getResourcePackageName(id);
4205                            break;
4206                    }
4207                    String typename = r.getResourceTypeName(id);
4208                    String entryname = r.getResourceEntryName(id);
4209                    out.append(" ");
4210                    out.append(pkgname);
4211                    out.append(":");
4212                    out.append(typename);
4213                    out.append("/");
4214                    out.append(entryname);
4215                } catch (Resources.NotFoundException e) {
4216                }
4217            }
4218        }
4219        out.append("}");
4220        return out.toString();
4221    }
4222
4223    /**
4224     * <p>
4225     * Initializes the fading edges from a given set of styled attributes. This
4226     * method should be called by subclasses that need fading edges and when an
4227     * instance of these subclasses is created programmatically rather than
4228     * being inflated from XML. This method is automatically called when the XML
4229     * is inflated.
4230     * </p>
4231     *
4232     * @param a the styled attributes set to initialize the fading edges from
4233     */
4234    protected void initializeFadingEdge(TypedArray a) {
4235        // This method probably shouldn't have been included in the SDK to begin with.
4236        // It relies on 'a' having been initialized using an attribute filter array that is
4237        // not publicly available to the SDK. The old method has been renamed
4238        // to initializeFadingEdgeInternal and hidden for framework use only;
4239        // this one initializes using defaults to make it safe to call for apps.
4240
4241        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4242
4243        initializeFadingEdgeInternal(arr);
4244
4245        arr.recycle();
4246    }
4247
4248    /**
4249     * <p>
4250     * Initializes the fading edges from a given set of styled attributes. This
4251     * method should be called by subclasses that need fading edges and when an
4252     * instance of these subclasses is created programmatically rather than
4253     * being inflated from XML. This method is automatically called when the XML
4254     * is inflated.
4255     * </p>
4256     *
4257     * @param a the styled attributes set to initialize the fading edges from
4258     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4259     */
4260    protected void initializeFadingEdgeInternal(TypedArray a) {
4261        initScrollCache();
4262
4263        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4264                R.styleable.View_fadingEdgeLength,
4265                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4266    }
4267
4268    /**
4269     * Returns the size of the vertical faded edges used to indicate that more
4270     * content in this view is visible.
4271     *
4272     * @return The size in pixels of the vertical faded edge or 0 if vertical
4273     *         faded edges are not enabled for this view.
4274     * @attr ref android.R.styleable#View_fadingEdgeLength
4275     */
4276    public int getVerticalFadingEdgeLength() {
4277        if (isVerticalFadingEdgeEnabled()) {
4278            ScrollabilityCache cache = mScrollCache;
4279            if (cache != null) {
4280                return cache.fadingEdgeLength;
4281            }
4282        }
4283        return 0;
4284    }
4285
4286    /**
4287     * Set the size of the faded edge used to indicate that more content in this
4288     * view is available.  Will not change whether the fading edge is enabled; use
4289     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4290     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4291     * for the vertical or horizontal fading edges.
4292     *
4293     * @param length The size in pixels of the faded edge used to indicate that more
4294     *        content in this view is visible.
4295     */
4296    public void setFadingEdgeLength(int length) {
4297        initScrollCache();
4298        mScrollCache.fadingEdgeLength = length;
4299    }
4300
4301    /**
4302     * Returns the size of the horizontal faded edges used to indicate that more
4303     * content in this view is visible.
4304     *
4305     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4306     *         faded edges are not enabled for this view.
4307     * @attr ref android.R.styleable#View_fadingEdgeLength
4308     */
4309    public int getHorizontalFadingEdgeLength() {
4310        if (isHorizontalFadingEdgeEnabled()) {
4311            ScrollabilityCache cache = mScrollCache;
4312            if (cache != null) {
4313                return cache.fadingEdgeLength;
4314            }
4315        }
4316        return 0;
4317    }
4318
4319    /**
4320     * Returns the width of the vertical scrollbar.
4321     *
4322     * @return The width in pixels of the vertical scrollbar or 0 if there
4323     *         is no vertical scrollbar.
4324     */
4325    public int getVerticalScrollbarWidth() {
4326        ScrollabilityCache cache = mScrollCache;
4327        if (cache != null) {
4328            ScrollBarDrawable scrollBar = cache.scrollBar;
4329            if (scrollBar != null) {
4330                int size = scrollBar.getSize(true);
4331                if (size <= 0) {
4332                    size = cache.scrollBarSize;
4333                }
4334                return size;
4335            }
4336            return 0;
4337        }
4338        return 0;
4339    }
4340
4341    /**
4342     * Returns the height of the horizontal scrollbar.
4343     *
4344     * @return The height in pixels of the horizontal scrollbar or 0 if
4345     *         there is no horizontal scrollbar.
4346     */
4347    protected int getHorizontalScrollbarHeight() {
4348        ScrollabilityCache cache = mScrollCache;
4349        if (cache != null) {
4350            ScrollBarDrawable scrollBar = cache.scrollBar;
4351            if (scrollBar != null) {
4352                int size = scrollBar.getSize(false);
4353                if (size <= 0) {
4354                    size = cache.scrollBarSize;
4355                }
4356                return size;
4357            }
4358            return 0;
4359        }
4360        return 0;
4361    }
4362
4363    /**
4364     * <p>
4365     * Initializes the scrollbars from a given set of styled attributes. This
4366     * method should be called by subclasses that need scrollbars and when an
4367     * instance of these subclasses is created programmatically rather than
4368     * being inflated from XML. This method is automatically called when the XML
4369     * is inflated.
4370     * </p>
4371     *
4372     * @param a the styled attributes set to initialize the scrollbars from
4373     */
4374    protected void initializeScrollbars(TypedArray a) {
4375        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4376        // using the View filter array which is not available to the SDK. As such, internal
4377        // framework usage now uses initializeScrollbarsInternal and we grab a default
4378        // TypedArray with the right filter instead here.
4379        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4380
4381        initializeScrollbarsInternal(arr);
4382
4383        // We ignored the method parameter. Recycle the one we actually did use.
4384        arr.recycle();
4385    }
4386
4387    /**
4388     * <p>
4389     * Initializes the scrollbars from a given set of styled attributes. This
4390     * method should be called by subclasses that need scrollbars and when an
4391     * instance of these subclasses is created programmatically rather than
4392     * being inflated from XML. This method is automatically called when the XML
4393     * is inflated.
4394     * </p>
4395     *
4396     * @param a the styled attributes set to initialize the scrollbars from
4397     * @hide
4398     */
4399    protected void initializeScrollbarsInternal(TypedArray a) {
4400        initScrollCache();
4401
4402        final ScrollabilityCache scrollabilityCache = mScrollCache;
4403
4404        if (scrollabilityCache.scrollBar == null) {
4405            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4406        }
4407
4408        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4409
4410        if (!fadeScrollbars) {
4411            scrollabilityCache.state = ScrollabilityCache.ON;
4412        }
4413        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4414
4415
4416        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4417                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4418                        .getScrollBarFadeDuration());
4419        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4420                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4421                ViewConfiguration.getScrollDefaultDelay());
4422
4423
4424        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4425                com.android.internal.R.styleable.View_scrollbarSize,
4426                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4427
4428        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4429        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4430
4431        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4432        if (thumb != null) {
4433            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4434        }
4435
4436        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4437                false);
4438        if (alwaysDraw) {
4439            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4440        }
4441
4442        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4443        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4444
4445        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4446        if (thumb != null) {
4447            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4448        }
4449
4450        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4451                false);
4452        if (alwaysDraw) {
4453            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4454        }
4455
4456        // Apply layout direction to the new Drawables if needed
4457        final int layoutDirection = getLayoutDirection();
4458        if (track != null) {
4459            track.setLayoutDirection(layoutDirection);
4460        }
4461        if (thumb != null) {
4462            thumb.setLayoutDirection(layoutDirection);
4463        }
4464
4465        // Re-apply user/background padding so that scrollbar(s) get added
4466        resolvePadding();
4467    }
4468
4469    /**
4470     * <p>
4471     * Initalizes the scrollability cache if necessary.
4472     * </p>
4473     */
4474    private void initScrollCache() {
4475        if (mScrollCache == null) {
4476            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4477        }
4478    }
4479
4480    private ScrollabilityCache getScrollCache() {
4481        initScrollCache();
4482        return mScrollCache;
4483    }
4484
4485    /**
4486     * Set the position of the vertical scroll bar. Should be one of
4487     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4488     * {@link #SCROLLBAR_POSITION_RIGHT}.
4489     *
4490     * @param position Where the vertical scroll bar should be positioned.
4491     */
4492    public void setVerticalScrollbarPosition(int position) {
4493        if (mVerticalScrollbarPosition != position) {
4494            mVerticalScrollbarPosition = position;
4495            computeOpaqueFlags();
4496            resolvePadding();
4497        }
4498    }
4499
4500    /**
4501     * @return The position where the vertical scroll bar will show, if applicable.
4502     * @see #setVerticalScrollbarPosition(int)
4503     */
4504    public int getVerticalScrollbarPosition() {
4505        return mVerticalScrollbarPosition;
4506    }
4507
4508    ListenerInfo getListenerInfo() {
4509        if (mListenerInfo != null) {
4510            return mListenerInfo;
4511        }
4512        mListenerInfo = new ListenerInfo();
4513        return mListenerInfo;
4514    }
4515
4516    /**
4517     * Register a callback to be invoked when focus of this view changed.
4518     *
4519     * @param l The callback that will run.
4520     */
4521    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4522        getListenerInfo().mOnFocusChangeListener = l;
4523    }
4524
4525    /**
4526     * Add a listener that will be called when the bounds of the view change due to
4527     * layout processing.
4528     *
4529     * @param listener The listener that will be called when layout bounds change.
4530     */
4531    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4532        ListenerInfo li = getListenerInfo();
4533        if (li.mOnLayoutChangeListeners == null) {
4534            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4535        }
4536        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4537            li.mOnLayoutChangeListeners.add(listener);
4538        }
4539    }
4540
4541    /**
4542     * Remove a listener for layout changes.
4543     *
4544     * @param listener The listener for layout bounds change.
4545     */
4546    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4547        ListenerInfo li = mListenerInfo;
4548        if (li == null || li.mOnLayoutChangeListeners == null) {
4549            return;
4550        }
4551        li.mOnLayoutChangeListeners.remove(listener);
4552    }
4553
4554    /**
4555     * Add a listener for attach state changes.
4556     *
4557     * This listener will be called whenever this view is attached or detached
4558     * from a window. Remove the listener using
4559     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4560     *
4561     * @param listener Listener to attach
4562     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4563     */
4564    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4565        ListenerInfo li = getListenerInfo();
4566        if (li.mOnAttachStateChangeListeners == null) {
4567            li.mOnAttachStateChangeListeners
4568                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4569        }
4570        li.mOnAttachStateChangeListeners.add(listener);
4571    }
4572
4573    /**
4574     * Remove a listener for attach state changes. The listener will receive no further
4575     * notification of window attach/detach events.
4576     *
4577     * @param listener Listener to remove
4578     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4579     */
4580    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4581        ListenerInfo li = mListenerInfo;
4582        if (li == null || li.mOnAttachStateChangeListeners == null) {
4583            return;
4584        }
4585        li.mOnAttachStateChangeListeners.remove(listener);
4586    }
4587
4588    /**
4589     * Returns the focus-change callback registered for this view.
4590     *
4591     * @return The callback, or null if one is not registered.
4592     */
4593    public OnFocusChangeListener getOnFocusChangeListener() {
4594        ListenerInfo li = mListenerInfo;
4595        return li != null ? li.mOnFocusChangeListener : null;
4596    }
4597
4598    /**
4599     * Register a callback to be invoked when this view is clicked. If this view is not
4600     * clickable, it becomes clickable.
4601     *
4602     * @param l The callback that will run
4603     *
4604     * @see #setClickable(boolean)
4605     */
4606    public void setOnClickListener(OnClickListener l) {
4607        if (!isClickable()) {
4608            setClickable(true);
4609        }
4610        getListenerInfo().mOnClickListener = l;
4611    }
4612
4613    /**
4614     * Return whether this view has an attached OnClickListener.  Returns
4615     * true if there is a listener, false if there is none.
4616     */
4617    public boolean hasOnClickListeners() {
4618        ListenerInfo li = mListenerInfo;
4619        return (li != null && li.mOnClickListener != null);
4620    }
4621
4622    /**
4623     * Register a callback to be invoked when this view is clicked and held. If this view is not
4624     * long clickable, it becomes long clickable.
4625     *
4626     * @param l The callback that will run
4627     *
4628     * @see #setLongClickable(boolean)
4629     */
4630    public void setOnLongClickListener(OnLongClickListener l) {
4631        if (!isLongClickable()) {
4632            setLongClickable(true);
4633        }
4634        getListenerInfo().mOnLongClickListener = l;
4635    }
4636
4637    /**
4638     * Register a callback to be invoked when the context menu for this view is
4639     * being built. If this view is not long clickable, it becomes long clickable.
4640     *
4641     * @param l The callback that will run
4642     *
4643     */
4644    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4645        if (!isLongClickable()) {
4646            setLongClickable(true);
4647        }
4648        getListenerInfo().mOnCreateContextMenuListener = l;
4649    }
4650
4651    /**
4652     * Call this view's OnClickListener, if it is defined.  Performs all normal
4653     * actions associated with clicking: reporting accessibility event, playing
4654     * a sound, etc.
4655     *
4656     * @return True there was an assigned OnClickListener that was called, false
4657     *         otherwise is returned.
4658     */
4659    public boolean performClick() {
4660        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4661
4662        ListenerInfo li = mListenerInfo;
4663        if (li != null && li.mOnClickListener != null) {
4664            playSoundEffect(SoundEffectConstants.CLICK);
4665            li.mOnClickListener.onClick(this);
4666            return true;
4667        }
4668
4669        return false;
4670    }
4671
4672    /**
4673     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4674     * this only calls the listener, and does not do any associated clicking
4675     * actions like reporting an accessibility event.
4676     *
4677     * @return True there was an assigned OnClickListener that was called, false
4678     *         otherwise is returned.
4679     */
4680    public boolean callOnClick() {
4681        ListenerInfo li = mListenerInfo;
4682        if (li != null && li.mOnClickListener != null) {
4683            li.mOnClickListener.onClick(this);
4684            return true;
4685        }
4686        return false;
4687    }
4688
4689    /**
4690     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4691     * OnLongClickListener did not consume the event.
4692     *
4693     * @return True if one of the above receivers consumed the event, false otherwise.
4694     */
4695    public boolean performLongClick() {
4696        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4697
4698        boolean handled = false;
4699        ListenerInfo li = mListenerInfo;
4700        if (li != null && li.mOnLongClickListener != null) {
4701            handled = li.mOnLongClickListener.onLongClick(View.this);
4702        }
4703        if (!handled) {
4704            handled = showContextMenu();
4705        }
4706        if (handled) {
4707            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4708        }
4709        return handled;
4710    }
4711
4712    /**
4713     * Performs button-related actions during a touch down event.
4714     *
4715     * @param event The event.
4716     * @return True if the down was consumed.
4717     *
4718     * @hide
4719     */
4720    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4721        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4722            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4723                return true;
4724            }
4725        }
4726        return false;
4727    }
4728
4729    /**
4730     * Bring up the context menu for this view.
4731     *
4732     * @return Whether a context menu was displayed.
4733     */
4734    public boolean showContextMenu() {
4735        return getParent().showContextMenuForChild(this);
4736    }
4737
4738    /**
4739     * Bring up the context menu for this view, referring to the item under the specified point.
4740     *
4741     * @param x The referenced x coordinate.
4742     * @param y The referenced y coordinate.
4743     * @param metaState The keyboard modifiers that were pressed.
4744     * @return Whether a context menu was displayed.
4745     *
4746     * @hide
4747     */
4748    public boolean showContextMenu(float x, float y, int metaState) {
4749        return showContextMenu();
4750    }
4751
4752    /**
4753     * Start an action mode.
4754     *
4755     * @param callback Callback that will control the lifecycle of the action mode
4756     * @return The new action mode if it is started, null otherwise
4757     *
4758     * @see ActionMode
4759     */
4760    public ActionMode startActionMode(ActionMode.Callback callback) {
4761        ViewParent parent = getParent();
4762        if (parent == null) return null;
4763        return parent.startActionModeForChild(this, callback);
4764    }
4765
4766    /**
4767     * Register a callback to be invoked when a hardware key is pressed in this view.
4768     * Key presses in software input methods will generally not trigger the methods of
4769     * this listener.
4770     * @param l the key listener to attach to this view
4771     */
4772    public void setOnKeyListener(OnKeyListener l) {
4773        getListenerInfo().mOnKeyListener = l;
4774    }
4775
4776    /**
4777     * Register a callback to be invoked when a touch event is sent to this view.
4778     * @param l the touch listener to attach to this view
4779     */
4780    public void setOnTouchListener(OnTouchListener l) {
4781        getListenerInfo().mOnTouchListener = l;
4782    }
4783
4784    /**
4785     * Register a callback to be invoked when a generic motion event is sent to this view.
4786     * @param l the generic motion listener to attach to this view
4787     */
4788    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4789        getListenerInfo().mOnGenericMotionListener = l;
4790    }
4791
4792    /**
4793     * Register a callback to be invoked when a hover event is sent to this view.
4794     * @param l the hover listener to attach to this view
4795     */
4796    public void setOnHoverListener(OnHoverListener l) {
4797        getListenerInfo().mOnHoverListener = l;
4798    }
4799
4800    /**
4801     * Register a drag event listener callback object for this View. The parameter is
4802     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4803     * View, the system calls the
4804     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4805     * @param l An implementation of {@link android.view.View.OnDragListener}.
4806     */
4807    public void setOnDragListener(OnDragListener l) {
4808        getListenerInfo().mOnDragListener = l;
4809    }
4810
4811    /**
4812     * Give this view focus. This will cause
4813     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4814     *
4815     * Note: this does not check whether this {@link View} should get focus, it just
4816     * gives it focus no matter what.  It should only be called internally by framework
4817     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4818     *
4819     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4820     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4821     *        focus moved when requestFocus() is called. It may not always
4822     *        apply, in which case use the default View.FOCUS_DOWN.
4823     * @param previouslyFocusedRect The rectangle of the view that had focus
4824     *        prior in this View's coordinate system.
4825     */
4826    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4827        if (DBG) {
4828            System.out.println(this + " requestFocus()");
4829        }
4830
4831        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4832            mPrivateFlags |= PFLAG_FOCUSED;
4833
4834            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4835
4836            if (mParent != null) {
4837                mParent.requestChildFocus(this, this);
4838            }
4839
4840            if (mAttachInfo != null) {
4841                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4842            }
4843
4844            onFocusChanged(true, direction, previouslyFocusedRect);
4845            manageFocusHotspot(true, oldFocus);
4846            refreshDrawableState();
4847        }
4848    }
4849
4850    /**
4851     * Forwards focus information to the background drawable, if necessary. When
4852     * the view is gaining focus, <code>v</code> is the previous focus holder.
4853     * When the view is losing focus, <code>v</code> is the next focus holder.
4854     *
4855     * @param focused whether this view is focused
4856     * @param v previous or the next focus holder, or null if none
4857     */
4858    private void manageFocusHotspot(boolean focused, View v) {
4859        final Rect r = new Rect();
4860        if (!focused && v != null && mAttachInfo != null) {
4861            v.getBoundsOnScreen(r);
4862            final int[] location = mAttachInfo.mTmpLocation;
4863            getLocationOnScreen(location);
4864            r.offset(-location[0], -location[1]);
4865        } else {
4866            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4867        }
4868
4869        final float x = r.exactCenterX();
4870        final float y = r.exactCenterY();
4871        drawableHotspotChanged(x, y);
4872    }
4873
4874    /**
4875     * Request that a rectangle of this view be visible on the screen,
4876     * scrolling if necessary just enough.
4877     *
4878     * <p>A View should call this if it maintains some notion of which part
4879     * of its content is interesting.  For example, a text editing view
4880     * should call this when its cursor moves.
4881     *
4882     * @param rectangle The rectangle.
4883     * @return Whether any parent scrolled.
4884     */
4885    public boolean requestRectangleOnScreen(Rect rectangle) {
4886        return requestRectangleOnScreen(rectangle, false);
4887    }
4888
4889    /**
4890     * Request that a rectangle of this view be visible on the screen,
4891     * scrolling if necessary just enough.
4892     *
4893     * <p>A View should call this if it maintains some notion of which part
4894     * of its content is interesting.  For example, a text editing view
4895     * should call this when its cursor moves.
4896     *
4897     * <p>When <code>immediate</code> is set to true, scrolling will not be
4898     * animated.
4899     *
4900     * @param rectangle The rectangle.
4901     * @param immediate True to forbid animated scrolling, false otherwise
4902     * @return Whether any parent scrolled.
4903     */
4904    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4905        if (mParent == null) {
4906            return false;
4907        }
4908
4909        View child = this;
4910
4911        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4912        position.set(rectangle);
4913
4914        ViewParent parent = mParent;
4915        boolean scrolled = false;
4916        while (parent != null) {
4917            rectangle.set((int) position.left, (int) position.top,
4918                    (int) position.right, (int) position.bottom);
4919
4920            scrolled |= parent.requestChildRectangleOnScreen(child,
4921                    rectangle, immediate);
4922
4923            if (!child.hasIdentityMatrix()) {
4924                child.getMatrix().mapRect(position);
4925            }
4926
4927            position.offset(child.mLeft, child.mTop);
4928
4929            if (!(parent instanceof View)) {
4930                break;
4931            }
4932
4933            View parentView = (View) parent;
4934
4935            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4936
4937            child = parentView;
4938            parent = child.getParent();
4939        }
4940
4941        return scrolled;
4942    }
4943
4944    /**
4945     * Called when this view wants to give up focus. If focus is cleared
4946     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4947     * <p>
4948     * <strong>Note:</strong> When a View clears focus the framework is trying
4949     * to give focus to the first focusable View from the top. Hence, if this
4950     * View is the first from the top that can take focus, then all callbacks
4951     * related to clearing focus will be invoked after wich the framework will
4952     * give focus to this view.
4953     * </p>
4954     */
4955    public void clearFocus() {
4956        if (DBG) {
4957            System.out.println(this + " clearFocus()");
4958        }
4959
4960        clearFocusInternal(null, true, true);
4961    }
4962
4963    /**
4964     * Clears focus from the view, optionally propagating the change up through
4965     * the parent hierarchy and requesting that the root view place new focus.
4966     *
4967     * @param propagate whether to propagate the change up through the parent
4968     *            hierarchy
4969     * @param refocus when propagate is true, specifies whether to request the
4970     *            root view place new focus
4971     */
4972    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4973        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4974            mPrivateFlags &= ~PFLAG_FOCUSED;
4975
4976            if (propagate && mParent != null) {
4977                mParent.clearChildFocus(this);
4978            }
4979
4980            onFocusChanged(false, 0, null);
4981
4982            manageFocusHotspot(false, focused);
4983            refreshDrawableState();
4984
4985            if (propagate && (!refocus || !rootViewRequestFocus())) {
4986                notifyGlobalFocusCleared(this);
4987            }
4988        }
4989    }
4990
4991    void notifyGlobalFocusCleared(View oldFocus) {
4992        if (oldFocus != null && mAttachInfo != null) {
4993            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4994        }
4995    }
4996
4997    boolean rootViewRequestFocus() {
4998        final View root = getRootView();
4999        return root != null && root.requestFocus();
5000    }
5001
5002    /**
5003     * Called internally by the view system when a new view is getting focus.
5004     * This is what clears the old focus.
5005     * <p>
5006     * <b>NOTE:</b> The parent view's focused child must be updated manually
5007     * after calling this method. Otherwise, the view hierarchy may be left in
5008     * an inconstent state.
5009     */
5010    void unFocus(View focused) {
5011        if (DBG) {
5012            System.out.println(this + " unFocus()");
5013        }
5014
5015        clearFocusInternal(focused, false, false);
5016    }
5017
5018    /**
5019     * Returns true if this view has focus iteself, or is the ancestor of the
5020     * view that has focus.
5021     *
5022     * @return True if this view has or contains focus, false otherwise.
5023     */
5024    @ViewDebug.ExportedProperty(category = "focus")
5025    public boolean hasFocus() {
5026        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5027    }
5028
5029    /**
5030     * Returns true if this view is focusable or if it contains a reachable View
5031     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5032     * is a View whose parents do not block descendants focus.
5033     *
5034     * Only {@link #VISIBLE} views are considered focusable.
5035     *
5036     * @return True if the view is focusable or if the view contains a focusable
5037     *         View, false otherwise.
5038     *
5039     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5040     */
5041    public boolean hasFocusable() {
5042        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5043    }
5044
5045    /**
5046     * Called by the view system when the focus state of this view changes.
5047     * When the focus change event is caused by directional navigation, direction
5048     * and previouslyFocusedRect provide insight into where the focus is coming from.
5049     * When overriding, be sure to call up through to the super class so that
5050     * the standard focus handling will occur.
5051     *
5052     * @param gainFocus True if the View has focus; false otherwise.
5053     * @param direction The direction focus has moved when requestFocus()
5054     *                  is called to give this view focus. Values are
5055     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5056     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5057     *                  It may not always apply, in which case use the default.
5058     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5059     *        system, of the previously focused view.  If applicable, this will be
5060     *        passed in as finer grained information about where the focus is coming
5061     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5062     */
5063    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5064            @Nullable Rect previouslyFocusedRect) {
5065        if (gainFocus) {
5066            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5067        } else {
5068            notifyViewAccessibilityStateChangedIfNeeded(
5069                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5070        }
5071
5072        InputMethodManager imm = InputMethodManager.peekInstance();
5073        if (!gainFocus) {
5074            if (isPressed()) {
5075                setPressed(false);
5076            }
5077            if (imm != null && mAttachInfo != null
5078                    && mAttachInfo.mHasWindowFocus) {
5079                imm.focusOut(this);
5080            }
5081            onFocusLost();
5082        } else if (imm != null && mAttachInfo != null
5083                && mAttachInfo.mHasWindowFocus) {
5084            imm.focusIn(this);
5085        }
5086
5087        invalidate(true);
5088        ListenerInfo li = mListenerInfo;
5089        if (li != null && li.mOnFocusChangeListener != null) {
5090            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5091        }
5092
5093        if (mAttachInfo != null) {
5094            mAttachInfo.mKeyDispatchState.reset(this);
5095        }
5096    }
5097
5098    /**
5099     * Sends an accessibility event of the given type. If accessibility is
5100     * not enabled this method has no effect. The default implementation calls
5101     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5102     * to populate information about the event source (this View), then calls
5103     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5104     * populate the text content of the event source including its descendants,
5105     * and last calls
5106     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5107     * on its parent to resuest sending of the event to interested parties.
5108     * <p>
5109     * If an {@link AccessibilityDelegate} has been specified via calling
5110     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5111     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5112     * responsible for handling this call.
5113     * </p>
5114     *
5115     * @param eventType The type of the event to send, as defined by several types from
5116     * {@link android.view.accessibility.AccessibilityEvent}, such as
5117     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5118     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5119     *
5120     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5121     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5122     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5123     * @see AccessibilityDelegate
5124     */
5125    public void sendAccessibilityEvent(int eventType) {
5126        if (mAccessibilityDelegate != null) {
5127            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5128        } else {
5129            sendAccessibilityEventInternal(eventType);
5130        }
5131    }
5132
5133    /**
5134     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5135     * {@link AccessibilityEvent} to make an announcement which is related to some
5136     * sort of a context change for which none of the events representing UI transitions
5137     * is a good fit. For example, announcing a new page in a book. If accessibility
5138     * is not enabled this method does nothing.
5139     *
5140     * @param text The announcement text.
5141     */
5142    public void announceForAccessibility(CharSequence text) {
5143        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5144            AccessibilityEvent event = AccessibilityEvent.obtain(
5145                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5146            onInitializeAccessibilityEvent(event);
5147            event.getText().add(text);
5148            event.setContentDescription(null);
5149            mParent.requestSendAccessibilityEvent(this, event);
5150        }
5151    }
5152
5153    /**
5154     * @see #sendAccessibilityEvent(int)
5155     *
5156     * Note: Called from the default {@link AccessibilityDelegate}.
5157     */
5158    void sendAccessibilityEventInternal(int eventType) {
5159        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5160            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5161        }
5162    }
5163
5164    /**
5165     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5166     * takes as an argument an empty {@link AccessibilityEvent} and does not
5167     * perform a check whether accessibility is enabled.
5168     * <p>
5169     * If an {@link AccessibilityDelegate} has been specified via calling
5170     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5171     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5172     * is responsible for handling this call.
5173     * </p>
5174     *
5175     * @param event The event to send.
5176     *
5177     * @see #sendAccessibilityEvent(int)
5178     */
5179    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5180        if (mAccessibilityDelegate != null) {
5181            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5182        } else {
5183            sendAccessibilityEventUncheckedInternal(event);
5184        }
5185    }
5186
5187    /**
5188     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5189     *
5190     * Note: Called from the default {@link AccessibilityDelegate}.
5191     */
5192    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5193        if (!isShown()) {
5194            return;
5195        }
5196        onInitializeAccessibilityEvent(event);
5197        // Only a subset of accessibility events populates text content.
5198        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5199            dispatchPopulateAccessibilityEvent(event);
5200        }
5201        // In the beginning we called #isShown(), so we know that getParent() is not null.
5202        getParent().requestSendAccessibilityEvent(this, event);
5203    }
5204
5205    /**
5206     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5207     * to its children for adding their text content to the event. Note that the
5208     * event text is populated in a separate dispatch path since we add to the
5209     * event not only the text of the source but also the text of all its descendants.
5210     * A typical implementation will call
5211     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5212     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5213     * on each child. Override this method if custom population of the event text
5214     * content is required.
5215     * <p>
5216     * If an {@link AccessibilityDelegate} has been specified via calling
5217     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5218     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5219     * is responsible for handling this call.
5220     * </p>
5221     * <p>
5222     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5223     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5224     * </p>
5225     *
5226     * @param event The event.
5227     *
5228     * @return True if the event population was completed.
5229     */
5230    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5231        if (mAccessibilityDelegate != null) {
5232            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5233        } else {
5234            return dispatchPopulateAccessibilityEventInternal(event);
5235        }
5236    }
5237
5238    /**
5239     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5240     *
5241     * Note: Called from the default {@link AccessibilityDelegate}.
5242     */
5243    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5244        onPopulateAccessibilityEvent(event);
5245        return false;
5246    }
5247
5248    /**
5249     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5250     * giving a chance to this View to populate the accessibility event with its
5251     * text content. While this method is free to modify event
5252     * attributes other than text content, doing so should normally be performed in
5253     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5254     * <p>
5255     * Example: Adding formatted date string to an accessibility event in addition
5256     *          to the text added by the super implementation:
5257     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5258     *     super.onPopulateAccessibilityEvent(event);
5259     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5260     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5261     *         mCurrentDate.getTimeInMillis(), flags);
5262     *     event.getText().add(selectedDateUtterance);
5263     * }</pre>
5264     * <p>
5265     * If an {@link AccessibilityDelegate} has been specified via calling
5266     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5267     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5268     * is responsible for handling this call.
5269     * </p>
5270     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5271     * information to the event, in case the default implementation has basic information to add.
5272     * </p>
5273     *
5274     * @param event The accessibility event which to populate.
5275     *
5276     * @see #sendAccessibilityEvent(int)
5277     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5278     */
5279    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5280        if (mAccessibilityDelegate != null) {
5281            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5282        } else {
5283            onPopulateAccessibilityEventInternal(event);
5284        }
5285    }
5286
5287    /**
5288     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5289     *
5290     * Note: Called from the default {@link AccessibilityDelegate}.
5291     */
5292    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5293    }
5294
5295    /**
5296     * Initializes an {@link AccessibilityEvent} with information about
5297     * this View which is the event source. In other words, the source of
5298     * an accessibility event is the view whose state change triggered firing
5299     * the event.
5300     * <p>
5301     * Example: Setting the password property of an event in addition
5302     *          to properties set by the super implementation:
5303     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5304     *     super.onInitializeAccessibilityEvent(event);
5305     *     event.setPassword(true);
5306     * }</pre>
5307     * <p>
5308     * If an {@link AccessibilityDelegate} has been specified via calling
5309     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5310     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5311     * is responsible for handling this call.
5312     * </p>
5313     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5314     * information to the event, in case the default implementation has basic information to add.
5315     * </p>
5316     * @param event The event to initialize.
5317     *
5318     * @see #sendAccessibilityEvent(int)
5319     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5320     */
5321    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5322        if (mAccessibilityDelegate != null) {
5323            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5324        } else {
5325            onInitializeAccessibilityEventInternal(event);
5326        }
5327    }
5328
5329    /**
5330     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5331     *
5332     * Note: Called from the default {@link AccessibilityDelegate}.
5333     */
5334    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5335        event.setSource(this);
5336        event.setClassName(View.class.getName());
5337        event.setPackageName(getContext().getPackageName());
5338        event.setEnabled(isEnabled());
5339        event.setContentDescription(mContentDescription);
5340
5341        switch (event.getEventType()) {
5342            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5343                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5344                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5345                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5346                event.setItemCount(focusablesTempList.size());
5347                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5348                if (mAttachInfo != null) {
5349                    focusablesTempList.clear();
5350                }
5351            } break;
5352            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5353                CharSequence text = getIterableTextForAccessibility();
5354                if (text != null && text.length() > 0) {
5355                    event.setFromIndex(getAccessibilitySelectionStart());
5356                    event.setToIndex(getAccessibilitySelectionEnd());
5357                    event.setItemCount(text.length());
5358                }
5359            } break;
5360        }
5361    }
5362
5363    /**
5364     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5365     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5366     * This method is responsible for obtaining an accessibility node info from a
5367     * pool of reusable instances and calling
5368     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5369     * initialize the former.
5370     * <p>
5371     * Note: The client is responsible for recycling the obtained instance by calling
5372     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5373     * </p>
5374     *
5375     * @return A populated {@link AccessibilityNodeInfo}.
5376     *
5377     * @see AccessibilityNodeInfo
5378     */
5379    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5380        if (mAccessibilityDelegate != null) {
5381            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5382        } else {
5383            return createAccessibilityNodeInfoInternal();
5384        }
5385    }
5386
5387    /**
5388     * @see #createAccessibilityNodeInfo()
5389     */
5390    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5391        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5392        if (provider != null) {
5393            return provider.createAccessibilityNodeInfo(View.NO_ID);
5394        } else {
5395            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5396            onInitializeAccessibilityNodeInfo(info);
5397            return info;
5398        }
5399    }
5400
5401    /**
5402     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5403     * The base implementation sets:
5404     * <ul>
5405     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5406     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5407     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5408     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5409     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5410     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5411     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5412     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5413     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5414     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5415     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5416     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5417     * </ul>
5418     * <p>
5419     * Subclasses should override this method, call the super implementation,
5420     * and set additional attributes.
5421     * </p>
5422     * <p>
5423     * If an {@link AccessibilityDelegate} has been specified via calling
5424     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5425     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5426     * is responsible for handling this call.
5427     * </p>
5428     *
5429     * @param info The instance to initialize.
5430     */
5431    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5432        if (mAccessibilityDelegate != null) {
5433            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5434        } else {
5435            onInitializeAccessibilityNodeInfoInternal(info);
5436        }
5437    }
5438
5439    /**
5440     * Gets the location of this view in screen coordintates.
5441     *
5442     * @param outRect The output location
5443     * @hide
5444     */
5445    public void getBoundsOnScreen(Rect outRect) {
5446        if (mAttachInfo == null) {
5447            return;
5448        }
5449
5450        RectF position = mAttachInfo.mTmpTransformRect;
5451        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5452
5453        if (!hasIdentityMatrix()) {
5454            getMatrix().mapRect(position);
5455        }
5456
5457        position.offset(mLeft, mTop);
5458
5459        ViewParent parent = mParent;
5460        while (parent instanceof View) {
5461            View parentView = (View) parent;
5462
5463            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5464
5465            if (!parentView.hasIdentityMatrix()) {
5466                parentView.getMatrix().mapRect(position);
5467            }
5468
5469            position.offset(parentView.mLeft, parentView.mTop);
5470
5471            parent = parentView.mParent;
5472        }
5473
5474        if (parent instanceof ViewRootImpl) {
5475            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5476            position.offset(0, -viewRootImpl.mCurScrollY);
5477        }
5478
5479        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5480
5481        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5482                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5483    }
5484
5485    /**
5486     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5487     *
5488     * Note: Called from the default {@link AccessibilityDelegate}.
5489     */
5490    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5491        Rect bounds = mAttachInfo.mTmpInvalRect;
5492
5493        getDrawingRect(bounds);
5494        info.setBoundsInParent(bounds);
5495
5496        getBoundsOnScreen(bounds);
5497        info.setBoundsInScreen(bounds);
5498
5499        ViewParent parent = getParentForAccessibility();
5500        if (parent instanceof View) {
5501            info.setParent((View) parent);
5502        }
5503
5504        if (mID != View.NO_ID) {
5505            View rootView = getRootView();
5506            if (rootView == null) {
5507                rootView = this;
5508            }
5509            View label = rootView.findLabelForView(this, mID);
5510            if (label != null) {
5511                info.setLabeledBy(label);
5512            }
5513
5514            if ((mAttachInfo.mAccessibilityFetchFlags
5515                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5516                    && Resources.resourceHasPackage(mID)) {
5517                try {
5518                    String viewId = getResources().getResourceName(mID);
5519                    info.setViewIdResourceName(viewId);
5520                } catch (Resources.NotFoundException nfe) {
5521                    /* ignore */
5522                }
5523            }
5524        }
5525
5526        if (mLabelForId != View.NO_ID) {
5527            View rootView = getRootView();
5528            if (rootView == null) {
5529                rootView = this;
5530            }
5531            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5532            if (labeled != null) {
5533                info.setLabelFor(labeled);
5534            }
5535        }
5536
5537        info.setVisibleToUser(isVisibleToUser());
5538
5539        info.setPackageName(mContext.getPackageName());
5540        info.setClassName(View.class.getName());
5541        info.setContentDescription(getContentDescription());
5542
5543        info.setEnabled(isEnabled());
5544        info.setClickable(isClickable());
5545        info.setFocusable(isFocusable());
5546        info.setFocused(isFocused());
5547        info.setAccessibilityFocused(isAccessibilityFocused());
5548        info.setSelected(isSelected());
5549        info.setLongClickable(isLongClickable());
5550        info.setLiveRegion(getAccessibilityLiveRegion());
5551
5552        // TODO: These make sense only if we are in an AdapterView but all
5553        // views can be selected. Maybe from accessibility perspective
5554        // we should report as selectable view in an AdapterView.
5555        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5556        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5557
5558        if (isFocusable()) {
5559            if (isFocused()) {
5560                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5561            } else {
5562                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5563            }
5564        }
5565
5566        if (!isAccessibilityFocused()) {
5567            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5568        } else {
5569            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5570        }
5571
5572        if (isClickable() && isEnabled()) {
5573            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5574        }
5575
5576        if (isLongClickable() && isEnabled()) {
5577            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5578        }
5579
5580        CharSequence text = getIterableTextForAccessibility();
5581        if (text != null && text.length() > 0) {
5582            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5583
5584            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5585            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5586            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5587            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5588                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5589                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5590        }
5591    }
5592
5593    private View findLabelForView(View view, int labeledId) {
5594        if (mMatchLabelForPredicate == null) {
5595            mMatchLabelForPredicate = new MatchLabelForPredicate();
5596        }
5597        mMatchLabelForPredicate.mLabeledId = labeledId;
5598        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5599    }
5600
5601    /**
5602     * Computes whether this view is visible to the user. Such a view is
5603     * attached, visible, all its predecessors are visible, it is not clipped
5604     * entirely by its predecessors, and has an alpha greater than zero.
5605     *
5606     * @return Whether the view is visible on the screen.
5607     *
5608     * @hide
5609     */
5610    protected boolean isVisibleToUser() {
5611        return isVisibleToUser(null);
5612    }
5613
5614    /**
5615     * Computes whether the given portion of this view is visible to the user.
5616     * Such a view is attached, visible, all its predecessors are visible,
5617     * has an alpha greater than zero, and the specified portion is not
5618     * clipped entirely by its predecessors.
5619     *
5620     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5621     *                    <code>null</code>, and the entire view will be tested in this case.
5622     *                    When <code>true</code> is returned by the function, the actual visible
5623     *                    region will be stored in this parameter; that is, if boundInView is fully
5624     *                    contained within the view, no modification will be made, otherwise regions
5625     *                    outside of the visible area of the view will be clipped.
5626     *
5627     * @return Whether the specified portion of the view is visible on the screen.
5628     *
5629     * @hide
5630     */
5631    protected boolean isVisibleToUser(Rect boundInView) {
5632        if (mAttachInfo != null) {
5633            // Attached to invisible window means this view is not visible.
5634            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5635                return false;
5636            }
5637            // An invisible predecessor or one with alpha zero means
5638            // that this view is not visible to the user.
5639            Object current = this;
5640            while (current instanceof View) {
5641                View view = (View) current;
5642                // We have attach info so this view is attached and there is no
5643                // need to check whether we reach to ViewRootImpl on the way up.
5644                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5645                        view.getVisibility() != VISIBLE) {
5646                    return false;
5647                }
5648                current = view.mParent;
5649            }
5650            // Check if the view is entirely covered by its predecessors.
5651            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5652            Point offset = mAttachInfo.mPoint;
5653            if (!getGlobalVisibleRect(visibleRect, offset)) {
5654                return false;
5655            }
5656            // Check if the visible portion intersects the rectangle of interest.
5657            if (boundInView != null) {
5658                visibleRect.offset(-offset.x, -offset.y);
5659                return boundInView.intersect(visibleRect);
5660            }
5661            return true;
5662        }
5663        return false;
5664    }
5665
5666    /**
5667     * Returns the delegate for implementing accessibility support via
5668     * composition. For more details see {@link AccessibilityDelegate}.
5669     *
5670     * @return The delegate, or null if none set.
5671     *
5672     * @hide
5673     */
5674    public AccessibilityDelegate getAccessibilityDelegate() {
5675        return mAccessibilityDelegate;
5676    }
5677
5678    /**
5679     * Sets a delegate for implementing accessibility support via composition as
5680     * opposed to inheritance. The delegate's primary use is for implementing
5681     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5682     *
5683     * @param delegate The delegate instance.
5684     *
5685     * @see AccessibilityDelegate
5686     */
5687    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5688        mAccessibilityDelegate = delegate;
5689    }
5690
5691    /**
5692     * Gets the provider for managing a virtual view hierarchy rooted at this View
5693     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5694     * that explore the window content.
5695     * <p>
5696     * If this method returns an instance, this instance is responsible for managing
5697     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5698     * View including the one representing the View itself. Similarly the returned
5699     * instance is responsible for performing accessibility actions on any virtual
5700     * view or the root view itself.
5701     * </p>
5702     * <p>
5703     * If an {@link AccessibilityDelegate} has been specified via calling
5704     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5705     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5706     * is responsible for handling this call.
5707     * </p>
5708     *
5709     * @return The provider.
5710     *
5711     * @see AccessibilityNodeProvider
5712     */
5713    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5714        if (mAccessibilityDelegate != null) {
5715            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5716        } else {
5717            return null;
5718        }
5719    }
5720
5721    /**
5722     * Gets the unique identifier of this view on the screen for accessibility purposes.
5723     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5724     *
5725     * @return The view accessibility id.
5726     *
5727     * @hide
5728     */
5729    public int getAccessibilityViewId() {
5730        if (mAccessibilityViewId == NO_ID) {
5731            mAccessibilityViewId = sNextAccessibilityViewId++;
5732        }
5733        return mAccessibilityViewId;
5734    }
5735
5736    /**
5737     * Gets the unique identifier of the window in which this View reseides.
5738     *
5739     * @return The window accessibility id.
5740     *
5741     * @hide
5742     */
5743    public int getAccessibilityWindowId() {
5744        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5745                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5746    }
5747
5748    /**
5749     * Gets the {@link View} description. It briefly describes the view and is
5750     * primarily used for accessibility support. Set this property to enable
5751     * better accessibility support for your application. This is especially
5752     * true for views that do not have textual representation (For example,
5753     * ImageButton).
5754     *
5755     * @return The content description.
5756     *
5757     * @attr ref android.R.styleable#View_contentDescription
5758     */
5759    @ViewDebug.ExportedProperty(category = "accessibility")
5760    public CharSequence getContentDescription() {
5761        return mContentDescription;
5762    }
5763
5764    /**
5765     * Sets the {@link View} description. It briefly describes the view and is
5766     * primarily used for accessibility support. Set this property to enable
5767     * better accessibility support for your application. This is especially
5768     * true for views that do not have textual representation (For example,
5769     * ImageButton).
5770     *
5771     * @param contentDescription The content description.
5772     *
5773     * @attr ref android.R.styleable#View_contentDescription
5774     */
5775    @RemotableViewMethod
5776    public void setContentDescription(CharSequence contentDescription) {
5777        if (mContentDescription == null) {
5778            if (contentDescription == null) {
5779                return;
5780            }
5781        } else if (mContentDescription.equals(contentDescription)) {
5782            return;
5783        }
5784        mContentDescription = contentDescription;
5785        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5786        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5787            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5788            notifySubtreeAccessibilityStateChangedIfNeeded();
5789        } else {
5790            notifyViewAccessibilityStateChangedIfNeeded(
5791                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5792        }
5793    }
5794
5795    /**
5796     * Gets the id of a view for which this view serves as a label for
5797     * accessibility purposes.
5798     *
5799     * @return The labeled view id.
5800     */
5801    @ViewDebug.ExportedProperty(category = "accessibility")
5802    public int getLabelFor() {
5803        return mLabelForId;
5804    }
5805
5806    /**
5807     * Sets the id of a view for which this view serves as a label for
5808     * accessibility purposes.
5809     *
5810     * @param id The labeled view id.
5811     */
5812    @RemotableViewMethod
5813    public void setLabelFor(int id) {
5814        mLabelForId = id;
5815        if (mLabelForId != View.NO_ID
5816                && mID == View.NO_ID) {
5817            mID = generateViewId();
5818        }
5819    }
5820
5821    /**
5822     * Invoked whenever this view loses focus, either by losing window focus or by losing
5823     * focus within its window. This method can be used to clear any state tied to the
5824     * focus. For instance, if a button is held pressed with the trackball and the window
5825     * loses focus, this method can be used to cancel the press.
5826     *
5827     * Subclasses of View overriding this method should always call super.onFocusLost().
5828     *
5829     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5830     * @see #onWindowFocusChanged(boolean)
5831     *
5832     * @hide pending API council approval
5833     */
5834    protected void onFocusLost() {
5835        resetPressedState();
5836    }
5837
5838    private void resetPressedState() {
5839        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5840            return;
5841        }
5842
5843        if (isPressed()) {
5844            setPressed(false);
5845
5846            if (!mHasPerformedLongPress) {
5847                removeLongPressCallback();
5848            }
5849        }
5850    }
5851
5852    /**
5853     * Returns true if this view has focus
5854     *
5855     * @return True if this view has focus, false otherwise.
5856     */
5857    @ViewDebug.ExportedProperty(category = "focus")
5858    public boolean isFocused() {
5859        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5860    }
5861
5862    /**
5863     * Find the view in the hierarchy rooted at this view that currently has
5864     * focus.
5865     *
5866     * @return The view that currently has focus, or null if no focused view can
5867     *         be found.
5868     */
5869    public View findFocus() {
5870        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5871    }
5872
5873    /**
5874     * Indicates whether this view is one of the set of scrollable containers in
5875     * its window.
5876     *
5877     * @return whether this view is one of the set of scrollable containers in
5878     * its window
5879     *
5880     * @attr ref android.R.styleable#View_isScrollContainer
5881     */
5882    public boolean isScrollContainer() {
5883        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5884    }
5885
5886    /**
5887     * Change whether this view is one of the set of scrollable containers in
5888     * its window.  This will be used to determine whether the window can
5889     * resize or must pan when a soft input area is open -- scrollable
5890     * containers allow the window to use resize mode since the container
5891     * will appropriately shrink.
5892     *
5893     * @attr ref android.R.styleable#View_isScrollContainer
5894     */
5895    public void setScrollContainer(boolean isScrollContainer) {
5896        if (isScrollContainer) {
5897            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5898                mAttachInfo.mScrollContainers.add(this);
5899                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5900            }
5901            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5902        } else {
5903            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5904                mAttachInfo.mScrollContainers.remove(this);
5905            }
5906            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5907        }
5908    }
5909
5910    /**
5911     * Returns the quality of the drawing cache.
5912     *
5913     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5914     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5915     *
5916     * @see #setDrawingCacheQuality(int)
5917     * @see #setDrawingCacheEnabled(boolean)
5918     * @see #isDrawingCacheEnabled()
5919     *
5920     * @attr ref android.R.styleable#View_drawingCacheQuality
5921     */
5922    @DrawingCacheQuality
5923    public int getDrawingCacheQuality() {
5924        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5925    }
5926
5927    /**
5928     * Set the drawing cache quality of this view. This value is used only when the
5929     * drawing cache is enabled
5930     *
5931     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5932     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5933     *
5934     * @see #getDrawingCacheQuality()
5935     * @see #setDrawingCacheEnabled(boolean)
5936     * @see #isDrawingCacheEnabled()
5937     *
5938     * @attr ref android.R.styleable#View_drawingCacheQuality
5939     */
5940    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5941        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5942    }
5943
5944    /**
5945     * Returns whether the screen should remain on, corresponding to the current
5946     * value of {@link #KEEP_SCREEN_ON}.
5947     *
5948     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5949     *
5950     * @see #setKeepScreenOn(boolean)
5951     *
5952     * @attr ref android.R.styleable#View_keepScreenOn
5953     */
5954    public boolean getKeepScreenOn() {
5955        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5956    }
5957
5958    /**
5959     * Controls whether the screen should remain on, modifying the
5960     * value of {@link #KEEP_SCREEN_ON}.
5961     *
5962     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5963     *
5964     * @see #getKeepScreenOn()
5965     *
5966     * @attr ref android.R.styleable#View_keepScreenOn
5967     */
5968    public void setKeepScreenOn(boolean keepScreenOn) {
5969        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5970    }
5971
5972    /**
5973     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5974     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5975     *
5976     * @attr ref android.R.styleable#View_nextFocusLeft
5977     */
5978    public int getNextFocusLeftId() {
5979        return mNextFocusLeftId;
5980    }
5981
5982    /**
5983     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5984     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5985     * decide automatically.
5986     *
5987     * @attr ref android.R.styleable#View_nextFocusLeft
5988     */
5989    public void setNextFocusLeftId(int nextFocusLeftId) {
5990        mNextFocusLeftId = nextFocusLeftId;
5991    }
5992
5993    /**
5994     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5995     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5996     *
5997     * @attr ref android.R.styleable#View_nextFocusRight
5998     */
5999    public int getNextFocusRightId() {
6000        return mNextFocusRightId;
6001    }
6002
6003    /**
6004     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6005     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6006     * decide automatically.
6007     *
6008     * @attr ref android.R.styleable#View_nextFocusRight
6009     */
6010    public void setNextFocusRightId(int nextFocusRightId) {
6011        mNextFocusRightId = nextFocusRightId;
6012    }
6013
6014    /**
6015     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6016     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6017     *
6018     * @attr ref android.R.styleable#View_nextFocusUp
6019     */
6020    public int getNextFocusUpId() {
6021        return mNextFocusUpId;
6022    }
6023
6024    /**
6025     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6026     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6027     * decide automatically.
6028     *
6029     * @attr ref android.R.styleable#View_nextFocusUp
6030     */
6031    public void setNextFocusUpId(int nextFocusUpId) {
6032        mNextFocusUpId = nextFocusUpId;
6033    }
6034
6035    /**
6036     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6037     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6038     *
6039     * @attr ref android.R.styleable#View_nextFocusDown
6040     */
6041    public int getNextFocusDownId() {
6042        return mNextFocusDownId;
6043    }
6044
6045    /**
6046     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6047     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6048     * decide automatically.
6049     *
6050     * @attr ref android.R.styleable#View_nextFocusDown
6051     */
6052    public void setNextFocusDownId(int nextFocusDownId) {
6053        mNextFocusDownId = nextFocusDownId;
6054    }
6055
6056    /**
6057     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6058     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6059     *
6060     * @attr ref android.R.styleable#View_nextFocusForward
6061     */
6062    public int getNextFocusForwardId() {
6063        return mNextFocusForwardId;
6064    }
6065
6066    /**
6067     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6068     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6069     * decide automatically.
6070     *
6071     * @attr ref android.R.styleable#View_nextFocusForward
6072     */
6073    public void setNextFocusForwardId(int nextFocusForwardId) {
6074        mNextFocusForwardId = nextFocusForwardId;
6075    }
6076
6077    /**
6078     * Returns the visibility of this view and all of its ancestors
6079     *
6080     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6081     */
6082    public boolean isShown() {
6083        View current = this;
6084        //noinspection ConstantConditions
6085        do {
6086            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6087                return false;
6088            }
6089            ViewParent parent = current.mParent;
6090            if (parent == null) {
6091                return false; // We are not attached to the view root
6092            }
6093            if (!(parent instanceof View)) {
6094                return true;
6095            }
6096            current = (View) parent;
6097        } while (current != null);
6098
6099        return false;
6100    }
6101
6102    /**
6103     * Called by the view hierarchy when the content insets for a window have
6104     * changed, to allow it to adjust its content to fit within those windows.
6105     * The content insets tell you the space that the status bar, input method,
6106     * and other system windows infringe on the application's window.
6107     *
6108     * <p>You do not normally need to deal with this function, since the default
6109     * window decoration given to applications takes care of applying it to the
6110     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6111     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6112     * and your content can be placed under those system elements.  You can then
6113     * use this method within your view hierarchy if you have parts of your UI
6114     * which you would like to ensure are not being covered.
6115     *
6116     * <p>The default implementation of this method simply applies the content
6117     * insets to the view's padding, consuming that content (modifying the
6118     * insets to be 0), and returning true.  This behavior is off by default, but can
6119     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6120     *
6121     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6122     * insets object is propagated down the hierarchy, so any changes made to it will
6123     * be seen by all following views (including potentially ones above in
6124     * the hierarchy since this is a depth-first traversal).  The first view
6125     * that returns true will abort the entire traversal.
6126     *
6127     * <p>The default implementation works well for a situation where it is
6128     * used with a container that covers the entire window, allowing it to
6129     * apply the appropriate insets to its content on all edges.  If you need
6130     * a more complicated layout (such as two different views fitting system
6131     * windows, one on the top of the window, and one on the bottom),
6132     * you can override the method and handle the insets however you would like.
6133     * Note that the insets provided by the framework are always relative to the
6134     * far edges of the window, not accounting for the location of the called view
6135     * within that window.  (In fact when this method is called you do not yet know
6136     * where the layout will place the view, as it is done before layout happens.)
6137     *
6138     * <p>Note: unlike many View methods, there is no dispatch phase to this
6139     * call.  If you are overriding it in a ViewGroup and want to allow the
6140     * call to continue to your children, you must be sure to call the super
6141     * implementation.
6142     *
6143     * <p>Here is a sample layout that makes use of fitting system windows
6144     * to have controls for a video view placed inside of the window decorations
6145     * that it hides and shows.  This can be used with code like the second
6146     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6147     *
6148     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6149     *
6150     * @param insets Current content insets of the window.  Prior to
6151     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6152     * the insets or else you and Android will be unhappy.
6153     *
6154     * @return {@code true} if this view applied the insets and it should not
6155     * continue propagating further down the hierarchy, {@code false} otherwise.
6156     * @see #getFitsSystemWindows()
6157     * @see #setFitsSystemWindows(boolean)
6158     * @see #setSystemUiVisibility(int)
6159     *
6160     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6161     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6162     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6163     * to implement handling their own insets.
6164     */
6165    protected boolean fitSystemWindows(Rect insets) {
6166        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6167            if (insets == null) {
6168                // Null insets by definition have already been consumed.
6169                // This call cannot apply insets since there are none to apply,
6170                // so return false.
6171                return false;
6172            }
6173            // If we're not in the process of dispatching the newer apply insets call,
6174            // that means we're not in the compatibility path. Dispatch into the newer
6175            // apply insets path and take things from there.
6176            try {
6177                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6178                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6179            } finally {
6180                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6181            }
6182        } else {
6183            // We're being called from the newer apply insets path.
6184            // Perform the standard fallback behavior.
6185            return fitSystemWindowsInt(insets);
6186        }
6187    }
6188
6189    private boolean fitSystemWindowsInt(Rect insets) {
6190        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6191            mUserPaddingStart = UNDEFINED_PADDING;
6192            mUserPaddingEnd = UNDEFINED_PADDING;
6193            Rect localInsets = sThreadLocal.get();
6194            if (localInsets == null) {
6195                localInsets = new Rect();
6196                sThreadLocal.set(localInsets);
6197            }
6198            boolean res = computeFitSystemWindows(insets, localInsets);
6199            mUserPaddingLeftInitial = localInsets.left;
6200            mUserPaddingRightInitial = localInsets.right;
6201            internalSetPadding(localInsets.left, localInsets.top,
6202                    localInsets.right, localInsets.bottom);
6203            return res;
6204        }
6205        return false;
6206    }
6207
6208    /**
6209     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6210     *
6211     * <p>This method should be overridden by views that wish to apply a policy different from or
6212     * in addition to the default behavior. Clients that wish to force a view subtree
6213     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6214     *
6215     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6216     * it will be called during dispatch instead of this method. The listener may optionally
6217     * call this method from its own implementation if it wishes to apply the view's default
6218     * insets policy in addition to its own.</p>
6219     *
6220     * <p>Implementations of this method should either return the insets parameter unchanged
6221     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6222     * that this view applied itself. This allows new inset types added in future platform
6223     * versions to pass through existing implementations unchanged without being erroneously
6224     * consumed.</p>
6225     *
6226     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6227     * property is set then the view will consume the system window insets and apply them
6228     * as padding for the view.</p>
6229     *
6230     * @param insets Insets to apply
6231     * @return The supplied insets with any applied insets consumed
6232     */
6233    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6234        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6235            // We weren't called from within a direct call to fitSystemWindows,
6236            // call into it as a fallback in case we're in a class that overrides it
6237            // and has logic to perform.
6238            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6239                return insets.consumeSystemWindowInsets();
6240            }
6241        } else {
6242            // We were called from within a direct call to fitSystemWindows.
6243            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6244                return insets.consumeSystemWindowInsets();
6245            }
6246        }
6247        return insets;
6248    }
6249
6250    /**
6251     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6252     * window insets to this view. The listener's
6253     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6254     * method will be called instead of the view's
6255     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6256     *
6257     * @param listener Listener to set
6258     *
6259     * @see #onApplyWindowInsets(WindowInsets)
6260     */
6261    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6262        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6263    }
6264
6265    /**
6266     * Request to apply the given window insets to this view or another view in its subtree.
6267     *
6268     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6269     * obscured by window decorations or overlays. This can include the status and navigation bars,
6270     * action bars, input methods and more. New inset categories may be added in the future.
6271     * The method returns the insets provided minus any that were applied by this view or its
6272     * children.</p>
6273     *
6274     * <p>Clients wishing to provide custom behavior should override the
6275     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6276     * {@link OnApplyWindowInsetsListener} via the
6277     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6278     * method.</p>
6279     *
6280     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6281     * </p>
6282     *
6283     * @param insets Insets to apply
6284     * @return The provided insets minus the insets that were consumed
6285     */
6286    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6287        try {
6288            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6289            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6290                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6291            } else {
6292                return onApplyWindowInsets(insets);
6293            }
6294        } finally {
6295            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6296        }
6297    }
6298
6299    /**
6300     * @hide Compute the insets that should be consumed by this view and the ones
6301     * that should propagate to those under it.
6302     */
6303    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6304        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6305                || mAttachInfo == null
6306                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6307                        && !mAttachInfo.mOverscanRequested)) {
6308            outLocalInsets.set(inoutInsets);
6309            inoutInsets.set(0, 0, 0, 0);
6310            return true;
6311        } else {
6312            // The application wants to take care of fitting system window for
6313            // the content...  however we still need to take care of any overscan here.
6314            final Rect overscan = mAttachInfo.mOverscanInsets;
6315            outLocalInsets.set(overscan);
6316            inoutInsets.left -= overscan.left;
6317            inoutInsets.top -= overscan.top;
6318            inoutInsets.right -= overscan.right;
6319            inoutInsets.bottom -= overscan.bottom;
6320            return false;
6321        }
6322    }
6323
6324    /**
6325     * Sets whether or not this view should account for system screen decorations
6326     * such as the status bar and inset its content; that is, controlling whether
6327     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6328     * executed.  See that method for more details.
6329     *
6330     * <p>Note that if you are providing your own implementation of
6331     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6332     * flag to true -- your implementation will be overriding the default
6333     * implementation that checks this flag.
6334     *
6335     * @param fitSystemWindows If true, then the default implementation of
6336     * {@link #fitSystemWindows(Rect)} will be executed.
6337     *
6338     * @attr ref android.R.styleable#View_fitsSystemWindows
6339     * @see #getFitsSystemWindows()
6340     * @see #fitSystemWindows(Rect)
6341     * @see #setSystemUiVisibility(int)
6342     */
6343    public void setFitsSystemWindows(boolean fitSystemWindows) {
6344        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6345    }
6346
6347    /**
6348     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6349     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6350     * will be executed.
6351     *
6352     * @return {@code true} if the default implementation of
6353     * {@link #fitSystemWindows(Rect)} will be executed.
6354     *
6355     * @attr ref android.R.styleable#View_fitsSystemWindows
6356     * @see #setFitsSystemWindows(boolean)
6357     * @see #fitSystemWindows(Rect)
6358     * @see #setSystemUiVisibility(int)
6359     */
6360    public boolean getFitsSystemWindows() {
6361        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6362    }
6363
6364    /** @hide */
6365    public boolean fitsSystemWindows() {
6366        return getFitsSystemWindows();
6367    }
6368
6369    /**
6370     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6371     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6372     */
6373    public void requestFitSystemWindows() {
6374        if (mParent != null) {
6375            mParent.requestFitSystemWindows();
6376        }
6377    }
6378
6379    /**
6380     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6381     */
6382    public void requestApplyInsets() {
6383        requestFitSystemWindows();
6384    }
6385
6386    /**
6387     * For use by PhoneWindow to make its own system window fitting optional.
6388     * @hide
6389     */
6390    public void makeOptionalFitsSystemWindows() {
6391        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6392    }
6393
6394    /**
6395     * Returns the visibility status for this view.
6396     *
6397     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6398     * @attr ref android.R.styleable#View_visibility
6399     */
6400    @ViewDebug.ExportedProperty(mapping = {
6401        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6402        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6403        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6404    })
6405    @Visibility
6406    public int getVisibility() {
6407        return mViewFlags & VISIBILITY_MASK;
6408    }
6409
6410    /**
6411     * Set the enabled state of this view.
6412     *
6413     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6414     * @attr ref android.R.styleable#View_visibility
6415     */
6416    @RemotableViewMethod
6417    public void setVisibility(@Visibility int visibility) {
6418        setFlags(visibility, VISIBILITY_MASK);
6419        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6420    }
6421
6422    /**
6423     * Returns the enabled status for this view. The interpretation of the
6424     * enabled state varies by subclass.
6425     *
6426     * @return True if this view is enabled, false otherwise.
6427     */
6428    @ViewDebug.ExportedProperty
6429    public boolean isEnabled() {
6430        return (mViewFlags & ENABLED_MASK) == ENABLED;
6431    }
6432
6433    /**
6434     * Set the enabled state of this view. The interpretation of the enabled
6435     * state varies by subclass.
6436     *
6437     * @param enabled True if this view is enabled, false otherwise.
6438     */
6439    @RemotableViewMethod
6440    public void setEnabled(boolean enabled) {
6441        if (enabled == isEnabled()) return;
6442
6443        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6444
6445        /*
6446         * The View most likely has to change its appearance, so refresh
6447         * the drawable state.
6448         */
6449        refreshDrawableState();
6450
6451        // Invalidate too, since the default behavior for views is to be
6452        // be drawn at 50% alpha rather than to change the drawable.
6453        invalidate(true);
6454
6455        if (!enabled) {
6456            cancelPendingInputEvents();
6457        }
6458    }
6459
6460    /**
6461     * Set whether this view can receive the focus.
6462     *
6463     * Setting this to false will also ensure that this view is not focusable
6464     * in touch mode.
6465     *
6466     * @param focusable If true, this view can receive the focus.
6467     *
6468     * @see #setFocusableInTouchMode(boolean)
6469     * @attr ref android.R.styleable#View_focusable
6470     */
6471    public void setFocusable(boolean focusable) {
6472        if (!focusable) {
6473            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6474        }
6475        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6476    }
6477
6478    /**
6479     * Set whether this view can receive focus while in touch mode.
6480     *
6481     * Setting this to true will also ensure that this view is focusable.
6482     *
6483     * @param focusableInTouchMode If true, this view can receive the focus while
6484     *   in touch mode.
6485     *
6486     * @see #setFocusable(boolean)
6487     * @attr ref android.R.styleable#View_focusableInTouchMode
6488     */
6489    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6490        // Focusable in touch mode should always be set before the focusable flag
6491        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6492        // which, in touch mode, will not successfully request focus on this view
6493        // because the focusable in touch mode flag is not set
6494        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6495        if (focusableInTouchMode) {
6496            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6497        }
6498    }
6499
6500    /**
6501     * Set whether this view should have sound effects enabled for events such as
6502     * clicking and touching.
6503     *
6504     * <p>You may wish to disable sound effects for a view if you already play sounds,
6505     * for instance, a dial key that plays dtmf tones.
6506     *
6507     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6508     * @see #isSoundEffectsEnabled()
6509     * @see #playSoundEffect(int)
6510     * @attr ref android.R.styleable#View_soundEffectsEnabled
6511     */
6512    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6513        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6514    }
6515
6516    /**
6517     * @return whether this view should have sound effects enabled for events such as
6518     *     clicking and touching.
6519     *
6520     * @see #setSoundEffectsEnabled(boolean)
6521     * @see #playSoundEffect(int)
6522     * @attr ref android.R.styleable#View_soundEffectsEnabled
6523     */
6524    @ViewDebug.ExportedProperty
6525    public boolean isSoundEffectsEnabled() {
6526        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6527    }
6528
6529    /**
6530     * Set whether this view should have haptic feedback for events such as
6531     * long presses.
6532     *
6533     * <p>You may wish to disable haptic feedback if your view already controls
6534     * its own haptic feedback.
6535     *
6536     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6537     * @see #isHapticFeedbackEnabled()
6538     * @see #performHapticFeedback(int)
6539     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6540     */
6541    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6542        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6543    }
6544
6545    /**
6546     * @return whether this view should have haptic feedback enabled for events
6547     * long presses.
6548     *
6549     * @see #setHapticFeedbackEnabled(boolean)
6550     * @see #performHapticFeedback(int)
6551     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6552     */
6553    @ViewDebug.ExportedProperty
6554    public boolean isHapticFeedbackEnabled() {
6555        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6556    }
6557
6558    /**
6559     * Returns the layout direction for this view.
6560     *
6561     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6562     *   {@link #LAYOUT_DIRECTION_RTL},
6563     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6564     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6565     *
6566     * @attr ref android.R.styleable#View_layoutDirection
6567     *
6568     * @hide
6569     */
6570    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6571        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6572        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6573        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6574        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6575    })
6576    @LayoutDir
6577    public int getRawLayoutDirection() {
6578        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6579    }
6580
6581    /**
6582     * Set the layout direction for this view. This will propagate a reset of layout direction
6583     * resolution to the view's children and resolve layout direction for this view.
6584     *
6585     * @param layoutDirection the layout direction to set. Should be one of:
6586     *
6587     * {@link #LAYOUT_DIRECTION_LTR},
6588     * {@link #LAYOUT_DIRECTION_RTL},
6589     * {@link #LAYOUT_DIRECTION_INHERIT},
6590     * {@link #LAYOUT_DIRECTION_LOCALE}.
6591     *
6592     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6593     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6594     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6595     *
6596     * @attr ref android.R.styleable#View_layoutDirection
6597     */
6598    @RemotableViewMethod
6599    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6600        if (getRawLayoutDirection() != layoutDirection) {
6601            // Reset the current layout direction and the resolved one
6602            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6603            resetRtlProperties();
6604            // Set the new layout direction (filtered)
6605            mPrivateFlags2 |=
6606                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6607            // We need to resolve all RTL properties as they all depend on layout direction
6608            resolveRtlPropertiesIfNeeded();
6609            requestLayout();
6610            invalidate(true);
6611        }
6612    }
6613
6614    /**
6615     * Returns the resolved layout direction for this view.
6616     *
6617     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6618     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6619     *
6620     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6621     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6622     *
6623     * @attr ref android.R.styleable#View_layoutDirection
6624     */
6625    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6626        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6627        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6628    })
6629    @ResolvedLayoutDir
6630    public int getLayoutDirection() {
6631        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6632        if (targetSdkVersion < JELLY_BEAN_MR1) {
6633            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6634            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6635        }
6636        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6637                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6638    }
6639
6640    /**
6641     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6642     * layout attribute and/or the inherited value from the parent
6643     *
6644     * @return true if the layout is right-to-left.
6645     *
6646     * @hide
6647     */
6648    @ViewDebug.ExportedProperty(category = "layout")
6649    public boolean isLayoutRtl() {
6650        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6651    }
6652
6653    /**
6654     * Indicates whether the view is currently tracking transient state that the
6655     * app should not need to concern itself with saving and restoring, but that
6656     * the framework should take special note to preserve when possible.
6657     *
6658     * <p>A view with transient state cannot be trivially rebound from an external
6659     * data source, such as an adapter binding item views in a list. This may be
6660     * because the view is performing an animation, tracking user selection
6661     * of content, or similar.</p>
6662     *
6663     * @return true if the view has transient state
6664     */
6665    @ViewDebug.ExportedProperty(category = "layout")
6666    public boolean hasTransientState() {
6667        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6668    }
6669
6670    /**
6671     * Set whether this view is currently tracking transient state that the
6672     * framework should attempt to preserve when possible. This flag is reference counted,
6673     * so every call to setHasTransientState(true) should be paired with a later call
6674     * to setHasTransientState(false).
6675     *
6676     * <p>A view with transient state cannot be trivially rebound from an external
6677     * data source, such as an adapter binding item views in a list. This may be
6678     * because the view is performing an animation, tracking user selection
6679     * of content, or similar.</p>
6680     *
6681     * @param hasTransientState true if this view has transient state
6682     */
6683    public void setHasTransientState(boolean hasTransientState) {
6684        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6685                mTransientStateCount - 1;
6686        if (mTransientStateCount < 0) {
6687            mTransientStateCount = 0;
6688            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6689                    "unmatched pair of setHasTransientState calls");
6690        } else if ((hasTransientState && mTransientStateCount == 1) ||
6691                (!hasTransientState && mTransientStateCount == 0)) {
6692            // update flag if we've just incremented up from 0 or decremented down to 0
6693            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6694                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6695            if (mParent != null) {
6696                try {
6697                    mParent.childHasTransientStateChanged(this, hasTransientState);
6698                } catch (AbstractMethodError e) {
6699                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6700                            " does not fully implement ViewParent", e);
6701                }
6702            }
6703        }
6704    }
6705
6706    /**
6707     * Returns true if this view is currently attached to a window.
6708     */
6709    public boolean isAttachedToWindow() {
6710        return mAttachInfo != null;
6711    }
6712
6713    /**
6714     * Returns true if this view has been through at least one layout since it
6715     * was last attached to or detached from a window.
6716     */
6717    public boolean isLaidOut() {
6718        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6719    }
6720
6721    /**
6722     * If this view doesn't do any drawing on its own, set this flag to
6723     * allow further optimizations. By default, this flag is not set on
6724     * View, but could be set on some View subclasses such as ViewGroup.
6725     *
6726     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6727     * you should clear this flag.
6728     *
6729     * @param willNotDraw whether or not this View draw on its own
6730     */
6731    public void setWillNotDraw(boolean willNotDraw) {
6732        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6733    }
6734
6735    /**
6736     * Returns whether or not this View draws on its own.
6737     *
6738     * @return true if this view has nothing to draw, false otherwise
6739     */
6740    @ViewDebug.ExportedProperty(category = "drawing")
6741    public boolean willNotDraw() {
6742        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6743    }
6744
6745    /**
6746     * When a View's drawing cache is enabled, drawing is redirected to an
6747     * offscreen bitmap. Some views, like an ImageView, must be able to
6748     * bypass this mechanism if they already draw a single bitmap, to avoid
6749     * unnecessary usage of the memory.
6750     *
6751     * @param willNotCacheDrawing true if this view does not cache its
6752     *        drawing, false otherwise
6753     */
6754    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6755        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6756    }
6757
6758    /**
6759     * Returns whether or not this View can cache its drawing or not.
6760     *
6761     * @return true if this view does not cache its drawing, false otherwise
6762     */
6763    @ViewDebug.ExportedProperty(category = "drawing")
6764    public boolean willNotCacheDrawing() {
6765        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6766    }
6767
6768    /**
6769     * Indicates whether this view reacts to click events or not.
6770     *
6771     * @return true if the view is clickable, false otherwise
6772     *
6773     * @see #setClickable(boolean)
6774     * @attr ref android.R.styleable#View_clickable
6775     */
6776    @ViewDebug.ExportedProperty
6777    public boolean isClickable() {
6778        return (mViewFlags & CLICKABLE) == CLICKABLE;
6779    }
6780
6781    /**
6782     * Enables or disables click events for this view. When a view
6783     * is clickable it will change its state to "pressed" on every click.
6784     * Subclasses should set the view clickable to visually react to
6785     * user's clicks.
6786     *
6787     * @param clickable true to make the view clickable, false otherwise
6788     *
6789     * @see #isClickable()
6790     * @attr ref android.R.styleable#View_clickable
6791     */
6792    public void setClickable(boolean clickable) {
6793        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6794    }
6795
6796    /**
6797     * Indicates whether this view reacts to long click events or not.
6798     *
6799     * @return true if the view is long clickable, false otherwise
6800     *
6801     * @see #setLongClickable(boolean)
6802     * @attr ref android.R.styleable#View_longClickable
6803     */
6804    public boolean isLongClickable() {
6805        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6806    }
6807
6808    /**
6809     * Enables or disables long click events for this view. When a view is long
6810     * clickable it reacts to the user holding down the button for a longer
6811     * duration than a tap. This event can either launch the listener or a
6812     * context menu.
6813     *
6814     * @param longClickable true to make the view long clickable, false otherwise
6815     * @see #isLongClickable()
6816     * @attr ref android.R.styleable#View_longClickable
6817     */
6818    public void setLongClickable(boolean longClickable) {
6819        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6820    }
6821
6822    /**
6823     * Sets the pressed state for this view and provides a touch coordinate for
6824     * animation hinting.
6825     *
6826     * @param pressed Pass true to set the View's internal state to "pressed",
6827     *            or false to reverts the View's internal state from a
6828     *            previously set "pressed" state.
6829     * @param x The x coordinate of the touch that caused the press
6830     * @param y The y coordinate of the touch that caused the press
6831     */
6832    private void setPressed(boolean pressed, float x, float y) {
6833        if (pressed) {
6834            drawableHotspotChanged(x, y);
6835        }
6836
6837        setPressed(pressed);
6838    }
6839
6840    /**
6841     * Sets the pressed state for this view.
6842     *
6843     * @see #isClickable()
6844     * @see #setClickable(boolean)
6845     *
6846     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6847     *        the View's internal state from a previously set "pressed" state.
6848     */
6849    public void setPressed(boolean pressed) {
6850        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6851
6852        if (pressed) {
6853            mPrivateFlags |= PFLAG_PRESSED;
6854        } else {
6855            mPrivateFlags &= ~PFLAG_PRESSED;
6856        }
6857
6858        if (needsRefresh) {
6859            refreshDrawableState();
6860        }
6861        dispatchSetPressed(pressed);
6862    }
6863
6864    /**
6865     * Dispatch setPressed to all of this View's children.
6866     *
6867     * @see #setPressed(boolean)
6868     *
6869     * @param pressed The new pressed state
6870     */
6871    protected void dispatchSetPressed(boolean pressed) {
6872    }
6873
6874    /**
6875     * Indicates whether the view is currently in pressed state. Unless
6876     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6877     * the pressed state.
6878     *
6879     * @see #setPressed(boolean)
6880     * @see #isClickable()
6881     * @see #setClickable(boolean)
6882     *
6883     * @return true if the view is currently pressed, false otherwise
6884     */
6885    public boolean isPressed() {
6886        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6887    }
6888
6889    /**
6890     * Indicates whether this view will save its state (that is,
6891     * whether its {@link #onSaveInstanceState} method will be called).
6892     *
6893     * @return Returns true if the view state saving is enabled, else false.
6894     *
6895     * @see #setSaveEnabled(boolean)
6896     * @attr ref android.R.styleable#View_saveEnabled
6897     */
6898    public boolean isSaveEnabled() {
6899        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6900    }
6901
6902    /**
6903     * Controls whether the saving of this view's state is
6904     * enabled (that is, whether its {@link #onSaveInstanceState} method
6905     * will be called).  Note that even if freezing is enabled, the
6906     * view still must have an id assigned to it (via {@link #setId(int)})
6907     * for its state to be saved.  This flag can only disable the
6908     * saving of this view; any child views may still have their state saved.
6909     *
6910     * @param enabled Set to false to <em>disable</em> state saving, or true
6911     * (the default) to allow it.
6912     *
6913     * @see #isSaveEnabled()
6914     * @see #setId(int)
6915     * @see #onSaveInstanceState()
6916     * @attr ref android.R.styleable#View_saveEnabled
6917     */
6918    public void setSaveEnabled(boolean enabled) {
6919        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6920    }
6921
6922    /**
6923     * Gets whether the framework should discard touches when the view's
6924     * window is obscured by another visible window.
6925     * Refer to the {@link View} security documentation for more details.
6926     *
6927     * @return True if touch filtering is enabled.
6928     *
6929     * @see #setFilterTouchesWhenObscured(boolean)
6930     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6931     */
6932    @ViewDebug.ExportedProperty
6933    public boolean getFilterTouchesWhenObscured() {
6934        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6935    }
6936
6937    /**
6938     * Sets whether the framework should discard touches when the view's
6939     * window is obscured by another visible window.
6940     * Refer to the {@link View} security documentation for more details.
6941     *
6942     * @param enabled True if touch filtering should be enabled.
6943     *
6944     * @see #getFilterTouchesWhenObscured
6945     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6946     */
6947    public void setFilterTouchesWhenObscured(boolean enabled) {
6948        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6949                FILTER_TOUCHES_WHEN_OBSCURED);
6950    }
6951
6952    /**
6953     * Indicates whether the entire hierarchy under this view will save its
6954     * state when a state saving traversal occurs from its parent.  The default
6955     * is true; if false, these views will not be saved unless
6956     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6957     *
6958     * @return Returns true if the view state saving from parent is enabled, else false.
6959     *
6960     * @see #setSaveFromParentEnabled(boolean)
6961     */
6962    public boolean isSaveFromParentEnabled() {
6963        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6964    }
6965
6966    /**
6967     * Controls whether the entire hierarchy under this view will save its
6968     * state when a state saving traversal occurs from its parent.  The default
6969     * is true; if false, these views will not be saved unless
6970     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6971     *
6972     * @param enabled Set to false to <em>disable</em> state saving, or true
6973     * (the default) to allow it.
6974     *
6975     * @see #isSaveFromParentEnabled()
6976     * @see #setId(int)
6977     * @see #onSaveInstanceState()
6978     */
6979    public void setSaveFromParentEnabled(boolean enabled) {
6980        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6981    }
6982
6983
6984    /**
6985     * Returns whether this View is able to take focus.
6986     *
6987     * @return True if this view can take focus, or false otherwise.
6988     * @attr ref android.R.styleable#View_focusable
6989     */
6990    @ViewDebug.ExportedProperty(category = "focus")
6991    public final boolean isFocusable() {
6992        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6993    }
6994
6995    /**
6996     * When a view is focusable, it may not want to take focus when in touch mode.
6997     * For example, a button would like focus when the user is navigating via a D-pad
6998     * so that the user can click on it, but once the user starts touching the screen,
6999     * the button shouldn't take focus
7000     * @return Whether the view is focusable in touch mode.
7001     * @attr ref android.R.styleable#View_focusableInTouchMode
7002     */
7003    @ViewDebug.ExportedProperty
7004    public final boolean isFocusableInTouchMode() {
7005        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7006    }
7007
7008    /**
7009     * Find the nearest view in the specified direction that can take focus.
7010     * This does not actually give focus to that view.
7011     *
7012     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7013     *
7014     * @return The nearest focusable in the specified direction, or null if none
7015     *         can be found.
7016     */
7017    public View focusSearch(@FocusRealDirection int direction) {
7018        if (mParent != null) {
7019            return mParent.focusSearch(this, direction);
7020        } else {
7021            return null;
7022        }
7023    }
7024
7025    /**
7026     * This method is the last chance for the focused view and its ancestors to
7027     * respond to an arrow key. This is called when the focused view did not
7028     * consume the key internally, nor could the view system find a new view in
7029     * the requested direction to give focus to.
7030     *
7031     * @param focused The currently focused view.
7032     * @param direction The direction focus wants to move. One of FOCUS_UP,
7033     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7034     * @return True if the this view consumed this unhandled move.
7035     */
7036    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7037        return false;
7038    }
7039
7040    /**
7041     * If a user manually specified the next view id for a particular direction,
7042     * use the root to look up the view.
7043     * @param root The root view of the hierarchy containing this view.
7044     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7045     * or FOCUS_BACKWARD.
7046     * @return The user specified next view, or null if there is none.
7047     */
7048    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7049        switch (direction) {
7050            case FOCUS_LEFT:
7051                if (mNextFocusLeftId == View.NO_ID) return null;
7052                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7053            case FOCUS_RIGHT:
7054                if (mNextFocusRightId == View.NO_ID) return null;
7055                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7056            case FOCUS_UP:
7057                if (mNextFocusUpId == View.NO_ID) return null;
7058                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7059            case FOCUS_DOWN:
7060                if (mNextFocusDownId == View.NO_ID) return null;
7061                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7062            case FOCUS_FORWARD:
7063                if (mNextFocusForwardId == View.NO_ID) return null;
7064                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7065            case FOCUS_BACKWARD: {
7066                if (mID == View.NO_ID) return null;
7067                final int id = mID;
7068                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7069                    @Override
7070                    public boolean apply(View t) {
7071                        return t.mNextFocusForwardId == id;
7072                    }
7073                });
7074            }
7075        }
7076        return null;
7077    }
7078
7079    private View findViewInsideOutShouldExist(View root, int id) {
7080        if (mMatchIdPredicate == null) {
7081            mMatchIdPredicate = new MatchIdPredicate();
7082        }
7083        mMatchIdPredicate.mId = id;
7084        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7085        if (result == null) {
7086            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7087        }
7088        return result;
7089    }
7090
7091    /**
7092     * Find and return all focusable views that are descendants of this view,
7093     * possibly including this view if it is focusable itself.
7094     *
7095     * @param direction The direction of the focus
7096     * @return A list of focusable views
7097     */
7098    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7099        ArrayList<View> result = new ArrayList<View>(24);
7100        addFocusables(result, direction);
7101        return result;
7102    }
7103
7104    /**
7105     * Add any focusable views that are descendants of this view (possibly
7106     * including this view if it is focusable itself) to views.  If we are in touch mode,
7107     * only add views that are also focusable in touch mode.
7108     *
7109     * @param views Focusable views found so far
7110     * @param direction The direction of the focus
7111     */
7112    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7113        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7114    }
7115
7116    /**
7117     * Adds any focusable views that are descendants of this view (possibly
7118     * including this view if it is focusable itself) to views. This method
7119     * adds all focusable views regardless if we are in touch mode or
7120     * only views focusable in touch mode if we are in touch mode or
7121     * only views that can take accessibility focus if accessibility is enabeld
7122     * depending on the focusable mode paramater.
7123     *
7124     * @param views Focusable views found so far or null if all we are interested is
7125     *        the number of focusables.
7126     * @param direction The direction of the focus.
7127     * @param focusableMode The type of focusables to be added.
7128     *
7129     * @see #FOCUSABLES_ALL
7130     * @see #FOCUSABLES_TOUCH_MODE
7131     */
7132    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7133            @FocusableMode int focusableMode) {
7134        if (views == null) {
7135            return;
7136        }
7137        if (!isFocusable()) {
7138            return;
7139        }
7140        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7141                && isInTouchMode() && !isFocusableInTouchMode()) {
7142            return;
7143        }
7144        views.add(this);
7145    }
7146
7147    /**
7148     * Finds the Views that contain given text. The containment is case insensitive.
7149     * The search is performed by either the text that the View renders or the content
7150     * description that describes the view for accessibility purposes and the view does
7151     * not render or both. Clients can specify how the search is to be performed via
7152     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7153     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7154     *
7155     * @param outViews The output list of matching Views.
7156     * @param searched The text to match against.
7157     *
7158     * @see #FIND_VIEWS_WITH_TEXT
7159     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7160     * @see #setContentDescription(CharSequence)
7161     */
7162    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7163            @FindViewFlags int flags) {
7164        if (getAccessibilityNodeProvider() != null) {
7165            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7166                outViews.add(this);
7167            }
7168        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7169                && (searched != null && searched.length() > 0)
7170                && (mContentDescription != null && mContentDescription.length() > 0)) {
7171            String searchedLowerCase = searched.toString().toLowerCase();
7172            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7173            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7174                outViews.add(this);
7175            }
7176        }
7177    }
7178
7179    /**
7180     * Find and return all touchable views that are descendants of this view,
7181     * possibly including this view if it is touchable itself.
7182     *
7183     * @return A list of touchable views
7184     */
7185    public ArrayList<View> getTouchables() {
7186        ArrayList<View> result = new ArrayList<View>();
7187        addTouchables(result);
7188        return result;
7189    }
7190
7191    /**
7192     * Add any touchable views that are descendants of this view (possibly
7193     * including this view if it is touchable itself) to views.
7194     *
7195     * @param views Touchable views found so far
7196     */
7197    public void addTouchables(ArrayList<View> views) {
7198        final int viewFlags = mViewFlags;
7199
7200        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7201                && (viewFlags & ENABLED_MASK) == ENABLED) {
7202            views.add(this);
7203        }
7204    }
7205
7206    /**
7207     * Returns whether this View is accessibility focused.
7208     *
7209     * @return True if this View is accessibility focused.
7210     */
7211    public boolean isAccessibilityFocused() {
7212        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7213    }
7214
7215    /**
7216     * Call this to try to give accessibility focus to this view.
7217     *
7218     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7219     * returns false or the view is no visible or the view already has accessibility
7220     * focus.
7221     *
7222     * See also {@link #focusSearch(int)}, which is what you call to say that you
7223     * have focus, and you want your parent to look for the next one.
7224     *
7225     * @return Whether this view actually took accessibility focus.
7226     *
7227     * @hide
7228     */
7229    public boolean requestAccessibilityFocus() {
7230        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7231        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7232            return false;
7233        }
7234        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7235            return false;
7236        }
7237        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7238            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7239            ViewRootImpl viewRootImpl = getViewRootImpl();
7240            if (viewRootImpl != null) {
7241                viewRootImpl.setAccessibilityFocus(this, null);
7242            }
7243            invalidate();
7244            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7245            return true;
7246        }
7247        return false;
7248    }
7249
7250    /**
7251     * Call this to try to clear accessibility focus of this view.
7252     *
7253     * See also {@link #focusSearch(int)}, which is what you call to say that you
7254     * have focus, and you want your parent to look for the next one.
7255     *
7256     * @hide
7257     */
7258    public void clearAccessibilityFocus() {
7259        clearAccessibilityFocusNoCallbacks();
7260        // Clear the global reference of accessibility focus if this
7261        // view or any of its descendants had accessibility focus.
7262        ViewRootImpl viewRootImpl = getViewRootImpl();
7263        if (viewRootImpl != null) {
7264            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7265            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7266                viewRootImpl.setAccessibilityFocus(null, null);
7267            }
7268        }
7269    }
7270
7271    private void sendAccessibilityHoverEvent(int eventType) {
7272        // Since we are not delivering to a client accessibility events from not
7273        // important views (unless the clinet request that) we need to fire the
7274        // event from the deepest view exposed to the client. As a consequence if
7275        // the user crosses a not exposed view the client will see enter and exit
7276        // of the exposed predecessor followed by and enter and exit of that same
7277        // predecessor when entering and exiting the not exposed descendant. This
7278        // is fine since the client has a clear idea which view is hovered at the
7279        // price of a couple more events being sent. This is a simple and
7280        // working solution.
7281        View source = this;
7282        while (true) {
7283            if (source.includeForAccessibility()) {
7284                source.sendAccessibilityEvent(eventType);
7285                return;
7286            }
7287            ViewParent parent = source.getParent();
7288            if (parent instanceof View) {
7289                source = (View) parent;
7290            } else {
7291                return;
7292            }
7293        }
7294    }
7295
7296    /**
7297     * Clears accessibility focus without calling any callback methods
7298     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7299     * is used for clearing accessibility focus when giving this focus to
7300     * another view.
7301     */
7302    void clearAccessibilityFocusNoCallbacks() {
7303        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7304            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7305            invalidate();
7306            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7307        }
7308    }
7309
7310    /**
7311     * Call this to try to give focus to a specific view or to one of its
7312     * descendants.
7313     *
7314     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7315     * false), or if it is focusable and it is not focusable in touch mode
7316     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7317     *
7318     * See also {@link #focusSearch(int)}, which is what you call to say that you
7319     * have focus, and you want your parent to look for the next one.
7320     *
7321     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7322     * {@link #FOCUS_DOWN} and <code>null</code>.
7323     *
7324     * @return Whether this view or one of its descendants actually took focus.
7325     */
7326    public final boolean requestFocus() {
7327        return requestFocus(View.FOCUS_DOWN);
7328    }
7329
7330    /**
7331     * Call this to try to give focus to a specific view or to one of its
7332     * descendants and give it a hint about what direction focus is heading.
7333     *
7334     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7335     * false), or if it is focusable and it is not focusable in touch mode
7336     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7337     *
7338     * See also {@link #focusSearch(int)}, which is what you call to say that you
7339     * have focus, and you want your parent to look for the next one.
7340     *
7341     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7342     * <code>null</code> set for the previously focused rectangle.
7343     *
7344     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7345     * @return Whether this view or one of its descendants actually took focus.
7346     */
7347    public final boolean requestFocus(int direction) {
7348        return requestFocus(direction, null);
7349    }
7350
7351    /**
7352     * Call this to try to give focus to a specific view or to one of its descendants
7353     * and give it hints about the direction and a specific rectangle that the focus
7354     * is coming from.  The rectangle can help give larger views a finer grained hint
7355     * about where focus is coming from, and therefore, where to show selection, or
7356     * forward focus change internally.
7357     *
7358     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7359     * false), or if it is focusable and it is not focusable in touch mode
7360     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7361     *
7362     * A View will not take focus if it is not visible.
7363     *
7364     * A View will not take focus if one of its parents has
7365     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7366     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7367     *
7368     * See also {@link #focusSearch(int)}, which is what you call to say that you
7369     * have focus, and you want your parent to look for the next one.
7370     *
7371     * You may wish to override this method if your custom {@link View} has an internal
7372     * {@link View} that it wishes to forward the request to.
7373     *
7374     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7375     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7376     *        to give a finer grained hint about where focus is coming from.  May be null
7377     *        if there is no hint.
7378     * @return Whether this view or one of its descendants actually took focus.
7379     */
7380    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7381        return requestFocusNoSearch(direction, previouslyFocusedRect);
7382    }
7383
7384    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7385        // need to be focusable
7386        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7387                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7388            return false;
7389        }
7390
7391        // need to be focusable in touch mode if in touch mode
7392        if (isInTouchMode() &&
7393            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7394               return false;
7395        }
7396
7397        // need to not have any parents blocking us
7398        if (hasAncestorThatBlocksDescendantFocus()) {
7399            return false;
7400        }
7401
7402        handleFocusGainInternal(direction, previouslyFocusedRect);
7403        return true;
7404    }
7405
7406    /**
7407     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7408     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7409     * touch mode to request focus when they are touched.
7410     *
7411     * @return Whether this view or one of its descendants actually took focus.
7412     *
7413     * @see #isInTouchMode()
7414     *
7415     */
7416    public final boolean requestFocusFromTouch() {
7417        // Leave touch mode if we need to
7418        if (isInTouchMode()) {
7419            ViewRootImpl viewRoot = getViewRootImpl();
7420            if (viewRoot != null) {
7421                viewRoot.ensureTouchMode(false);
7422            }
7423        }
7424        return requestFocus(View.FOCUS_DOWN);
7425    }
7426
7427    /**
7428     * @return Whether any ancestor of this view blocks descendant focus.
7429     */
7430    private boolean hasAncestorThatBlocksDescendantFocus() {
7431        ViewParent ancestor = mParent;
7432        while (ancestor instanceof ViewGroup) {
7433            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7434            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7435                return true;
7436            } else {
7437                ancestor = vgAncestor.getParent();
7438            }
7439        }
7440        return false;
7441    }
7442
7443    /**
7444     * Gets the mode for determining whether this View is important for accessibility
7445     * which is if it fires accessibility events and if it is reported to
7446     * accessibility services that query the screen.
7447     *
7448     * @return The mode for determining whether a View is important for accessibility.
7449     *
7450     * @attr ref android.R.styleable#View_importantForAccessibility
7451     *
7452     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7453     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7454     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7455     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7456     */
7457    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7458            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7459            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7460            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7461            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7462                    to = "noHideDescendants")
7463        })
7464    public int getImportantForAccessibility() {
7465        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7466                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7467    }
7468
7469    /**
7470     * Sets the live region mode for this view. This indicates to accessibility
7471     * services whether they should automatically notify the user about changes
7472     * to the view's content description or text, or to the content descriptions
7473     * or text of the view's children (where applicable).
7474     * <p>
7475     * For example, in a login screen with a TextView that displays an "incorrect
7476     * password" notification, that view should be marked as a live region with
7477     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7478     * <p>
7479     * To disable change notifications for this view, use
7480     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7481     * mode for most views.
7482     * <p>
7483     * To indicate that the user should be notified of changes, use
7484     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7485     * <p>
7486     * If the view's changes should interrupt ongoing speech and notify the user
7487     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7488     *
7489     * @param mode The live region mode for this view, one of:
7490     *        <ul>
7491     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7492     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7493     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7494     *        </ul>
7495     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7496     */
7497    public void setAccessibilityLiveRegion(int mode) {
7498        if (mode != getAccessibilityLiveRegion()) {
7499            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7500            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7501                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7502            notifyViewAccessibilityStateChangedIfNeeded(
7503                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7504        }
7505    }
7506
7507    /**
7508     * Gets the live region mode for this View.
7509     *
7510     * @return The live region mode for the view.
7511     *
7512     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7513     *
7514     * @see #setAccessibilityLiveRegion(int)
7515     */
7516    public int getAccessibilityLiveRegion() {
7517        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7518                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7519    }
7520
7521    /**
7522     * Sets how to determine whether this view is important for accessibility
7523     * which is if it fires accessibility events and if it is reported to
7524     * accessibility services that query the screen.
7525     *
7526     * @param mode How to determine whether this view is important for accessibility.
7527     *
7528     * @attr ref android.R.styleable#View_importantForAccessibility
7529     *
7530     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7531     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7532     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7533     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7534     */
7535    public void setImportantForAccessibility(int mode) {
7536        final int oldMode = getImportantForAccessibility();
7537        if (mode != oldMode) {
7538            // If we're moving between AUTO and another state, we might not need
7539            // to send a subtree changed notification. We'll store the computed
7540            // importance, since we'll need to check it later to make sure.
7541            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7542                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7543            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7544            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7545            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7546                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7547            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7548                notifySubtreeAccessibilityStateChangedIfNeeded();
7549            } else {
7550                notifyViewAccessibilityStateChangedIfNeeded(
7551                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7552            }
7553        }
7554    }
7555
7556    /**
7557     * Computes whether this view should be exposed for accessibility. In
7558     * general, views that are interactive or provide information are exposed
7559     * while views that serve only as containers are hidden.
7560     * <p>
7561     * If an ancestor of this view has importance
7562     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7563     * returns <code>false</code>.
7564     * <p>
7565     * Otherwise, the value is computed according to the view's
7566     * {@link #getImportantForAccessibility()} value:
7567     * <ol>
7568     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7569     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7570     * </code>
7571     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7572     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7573     * view satisfies any of the following:
7574     * <ul>
7575     * <li>Is actionable, e.g. {@link #isClickable()},
7576     * {@link #isLongClickable()}, or {@link #isFocusable()}
7577     * <li>Has an {@link AccessibilityDelegate}
7578     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7579     * {@link OnKeyListener}, etc.
7580     * <li>Is an accessibility live region, e.g.
7581     * {@link #getAccessibilityLiveRegion()} is not
7582     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7583     * </ul>
7584     * </ol>
7585     *
7586     * @return Whether the view is exposed for accessibility.
7587     * @see #setImportantForAccessibility(int)
7588     * @see #getImportantForAccessibility()
7589     */
7590    public boolean isImportantForAccessibility() {
7591        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7592                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7593        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7594                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7595            return false;
7596        }
7597
7598        // Check parent mode to ensure we're not hidden.
7599        ViewParent parent = mParent;
7600        while (parent instanceof View) {
7601            if (((View) parent).getImportantForAccessibility()
7602                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7603                return false;
7604            }
7605            parent = parent.getParent();
7606        }
7607
7608        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7609                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7610                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7611    }
7612
7613    /**
7614     * Gets the parent for accessibility purposes. Note that the parent for
7615     * accessibility is not necessary the immediate parent. It is the first
7616     * predecessor that is important for accessibility.
7617     *
7618     * @return The parent for accessibility purposes.
7619     */
7620    public ViewParent getParentForAccessibility() {
7621        if (mParent instanceof View) {
7622            View parentView = (View) mParent;
7623            if (parentView.includeForAccessibility()) {
7624                return mParent;
7625            } else {
7626                return mParent.getParentForAccessibility();
7627            }
7628        }
7629        return null;
7630    }
7631
7632    /**
7633     * Adds the children of a given View for accessibility. Since some Views are
7634     * not important for accessibility the children for accessibility are not
7635     * necessarily direct children of the view, rather they are the first level of
7636     * descendants important for accessibility.
7637     *
7638     * @param children The list of children for accessibility.
7639     */
7640    public void addChildrenForAccessibility(ArrayList<View> children) {
7641
7642    }
7643
7644    /**
7645     * Whether to regard this view for accessibility. A view is regarded for
7646     * accessibility if it is important for accessibility or the querying
7647     * accessibility service has explicitly requested that view not
7648     * important for accessibility are regarded.
7649     *
7650     * @return Whether to regard the view for accessibility.
7651     *
7652     * @hide
7653     */
7654    public boolean includeForAccessibility() {
7655        if (mAttachInfo != null) {
7656            return (mAttachInfo.mAccessibilityFetchFlags
7657                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7658                    || isImportantForAccessibility();
7659        }
7660        return false;
7661    }
7662
7663    /**
7664     * Returns whether the View is considered actionable from
7665     * accessibility perspective. Such view are important for
7666     * accessibility.
7667     *
7668     * @return True if the view is actionable for accessibility.
7669     *
7670     * @hide
7671     */
7672    public boolean isActionableForAccessibility() {
7673        return (isClickable() || isLongClickable() || isFocusable());
7674    }
7675
7676    /**
7677     * Returns whether the View has registered callbacks which makes it
7678     * important for accessibility.
7679     *
7680     * @return True if the view is actionable for accessibility.
7681     */
7682    private boolean hasListenersForAccessibility() {
7683        ListenerInfo info = getListenerInfo();
7684        return mTouchDelegate != null || info.mOnKeyListener != null
7685                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7686                || info.mOnHoverListener != null || info.mOnDragListener != null;
7687    }
7688
7689    /**
7690     * Notifies that the accessibility state of this view changed. The change
7691     * is local to this view and does not represent structural changes such
7692     * as children and parent. For example, the view became focusable. The
7693     * notification is at at most once every
7694     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7695     * to avoid unnecessary load to the system. Also once a view has a pending
7696     * notification this method is a NOP until the notification has been sent.
7697     *
7698     * @hide
7699     */
7700    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7701        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7702            return;
7703        }
7704        if (mSendViewStateChangedAccessibilityEvent == null) {
7705            mSendViewStateChangedAccessibilityEvent =
7706                    new SendViewStateChangedAccessibilityEvent();
7707        }
7708        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7709    }
7710
7711    /**
7712     * Notifies that the accessibility state of this view changed. The change
7713     * is *not* local to this view and does represent structural changes such
7714     * as children and parent. For example, the view size changed. The
7715     * notification is at at most once every
7716     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7717     * to avoid unnecessary load to the system. Also once a view has a pending
7718     * notification this method is a NOP until the notification has been sent.
7719     *
7720     * @hide
7721     */
7722    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7723        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7724            return;
7725        }
7726        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7727            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7728            if (mParent != null) {
7729                try {
7730                    mParent.notifySubtreeAccessibilityStateChanged(
7731                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7732                } catch (AbstractMethodError e) {
7733                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7734                            " does not fully implement ViewParent", e);
7735                }
7736            }
7737        }
7738    }
7739
7740    /**
7741     * Reset the flag indicating the accessibility state of the subtree rooted
7742     * at this view changed.
7743     */
7744    void resetSubtreeAccessibilityStateChanged() {
7745        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7746    }
7747
7748    /**
7749     * Performs the specified accessibility action on the view. For
7750     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7751     * <p>
7752     * If an {@link AccessibilityDelegate} has been specified via calling
7753     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7754     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7755     * is responsible for handling this call.
7756     * </p>
7757     *
7758     * @param action The action to perform.
7759     * @param arguments Optional action arguments.
7760     * @return Whether the action was performed.
7761     */
7762    public boolean performAccessibilityAction(int action, Bundle arguments) {
7763      if (mAccessibilityDelegate != null) {
7764          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7765      } else {
7766          return performAccessibilityActionInternal(action, arguments);
7767      }
7768    }
7769
7770   /**
7771    * @see #performAccessibilityAction(int, Bundle)
7772    *
7773    * Note: Called from the default {@link AccessibilityDelegate}.
7774    */
7775    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7776        switch (action) {
7777            case AccessibilityNodeInfo.ACTION_CLICK: {
7778                if (isClickable()) {
7779                    performClick();
7780                    return true;
7781                }
7782            } break;
7783            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7784                if (isLongClickable()) {
7785                    performLongClick();
7786                    return true;
7787                }
7788            } break;
7789            case AccessibilityNodeInfo.ACTION_FOCUS: {
7790                if (!hasFocus()) {
7791                    // Get out of touch mode since accessibility
7792                    // wants to move focus around.
7793                    getViewRootImpl().ensureTouchMode(false);
7794                    return requestFocus();
7795                }
7796            } break;
7797            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7798                if (hasFocus()) {
7799                    clearFocus();
7800                    return !isFocused();
7801                }
7802            } break;
7803            case AccessibilityNodeInfo.ACTION_SELECT: {
7804                if (!isSelected()) {
7805                    setSelected(true);
7806                    return isSelected();
7807                }
7808            } break;
7809            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7810                if (isSelected()) {
7811                    setSelected(false);
7812                    return !isSelected();
7813                }
7814            } break;
7815            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7816                if (!isAccessibilityFocused()) {
7817                    return requestAccessibilityFocus();
7818                }
7819            } break;
7820            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7821                if (isAccessibilityFocused()) {
7822                    clearAccessibilityFocus();
7823                    return true;
7824                }
7825            } break;
7826            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7827                if (arguments != null) {
7828                    final int granularity = arguments.getInt(
7829                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7830                    final boolean extendSelection = arguments.getBoolean(
7831                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7832                    return traverseAtGranularity(granularity, true, extendSelection);
7833                }
7834            } break;
7835            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7836                if (arguments != null) {
7837                    final int granularity = arguments.getInt(
7838                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7839                    final boolean extendSelection = arguments.getBoolean(
7840                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7841                    return traverseAtGranularity(granularity, false, extendSelection);
7842                }
7843            } break;
7844            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7845                CharSequence text = getIterableTextForAccessibility();
7846                if (text == null) {
7847                    return false;
7848                }
7849                final int start = (arguments != null) ? arguments.getInt(
7850                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7851                final int end = (arguments != null) ? arguments.getInt(
7852                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7853                // Only cursor position can be specified (selection length == 0)
7854                if ((getAccessibilitySelectionStart() != start
7855                        || getAccessibilitySelectionEnd() != end)
7856                        && (start == end)) {
7857                    setAccessibilitySelection(start, end);
7858                    notifyViewAccessibilityStateChangedIfNeeded(
7859                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7860                    return true;
7861                }
7862            } break;
7863        }
7864        return false;
7865    }
7866
7867    private boolean traverseAtGranularity(int granularity, boolean forward,
7868            boolean extendSelection) {
7869        CharSequence text = getIterableTextForAccessibility();
7870        if (text == null || text.length() == 0) {
7871            return false;
7872        }
7873        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7874        if (iterator == null) {
7875            return false;
7876        }
7877        int current = getAccessibilitySelectionEnd();
7878        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7879            current = forward ? 0 : text.length();
7880        }
7881        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7882        if (range == null) {
7883            return false;
7884        }
7885        final int segmentStart = range[0];
7886        final int segmentEnd = range[1];
7887        int selectionStart;
7888        int selectionEnd;
7889        if (extendSelection && isAccessibilitySelectionExtendable()) {
7890            selectionStart = getAccessibilitySelectionStart();
7891            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7892                selectionStart = forward ? segmentStart : segmentEnd;
7893            }
7894            selectionEnd = forward ? segmentEnd : segmentStart;
7895        } else {
7896            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7897        }
7898        setAccessibilitySelection(selectionStart, selectionEnd);
7899        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7900                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7901        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7902        return true;
7903    }
7904
7905    /**
7906     * Gets the text reported for accessibility purposes.
7907     *
7908     * @return The accessibility text.
7909     *
7910     * @hide
7911     */
7912    public CharSequence getIterableTextForAccessibility() {
7913        return getContentDescription();
7914    }
7915
7916    /**
7917     * Gets whether accessibility selection can be extended.
7918     *
7919     * @return If selection is extensible.
7920     *
7921     * @hide
7922     */
7923    public boolean isAccessibilitySelectionExtendable() {
7924        return false;
7925    }
7926
7927    /**
7928     * @hide
7929     */
7930    public int getAccessibilitySelectionStart() {
7931        return mAccessibilityCursorPosition;
7932    }
7933
7934    /**
7935     * @hide
7936     */
7937    public int getAccessibilitySelectionEnd() {
7938        return getAccessibilitySelectionStart();
7939    }
7940
7941    /**
7942     * @hide
7943     */
7944    public void setAccessibilitySelection(int start, int end) {
7945        if (start ==  end && end == mAccessibilityCursorPosition) {
7946            return;
7947        }
7948        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7949            mAccessibilityCursorPosition = start;
7950        } else {
7951            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7952        }
7953        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7954    }
7955
7956    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7957            int fromIndex, int toIndex) {
7958        if (mParent == null) {
7959            return;
7960        }
7961        AccessibilityEvent event = AccessibilityEvent.obtain(
7962                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7963        onInitializeAccessibilityEvent(event);
7964        onPopulateAccessibilityEvent(event);
7965        event.setFromIndex(fromIndex);
7966        event.setToIndex(toIndex);
7967        event.setAction(action);
7968        event.setMovementGranularity(granularity);
7969        mParent.requestSendAccessibilityEvent(this, event);
7970    }
7971
7972    /**
7973     * @hide
7974     */
7975    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7976        switch (granularity) {
7977            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7978                CharSequence text = getIterableTextForAccessibility();
7979                if (text != null && text.length() > 0) {
7980                    CharacterTextSegmentIterator iterator =
7981                        CharacterTextSegmentIterator.getInstance(
7982                                mContext.getResources().getConfiguration().locale);
7983                    iterator.initialize(text.toString());
7984                    return iterator;
7985                }
7986            } break;
7987            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7988                CharSequence text = getIterableTextForAccessibility();
7989                if (text != null && text.length() > 0) {
7990                    WordTextSegmentIterator iterator =
7991                        WordTextSegmentIterator.getInstance(
7992                                mContext.getResources().getConfiguration().locale);
7993                    iterator.initialize(text.toString());
7994                    return iterator;
7995                }
7996            } break;
7997            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7998                CharSequence text = getIterableTextForAccessibility();
7999                if (text != null && text.length() > 0) {
8000                    ParagraphTextSegmentIterator iterator =
8001                        ParagraphTextSegmentIterator.getInstance();
8002                    iterator.initialize(text.toString());
8003                    return iterator;
8004                }
8005            } break;
8006        }
8007        return null;
8008    }
8009
8010    /**
8011     * @hide
8012     */
8013    public void dispatchStartTemporaryDetach() {
8014        onStartTemporaryDetach();
8015    }
8016
8017    /**
8018     * This is called when a container is going to temporarily detach a child, with
8019     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8020     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8021     * {@link #onDetachedFromWindow()} when the container is done.
8022     */
8023    public void onStartTemporaryDetach() {
8024        removeUnsetPressCallback();
8025        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8026    }
8027
8028    /**
8029     * @hide
8030     */
8031    public void dispatchFinishTemporaryDetach() {
8032        onFinishTemporaryDetach();
8033    }
8034
8035    /**
8036     * Called after {@link #onStartTemporaryDetach} when the container is done
8037     * changing the view.
8038     */
8039    public void onFinishTemporaryDetach() {
8040    }
8041
8042    /**
8043     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8044     * for this view's window.  Returns null if the view is not currently attached
8045     * to the window.  Normally you will not need to use this directly, but
8046     * just use the standard high-level event callbacks like
8047     * {@link #onKeyDown(int, KeyEvent)}.
8048     */
8049    public KeyEvent.DispatcherState getKeyDispatcherState() {
8050        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8051    }
8052
8053    /**
8054     * Dispatch a key event before it is processed by any input method
8055     * associated with the view hierarchy.  This can be used to intercept
8056     * key events in special situations before the IME consumes them; a
8057     * typical example would be handling the BACK key to update the application's
8058     * UI instead of allowing the IME to see it and close itself.
8059     *
8060     * @param event The key event to be dispatched.
8061     * @return True if the event was handled, false otherwise.
8062     */
8063    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8064        return onKeyPreIme(event.getKeyCode(), event);
8065    }
8066
8067    /**
8068     * Dispatch a key event to the next view on the focus path. This path runs
8069     * from the top of the view tree down to the currently focused view. If this
8070     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8071     * the next node down the focus path. This method also fires any key
8072     * listeners.
8073     *
8074     * @param event The key event to be dispatched.
8075     * @return True if the event was handled, false otherwise.
8076     */
8077    public boolean dispatchKeyEvent(KeyEvent event) {
8078        if (mInputEventConsistencyVerifier != null) {
8079            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8080        }
8081
8082        // Give any attached key listener a first crack at the event.
8083        //noinspection SimplifiableIfStatement
8084        ListenerInfo li = mListenerInfo;
8085        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8086                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8087            return true;
8088        }
8089
8090        if (event.dispatch(this, mAttachInfo != null
8091                ? mAttachInfo.mKeyDispatchState : null, this)) {
8092            return true;
8093        }
8094
8095        if (mInputEventConsistencyVerifier != null) {
8096            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8097        }
8098        return false;
8099    }
8100
8101    /**
8102     * Dispatches a key shortcut event.
8103     *
8104     * @param event The key event to be dispatched.
8105     * @return True if the event was handled by the view, false otherwise.
8106     */
8107    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8108        return onKeyShortcut(event.getKeyCode(), event);
8109    }
8110
8111    /**
8112     * Pass the touch screen motion event down to the target view, or this
8113     * view if it is the target.
8114     *
8115     * @param event The motion event to be dispatched.
8116     * @return True if the event was handled by the view, false otherwise.
8117     */
8118    public boolean dispatchTouchEvent(MotionEvent event) {
8119        boolean result = false;
8120
8121        if (mInputEventConsistencyVerifier != null) {
8122            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8123        }
8124
8125        final int actionMasked = event.getActionMasked();
8126        if (actionMasked == MotionEvent.ACTION_DOWN) {
8127            // Defensive cleanup for new gesture
8128            stopNestedScroll();
8129        }
8130
8131        if (onFilterTouchEventForSecurity(event)) {
8132            //noinspection SimplifiableIfStatement
8133            ListenerInfo li = mListenerInfo;
8134            if (li != null && li.mOnTouchListener != null
8135                    && (mViewFlags & ENABLED_MASK) == ENABLED
8136                    && li.mOnTouchListener.onTouch(this, event)) {
8137                result = true;
8138            }
8139
8140            if (!result && onTouchEvent(event)) {
8141                result = true;
8142            }
8143        }
8144
8145        if (!result && mInputEventConsistencyVerifier != null) {
8146            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8147        }
8148
8149        // Clean up after nested scrolls if this is the end of a gesture;
8150        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8151        // of the gesture.
8152        if (actionMasked == MotionEvent.ACTION_UP ||
8153                actionMasked == MotionEvent.ACTION_CANCEL ||
8154                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8155            stopNestedScroll();
8156        }
8157
8158        return result;
8159    }
8160
8161    /**
8162     * Filter the touch event to apply security policies.
8163     *
8164     * @param event The motion event to be filtered.
8165     * @return True if the event should be dispatched, false if the event should be dropped.
8166     *
8167     * @see #getFilterTouchesWhenObscured
8168     */
8169    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8170        //noinspection RedundantIfStatement
8171        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8172                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8173            // Window is obscured, drop this touch.
8174            return false;
8175        }
8176        return true;
8177    }
8178
8179    /**
8180     * Pass a trackball motion event down to the focused view.
8181     *
8182     * @param event The motion event to be dispatched.
8183     * @return True if the event was handled by the view, false otherwise.
8184     */
8185    public boolean dispatchTrackballEvent(MotionEvent event) {
8186        if (mInputEventConsistencyVerifier != null) {
8187            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8188        }
8189
8190        return onTrackballEvent(event);
8191    }
8192
8193    /**
8194     * Dispatch a generic motion event.
8195     * <p>
8196     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8197     * are delivered to the view under the pointer.  All other generic motion events are
8198     * delivered to the focused view.  Hover events are handled specially and are delivered
8199     * to {@link #onHoverEvent(MotionEvent)}.
8200     * </p>
8201     *
8202     * @param event The motion event to be dispatched.
8203     * @return True if the event was handled by the view, false otherwise.
8204     */
8205    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8206        if (mInputEventConsistencyVerifier != null) {
8207            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8208        }
8209
8210        final int source = event.getSource();
8211        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8212            final int action = event.getAction();
8213            if (action == MotionEvent.ACTION_HOVER_ENTER
8214                    || action == MotionEvent.ACTION_HOVER_MOVE
8215                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8216                if (dispatchHoverEvent(event)) {
8217                    return true;
8218                }
8219            } else if (dispatchGenericPointerEvent(event)) {
8220                return true;
8221            }
8222        } else if (dispatchGenericFocusedEvent(event)) {
8223            return true;
8224        }
8225
8226        if (dispatchGenericMotionEventInternal(event)) {
8227            return true;
8228        }
8229
8230        if (mInputEventConsistencyVerifier != null) {
8231            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8232        }
8233        return false;
8234    }
8235
8236    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8237        //noinspection SimplifiableIfStatement
8238        ListenerInfo li = mListenerInfo;
8239        if (li != null && li.mOnGenericMotionListener != null
8240                && (mViewFlags & ENABLED_MASK) == ENABLED
8241                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8242            return true;
8243        }
8244
8245        if (onGenericMotionEvent(event)) {
8246            return true;
8247        }
8248
8249        if (mInputEventConsistencyVerifier != null) {
8250            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8251        }
8252        return false;
8253    }
8254
8255    /**
8256     * Dispatch a hover event.
8257     * <p>
8258     * Do not call this method directly.
8259     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8260     * </p>
8261     *
8262     * @param event The motion event to be dispatched.
8263     * @return True if the event was handled by the view, false otherwise.
8264     */
8265    protected boolean dispatchHoverEvent(MotionEvent event) {
8266        ListenerInfo li = mListenerInfo;
8267        //noinspection SimplifiableIfStatement
8268        if (li != null && li.mOnHoverListener != null
8269                && (mViewFlags & ENABLED_MASK) == ENABLED
8270                && li.mOnHoverListener.onHover(this, event)) {
8271            return true;
8272        }
8273
8274        return onHoverEvent(event);
8275    }
8276
8277    /**
8278     * Returns true if the view has a child to which it has recently sent
8279     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8280     * it does not have a hovered child, then it must be the innermost hovered view.
8281     * @hide
8282     */
8283    protected boolean hasHoveredChild() {
8284        return false;
8285    }
8286
8287    /**
8288     * Dispatch a generic motion event to the view under the first pointer.
8289     * <p>
8290     * Do not call this method directly.
8291     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8292     * </p>
8293     *
8294     * @param event The motion event to be dispatched.
8295     * @return True if the event was handled by the view, false otherwise.
8296     */
8297    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8298        return false;
8299    }
8300
8301    /**
8302     * Dispatch a generic motion event to the currently focused view.
8303     * <p>
8304     * Do not call this method directly.
8305     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8306     * </p>
8307     *
8308     * @param event The motion event to be dispatched.
8309     * @return True if the event was handled by the view, false otherwise.
8310     */
8311    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8312        return false;
8313    }
8314
8315    /**
8316     * Dispatch a pointer event.
8317     * <p>
8318     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8319     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8320     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8321     * and should not be expected to handle other pointing device features.
8322     * </p>
8323     *
8324     * @param event The motion event to be dispatched.
8325     * @return True if the event was handled by the view, false otherwise.
8326     * @hide
8327     */
8328    public final boolean dispatchPointerEvent(MotionEvent event) {
8329        if (event.isTouchEvent()) {
8330            return dispatchTouchEvent(event);
8331        } else {
8332            return dispatchGenericMotionEvent(event);
8333        }
8334    }
8335
8336    /**
8337     * Called when the window containing this view gains or loses window focus.
8338     * ViewGroups should override to route to their children.
8339     *
8340     * @param hasFocus True if the window containing this view now has focus,
8341     *        false otherwise.
8342     */
8343    public void dispatchWindowFocusChanged(boolean hasFocus) {
8344        onWindowFocusChanged(hasFocus);
8345    }
8346
8347    /**
8348     * Called when the window containing this view gains or loses focus.  Note
8349     * that this is separate from view focus: to receive key events, both
8350     * your view and its window must have focus.  If a window is displayed
8351     * on top of yours that takes input focus, then your own window will lose
8352     * focus but the view focus will remain unchanged.
8353     *
8354     * @param hasWindowFocus True if the window containing this view now has
8355     *        focus, false otherwise.
8356     */
8357    public void onWindowFocusChanged(boolean hasWindowFocus) {
8358        InputMethodManager imm = InputMethodManager.peekInstance();
8359        if (!hasWindowFocus) {
8360            if (isPressed()) {
8361                setPressed(false);
8362            }
8363            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8364                imm.focusOut(this);
8365            }
8366            removeLongPressCallback();
8367            removeTapCallback();
8368            onFocusLost();
8369        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8370            imm.focusIn(this);
8371        }
8372        refreshDrawableState();
8373    }
8374
8375    /**
8376     * Returns true if this view is in a window that currently has window focus.
8377     * Note that this is not the same as the view itself having focus.
8378     *
8379     * @return True if this view is in a window that currently has window focus.
8380     */
8381    public boolean hasWindowFocus() {
8382        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8383    }
8384
8385    /**
8386     * Dispatch a view visibility change down the view hierarchy.
8387     * ViewGroups should override to route to their children.
8388     * @param changedView The view whose visibility changed. Could be 'this' or
8389     * an ancestor view.
8390     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8391     * {@link #INVISIBLE} or {@link #GONE}.
8392     */
8393    protected void dispatchVisibilityChanged(@NonNull View changedView,
8394            @Visibility int visibility) {
8395        onVisibilityChanged(changedView, visibility);
8396    }
8397
8398    /**
8399     * Called when the visibility of the view or an ancestor of the view is changed.
8400     * @param changedView The view whose visibility changed. Could be 'this' or
8401     * an ancestor view.
8402     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8403     * {@link #INVISIBLE} or {@link #GONE}.
8404     */
8405    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8406        if (visibility == VISIBLE) {
8407            if (mAttachInfo != null) {
8408                initialAwakenScrollBars();
8409            } else {
8410                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8411            }
8412        }
8413    }
8414
8415    /**
8416     * Dispatch a hint about whether this view is displayed. For instance, when
8417     * a View moves out of the screen, it might receives a display hint indicating
8418     * the view is not displayed. Applications should not <em>rely</em> on this hint
8419     * as there is no guarantee that they will receive one.
8420     *
8421     * @param hint A hint about whether or not this view is displayed:
8422     * {@link #VISIBLE} or {@link #INVISIBLE}.
8423     */
8424    public void dispatchDisplayHint(@Visibility int hint) {
8425        onDisplayHint(hint);
8426    }
8427
8428    /**
8429     * Gives this view a hint about whether is displayed or not. For instance, when
8430     * a View moves out of the screen, it might receives a display hint indicating
8431     * the view is not displayed. Applications should not <em>rely</em> on this hint
8432     * as there is no guarantee that they will receive one.
8433     *
8434     * @param hint A hint about whether or not this view is displayed:
8435     * {@link #VISIBLE} or {@link #INVISIBLE}.
8436     */
8437    protected void onDisplayHint(@Visibility int hint) {
8438    }
8439
8440    /**
8441     * Dispatch a window visibility change down the view hierarchy.
8442     * ViewGroups should override to route to their children.
8443     *
8444     * @param visibility The new visibility of the window.
8445     *
8446     * @see #onWindowVisibilityChanged(int)
8447     */
8448    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8449        onWindowVisibilityChanged(visibility);
8450    }
8451
8452    /**
8453     * Called when the window containing has change its visibility
8454     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8455     * that this tells you whether or not your window is being made visible
8456     * to the window manager; this does <em>not</em> tell you whether or not
8457     * your window is obscured by other windows on the screen, even if it
8458     * is itself visible.
8459     *
8460     * @param visibility The new visibility of the window.
8461     */
8462    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8463        if (visibility == VISIBLE) {
8464            initialAwakenScrollBars();
8465        }
8466    }
8467
8468    /**
8469     * Returns the current visibility of the window this view is attached to
8470     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8471     *
8472     * @return Returns the current visibility of the view's window.
8473     */
8474    @Visibility
8475    public int getWindowVisibility() {
8476        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8477    }
8478
8479    /**
8480     * Retrieve the overall visible display size in which the window this view is
8481     * attached to has been positioned in.  This takes into account screen
8482     * decorations above the window, for both cases where the window itself
8483     * is being position inside of them or the window is being placed under
8484     * then and covered insets are used for the window to position its content
8485     * inside.  In effect, this tells you the available area where content can
8486     * be placed and remain visible to users.
8487     *
8488     * <p>This function requires an IPC back to the window manager to retrieve
8489     * the requested information, so should not be used in performance critical
8490     * code like drawing.
8491     *
8492     * @param outRect Filled in with the visible display frame.  If the view
8493     * is not attached to a window, this is simply the raw display size.
8494     */
8495    public void getWindowVisibleDisplayFrame(Rect outRect) {
8496        if (mAttachInfo != null) {
8497            try {
8498                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8499            } catch (RemoteException e) {
8500                return;
8501            }
8502            // XXX This is really broken, and probably all needs to be done
8503            // in the window manager, and we need to know more about whether
8504            // we want the area behind or in front of the IME.
8505            final Rect insets = mAttachInfo.mVisibleInsets;
8506            outRect.left += insets.left;
8507            outRect.top += insets.top;
8508            outRect.right -= insets.right;
8509            outRect.bottom -= insets.bottom;
8510            return;
8511        }
8512        // The view is not attached to a display so we don't have a context.
8513        // Make a best guess about the display size.
8514        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8515        d.getRectSize(outRect);
8516    }
8517
8518    /**
8519     * Dispatch a notification about a resource configuration change down
8520     * the view hierarchy.
8521     * ViewGroups should override to route to their children.
8522     *
8523     * @param newConfig The new resource configuration.
8524     *
8525     * @see #onConfigurationChanged(android.content.res.Configuration)
8526     */
8527    public void dispatchConfigurationChanged(Configuration newConfig) {
8528        onConfigurationChanged(newConfig);
8529    }
8530
8531    /**
8532     * Called when the current configuration of the resources being used
8533     * by the application have changed.  You can use this to decide when
8534     * to reload resources that can changed based on orientation and other
8535     * configuration characterstics.  You only need to use this if you are
8536     * not relying on the normal {@link android.app.Activity} mechanism of
8537     * recreating the activity instance upon a configuration change.
8538     *
8539     * @param newConfig The new resource configuration.
8540     */
8541    protected void onConfigurationChanged(Configuration newConfig) {
8542    }
8543
8544    /**
8545     * Private function to aggregate all per-view attributes in to the view
8546     * root.
8547     */
8548    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8549        performCollectViewAttributes(attachInfo, visibility);
8550    }
8551
8552    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8553        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8554            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8555                attachInfo.mKeepScreenOn = true;
8556            }
8557            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8558            ListenerInfo li = mListenerInfo;
8559            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8560                attachInfo.mHasSystemUiListeners = true;
8561            }
8562        }
8563    }
8564
8565    void needGlobalAttributesUpdate(boolean force) {
8566        final AttachInfo ai = mAttachInfo;
8567        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8568            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8569                    || ai.mHasSystemUiListeners) {
8570                ai.mRecomputeGlobalAttributes = true;
8571            }
8572        }
8573    }
8574
8575    /**
8576     * Returns whether the device is currently in touch mode.  Touch mode is entered
8577     * once the user begins interacting with the device by touch, and affects various
8578     * things like whether focus is always visible to the user.
8579     *
8580     * @return Whether the device is in touch mode.
8581     */
8582    @ViewDebug.ExportedProperty
8583    public boolean isInTouchMode() {
8584        if (mAttachInfo != null) {
8585            return mAttachInfo.mInTouchMode;
8586        } else {
8587            return ViewRootImpl.isInTouchMode();
8588        }
8589    }
8590
8591    /**
8592     * Returns the context the view is running in, through which it can
8593     * access the current theme, resources, etc.
8594     *
8595     * @return The view's Context.
8596     */
8597    @ViewDebug.CapturedViewProperty
8598    public final Context getContext() {
8599        return mContext;
8600    }
8601
8602    /**
8603     * Handle a key event before it is processed by any input method
8604     * associated with the view hierarchy.  This can be used to intercept
8605     * key events in special situations before the IME consumes them; a
8606     * typical example would be handling the BACK key to update the application's
8607     * UI instead of allowing the IME to see it and close itself.
8608     *
8609     * @param keyCode The value in event.getKeyCode().
8610     * @param event Description of the key event.
8611     * @return If you handled the event, return true. If you want to allow the
8612     *         event to be handled by the next receiver, return false.
8613     */
8614    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8615        return false;
8616    }
8617
8618    /**
8619     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8620     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8621     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8622     * is released, if the view is enabled and clickable.
8623     *
8624     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8625     * although some may elect to do so in some situations. Do not rely on this to
8626     * catch software key presses.
8627     *
8628     * @param keyCode A key code that represents the button pressed, from
8629     *                {@link android.view.KeyEvent}.
8630     * @param event   The KeyEvent object that defines the button action.
8631     */
8632    public boolean onKeyDown(int keyCode, KeyEvent event) {
8633        boolean result = false;
8634
8635        if (KeyEvent.isConfirmKey(keyCode)) {
8636            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8637                return true;
8638            }
8639            // Long clickable items don't necessarily have to be clickable
8640            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8641                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8642                    (event.getRepeatCount() == 0)) {
8643                setPressed(true);
8644                checkForLongClick(0);
8645                return true;
8646            }
8647        }
8648        return result;
8649    }
8650
8651    /**
8652     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8653     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8654     * the event).
8655     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8656     * although some may elect to do so in some situations. Do not rely on this to
8657     * catch software key presses.
8658     */
8659    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8660        return false;
8661    }
8662
8663    /**
8664     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8665     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8666     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8667     * {@link KeyEvent#KEYCODE_ENTER} is released.
8668     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8669     * although some may elect to do so in some situations. Do not rely on this to
8670     * catch software key presses.
8671     *
8672     * @param keyCode A key code that represents the button pressed, from
8673     *                {@link android.view.KeyEvent}.
8674     * @param event   The KeyEvent object that defines the button action.
8675     */
8676    public boolean onKeyUp(int keyCode, KeyEvent event) {
8677        if (KeyEvent.isConfirmKey(keyCode)) {
8678            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8679                return true;
8680            }
8681            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8682                setPressed(false);
8683
8684                if (!mHasPerformedLongPress) {
8685                    // This is a tap, so remove the longpress check
8686                    removeLongPressCallback();
8687                    return performClick();
8688                }
8689            }
8690        }
8691        return false;
8692    }
8693
8694    /**
8695     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8696     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8697     * the event).
8698     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8699     * although some may elect to do so in some situations. Do not rely on this to
8700     * catch software key presses.
8701     *
8702     * @param keyCode     A key code that represents the button pressed, from
8703     *                    {@link android.view.KeyEvent}.
8704     * @param repeatCount The number of times the action was made.
8705     * @param event       The KeyEvent object that defines the button action.
8706     */
8707    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8708        return false;
8709    }
8710
8711    /**
8712     * Called on the focused view when a key shortcut event is not handled.
8713     * Override this method to implement local key shortcuts for the View.
8714     * Key shortcuts can also be implemented by setting the
8715     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8716     *
8717     * @param keyCode The value in event.getKeyCode().
8718     * @param event Description of the key event.
8719     * @return If you handled the event, return true. If you want to allow the
8720     *         event to be handled by the next receiver, return false.
8721     */
8722    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8723        return false;
8724    }
8725
8726    /**
8727     * Check whether the called view is a text editor, in which case it
8728     * would make sense to automatically display a soft input window for
8729     * it.  Subclasses should override this if they implement
8730     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8731     * a call on that method would return a non-null InputConnection, and
8732     * they are really a first-class editor that the user would normally
8733     * start typing on when the go into a window containing your view.
8734     *
8735     * <p>The default implementation always returns false.  This does
8736     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8737     * will not be called or the user can not otherwise perform edits on your
8738     * view; it is just a hint to the system that this is not the primary
8739     * purpose of this view.
8740     *
8741     * @return Returns true if this view is a text editor, else false.
8742     */
8743    public boolean onCheckIsTextEditor() {
8744        return false;
8745    }
8746
8747    /**
8748     * Create a new InputConnection for an InputMethod to interact
8749     * with the view.  The default implementation returns null, since it doesn't
8750     * support input methods.  You can override this to implement such support.
8751     * This is only needed for views that take focus and text input.
8752     *
8753     * <p>When implementing this, you probably also want to implement
8754     * {@link #onCheckIsTextEditor()} to indicate you will return a
8755     * non-null InputConnection.</p>
8756     *
8757     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8758     * object correctly and in its entirety, so that the connected IME can rely
8759     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8760     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8761     * must be filled in with the correct cursor position for IMEs to work correctly
8762     * with your application.</p>
8763     *
8764     * @param outAttrs Fill in with attribute information about the connection.
8765     */
8766    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8767        return null;
8768    }
8769
8770    /**
8771     * Called by the {@link android.view.inputmethod.InputMethodManager}
8772     * when a view who is not the current
8773     * input connection target is trying to make a call on the manager.  The
8774     * default implementation returns false; you can override this to return
8775     * true for certain views if you are performing InputConnection proxying
8776     * to them.
8777     * @param view The View that is making the InputMethodManager call.
8778     * @return Return true to allow the call, false to reject.
8779     */
8780    public boolean checkInputConnectionProxy(View view) {
8781        return false;
8782    }
8783
8784    /**
8785     * Show the context menu for this view. It is not safe to hold on to the
8786     * menu after returning from this method.
8787     *
8788     * You should normally not overload this method. Overload
8789     * {@link #onCreateContextMenu(ContextMenu)} or define an
8790     * {@link OnCreateContextMenuListener} to add items to the context menu.
8791     *
8792     * @param menu The context menu to populate
8793     */
8794    public void createContextMenu(ContextMenu menu) {
8795        ContextMenuInfo menuInfo = getContextMenuInfo();
8796
8797        // Sets the current menu info so all items added to menu will have
8798        // my extra info set.
8799        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8800
8801        onCreateContextMenu(menu);
8802        ListenerInfo li = mListenerInfo;
8803        if (li != null && li.mOnCreateContextMenuListener != null) {
8804            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8805        }
8806
8807        // Clear the extra information so subsequent items that aren't mine don't
8808        // have my extra info.
8809        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8810
8811        if (mParent != null) {
8812            mParent.createContextMenu(menu);
8813        }
8814    }
8815
8816    /**
8817     * Views should implement this if they have extra information to associate
8818     * with the context menu. The return result is supplied as a parameter to
8819     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8820     * callback.
8821     *
8822     * @return Extra information about the item for which the context menu
8823     *         should be shown. This information will vary across different
8824     *         subclasses of View.
8825     */
8826    protected ContextMenuInfo getContextMenuInfo() {
8827        return null;
8828    }
8829
8830    /**
8831     * Views should implement this if the view itself is going to add items to
8832     * the context menu.
8833     *
8834     * @param menu the context menu to populate
8835     */
8836    protected void onCreateContextMenu(ContextMenu menu) {
8837    }
8838
8839    /**
8840     * Implement this method to handle trackball motion events.  The
8841     * <em>relative</em> movement of the trackball since the last event
8842     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8843     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8844     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8845     * they will often be fractional values, representing the more fine-grained
8846     * movement information available from a trackball).
8847     *
8848     * @param event The motion event.
8849     * @return True if the event was handled, false otherwise.
8850     */
8851    public boolean onTrackballEvent(MotionEvent event) {
8852        return false;
8853    }
8854
8855    /**
8856     * Implement this method to handle generic motion events.
8857     * <p>
8858     * Generic motion events describe joystick movements, mouse hovers, track pad
8859     * touches, scroll wheel movements and other input events.  The
8860     * {@link MotionEvent#getSource() source} of the motion event specifies
8861     * the class of input that was received.  Implementations of this method
8862     * must examine the bits in the source before processing the event.
8863     * The following code example shows how this is done.
8864     * </p><p>
8865     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8866     * are delivered to the view under the pointer.  All other generic motion events are
8867     * delivered to the focused view.
8868     * </p>
8869     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8870     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8871     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8872     *             // process the joystick movement...
8873     *             return true;
8874     *         }
8875     *     }
8876     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8877     *         switch (event.getAction()) {
8878     *             case MotionEvent.ACTION_HOVER_MOVE:
8879     *                 // process the mouse hover movement...
8880     *                 return true;
8881     *             case MotionEvent.ACTION_SCROLL:
8882     *                 // process the scroll wheel movement...
8883     *                 return true;
8884     *         }
8885     *     }
8886     *     return super.onGenericMotionEvent(event);
8887     * }</pre>
8888     *
8889     * @param event The generic motion event being processed.
8890     * @return True if the event was handled, false otherwise.
8891     */
8892    public boolean onGenericMotionEvent(MotionEvent event) {
8893        return false;
8894    }
8895
8896    /**
8897     * Implement this method to handle hover events.
8898     * <p>
8899     * This method is called whenever a pointer is hovering into, over, or out of the
8900     * bounds of a view and the view is not currently being touched.
8901     * Hover events are represented as pointer events with action
8902     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8903     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8904     * </p>
8905     * <ul>
8906     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8907     * when the pointer enters the bounds of the view.</li>
8908     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8909     * when the pointer has already entered the bounds of the view and has moved.</li>
8910     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8911     * when the pointer has exited the bounds of the view or when the pointer is
8912     * about to go down due to a button click, tap, or similar user action that
8913     * causes the view to be touched.</li>
8914     * </ul>
8915     * <p>
8916     * The view should implement this method to return true to indicate that it is
8917     * handling the hover event, such as by changing its drawable state.
8918     * </p><p>
8919     * The default implementation calls {@link #setHovered} to update the hovered state
8920     * of the view when a hover enter or hover exit event is received, if the view
8921     * is enabled and is clickable.  The default implementation also sends hover
8922     * accessibility events.
8923     * </p>
8924     *
8925     * @param event The motion event that describes the hover.
8926     * @return True if the view handled the hover event.
8927     *
8928     * @see #isHovered
8929     * @see #setHovered
8930     * @see #onHoverChanged
8931     */
8932    public boolean onHoverEvent(MotionEvent event) {
8933        // The root view may receive hover (or touch) events that are outside the bounds of
8934        // the window.  This code ensures that we only send accessibility events for
8935        // hovers that are actually within the bounds of the root view.
8936        final int action = event.getActionMasked();
8937        if (!mSendingHoverAccessibilityEvents) {
8938            if ((action == MotionEvent.ACTION_HOVER_ENTER
8939                    || action == MotionEvent.ACTION_HOVER_MOVE)
8940                    && !hasHoveredChild()
8941                    && pointInView(event.getX(), event.getY())) {
8942                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8943                mSendingHoverAccessibilityEvents = true;
8944            }
8945        } else {
8946            if (action == MotionEvent.ACTION_HOVER_EXIT
8947                    || (action == MotionEvent.ACTION_MOVE
8948                            && !pointInView(event.getX(), event.getY()))) {
8949                mSendingHoverAccessibilityEvents = false;
8950                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8951            }
8952        }
8953
8954        if (isHoverable()) {
8955            switch (action) {
8956                case MotionEvent.ACTION_HOVER_ENTER:
8957                    setHovered(true);
8958                    break;
8959                case MotionEvent.ACTION_HOVER_EXIT:
8960                    setHovered(false);
8961                    break;
8962            }
8963
8964            // Dispatch the event to onGenericMotionEvent before returning true.
8965            // This is to provide compatibility with existing applications that
8966            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8967            // break because of the new default handling for hoverable views
8968            // in onHoverEvent.
8969            // Note that onGenericMotionEvent will be called by default when
8970            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8971            dispatchGenericMotionEventInternal(event);
8972            // The event was already handled by calling setHovered(), so always
8973            // return true.
8974            return true;
8975        }
8976
8977        return false;
8978    }
8979
8980    /**
8981     * Returns true if the view should handle {@link #onHoverEvent}
8982     * by calling {@link #setHovered} to change its hovered state.
8983     *
8984     * @return True if the view is hoverable.
8985     */
8986    private boolean isHoverable() {
8987        final int viewFlags = mViewFlags;
8988        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8989            return false;
8990        }
8991
8992        return (viewFlags & CLICKABLE) == CLICKABLE
8993                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8994    }
8995
8996    /**
8997     * Returns true if the view is currently hovered.
8998     *
8999     * @return True if the view is currently hovered.
9000     *
9001     * @see #setHovered
9002     * @see #onHoverChanged
9003     */
9004    @ViewDebug.ExportedProperty
9005    public boolean isHovered() {
9006        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9007    }
9008
9009    /**
9010     * Sets whether the view is currently hovered.
9011     * <p>
9012     * Calling this method also changes the drawable state of the view.  This
9013     * enables the view to react to hover by using different drawable resources
9014     * to change its appearance.
9015     * </p><p>
9016     * The {@link #onHoverChanged} method is called when the hovered state changes.
9017     * </p>
9018     *
9019     * @param hovered True if the view is hovered.
9020     *
9021     * @see #isHovered
9022     * @see #onHoverChanged
9023     */
9024    public void setHovered(boolean hovered) {
9025        if (hovered) {
9026            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9027                mPrivateFlags |= PFLAG_HOVERED;
9028                refreshDrawableState();
9029                onHoverChanged(true);
9030            }
9031        } else {
9032            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9033                mPrivateFlags &= ~PFLAG_HOVERED;
9034                refreshDrawableState();
9035                onHoverChanged(false);
9036            }
9037        }
9038    }
9039
9040    /**
9041     * Implement this method to handle hover state changes.
9042     * <p>
9043     * This method is called whenever the hover state changes as a result of a
9044     * call to {@link #setHovered}.
9045     * </p>
9046     *
9047     * @param hovered The current hover state, as returned by {@link #isHovered}.
9048     *
9049     * @see #isHovered
9050     * @see #setHovered
9051     */
9052    public void onHoverChanged(boolean hovered) {
9053    }
9054
9055    /**
9056     * Implement this method to handle touch screen motion events.
9057     * <p>
9058     * If this method is used to detect click actions, it is recommended that
9059     * the actions be performed by implementing and calling
9060     * {@link #performClick()}. This will ensure consistent system behavior,
9061     * including:
9062     * <ul>
9063     * <li>obeying click sound preferences
9064     * <li>dispatching OnClickListener calls
9065     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9066     * accessibility features are enabled
9067     * </ul>
9068     *
9069     * @param event The motion event.
9070     * @return True if the event was handled, false otherwise.
9071     */
9072    public boolean onTouchEvent(MotionEvent event) {
9073        final float x = event.getX();
9074        final float y = event.getY();
9075        final int viewFlags = mViewFlags;
9076
9077        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9078            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9079                setPressed(false);
9080            }
9081            // A disabled view that is clickable still consumes the touch
9082            // events, it just doesn't respond to them.
9083            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9084                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9085        }
9086
9087        if (mTouchDelegate != null) {
9088            if (mTouchDelegate.onTouchEvent(event)) {
9089                return true;
9090            }
9091        }
9092
9093        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9094                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9095            switch (event.getAction()) {
9096                case MotionEvent.ACTION_UP:
9097                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9098                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9099                        // take focus if we don't have it already and we should in
9100                        // touch mode.
9101                        boolean focusTaken = false;
9102                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9103                            focusTaken = requestFocus();
9104                        }
9105
9106                        if (prepressed) {
9107                            // The button is being released before we actually
9108                            // showed it as pressed.  Make it show the pressed
9109                            // state now (before scheduling the click) to ensure
9110                            // the user sees it.
9111                            setPressed(true, x, y);
9112                       }
9113
9114                        if (!mHasPerformedLongPress) {
9115                            // This is a tap, so remove the longpress check
9116                            removeLongPressCallback();
9117
9118                            // Only perform take click actions if we were in the pressed state
9119                            if (!focusTaken) {
9120                                // Use a Runnable and post this rather than calling
9121                                // performClick directly. This lets other visual state
9122                                // of the view update before click actions start.
9123                                if (mPerformClick == null) {
9124                                    mPerformClick = new PerformClick();
9125                                }
9126                                if (!post(mPerformClick)) {
9127                                    performClick();
9128                                }
9129                            }
9130                        }
9131
9132                        if (mUnsetPressedState == null) {
9133                            mUnsetPressedState = new UnsetPressedState();
9134                        }
9135
9136                        if (prepressed) {
9137                            postDelayed(mUnsetPressedState,
9138                                    ViewConfiguration.getPressedStateDuration());
9139                        } else if (!post(mUnsetPressedState)) {
9140                            // If the post failed, unpress right now
9141                            mUnsetPressedState.run();
9142                        }
9143
9144                        removeTapCallback();
9145                    }
9146                    break;
9147
9148                case MotionEvent.ACTION_DOWN:
9149                    mHasPerformedLongPress = false;
9150
9151                    if (performButtonActionOnTouchDown(event)) {
9152                        break;
9153                    }
9154
9155                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9156                    boolean isInScrollingContainer = isInScrollingContainer();
9157
9158                    // For views inside a scrolling container, delay the pressed feedback for
9159                    // a short period in case this is a scroll.
9160                    if (isInScrollingContainer) {
9161                        mPrivateFlags |= PFLAG_PREPRESSED;
9162                        if (mPendingCheckForTap == null) {
9163                            mPendingCheckForTap = new CheckForTap();
9164                        }
9165                        mPendingCheckForTap.x = event.getX();
9166                        mPendingCheckForTap.y = event.getY();
9167                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9168                    } else {
9169                        // Not inside a scrolling container, so show the feedback right away
9170                        setPressed(true, x, y);
9171                        checkForLongClick(0);
9172                    }
9173                    break;
9174
9175                case MotionEvent.ACTION_CANCEL:
9176                    setPressed(false);
9177                    removeTapCallback();
9178                    removeLongPressCallback();
9179                    break;
9180
9181                case MotionEvent.ACTION_MOVE:
9182                    drawableHotspotChanged(x, y);
9183
9184                    // Be lenient about moving outside of buttons
9185                    if (!pointInView(x, y, mTouchSlop)) {
9186                        // Outside button
9187                        removeTapCallback();
9188                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9189                            // Remove any future long press/tap checks
9190                            removeLongPressCallback();
9191
9192                            setPressed(false);
9193                        }
9194                    }
9195                    break;
9196            }
9197
9198            return true;
9199        }
9200
9201        return false;
9202    }
9203
9204    /**
9205     * @hide
9206     */
9207    public boolean isInScrollingContainer() {
9208        ViewParent p = getParent();
9209        while (p != null && p instanceof ViewGroup) {
9210            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9211                return true;
9212            }
9213            p = p.getParent();
9214        }
9215        return false;
9216    }
9217
9218    /**
9219     * Remove the longpress detection timer.
9220     */
9221    private void removeLongPressCallback() {
9222        if (mPendingCheckForLongPress != null) {
9223          removeCallbacks(mPendingCheckForLongPress);
9224        }
9225    }
9226
9227    /**
9228     * Remove the pending click action
9229     */
9230    private void removePerformClickCallback() {
9231        if (mPerformClick != null) {
9232            removeCallbacks(mPerformClick);
9233        }
9234    }
9235
9236    /**
9237     * Remove the prepress detection timer.
9238     */
9239    private void removeUnsetPressCallback() {
9240        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9241            setPressed(false);
9242            removeCallbacks(mUnsetPressedState);
9243        }
9244    }
9245
9246    /**
9247     * Remove the tap detection timer.
9248     */
9249    private void removeTapCallback() {
9250        if (mPendingCheckForTap != null) {
9251            mPrivateFlags &= ~PFLAG_PREPRESSED;
9252            removeCallbacks(mPendingCheckForTap);
9253        }
9254    }
9255
9256    /**
9257     * Cancels a pending long press.  Your subclass can use this if you
9258     * want the context menu to come up if the user presses and holds
9259     * at the same place, but you don't want it to come up if they press
9260     * and then move around enough to cause scrolling.
9261     */
9262    public void cancelLongPress() {
9263        removeLongPressCallback();
9264
9265        /*
9266         * The prepressed state handled by the tap callback is a display
9267         * construct, but the tap callback will post a long press callback
9268         * less its own timeout. Remove it here.
9269         */
9270        removeTapCallback();
9271    }
9272
9273    /**
9274     * Remove the pending callback for sending a
9275     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9276     */
9277    private void removeSendViewScrolledAccessibilityEventCallback() {
9278        if (mSendViewScrolledAccessibilityEvent != null) {
9279            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9280            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9281        }
9282    }
9283
9284    /**
9285     * Sets the TouchDelegate for this View.
9286     */
9287    public void setTouchDelegate(TouchDelegate delegate) {
9288        mTouchDelegate = delegate;
9289    }
9290
9291    /**
9292     * Gets the TouchDelegate for this View.
9293     */
9294    public TouchDelegate getTouchDelegate() {
9295        return mTouchDelegate;
9296    }
9297
9298    /**
9299     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9300     *
9301     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9302     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9303     * available. This method should only be called for touch events.
9304     *
9305     * <p class="note">This api is not intended for most applications. Buffered dispatch
9306     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9307     * streams will not improve your input latency. Side effects include: increased latency,
9308     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9309     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9310     * you.</p>
9311     */
9312    public final void requestUnbufferedDispatch(MotionEvent event) {
9313        final int action = event.getAction();
9314        if (mAttachInfo == null
9315                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9316                || !event.isTouchEvent()) {
9317            return;
9318        }
9319        mAttachInfo.mUnbufferedDispatchRequested = true;
9320    }
9321
9322    /**
9323     * Set flags controlling behavior of this view.
9324     *
9325     * @param flags Constant indicating the value which should be set
9326     * @param mask Constant indicating the bit range that should be changed
9327     */
9328    void setFlags(int flags, int mask) {
9329        final boolean accessibilityEnabled =
9330                AccessibilityManager.getInstance(mContext).isEnabled();
9331        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9332
9333        int old = mViewFlags;
9334        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9335
9336        int changed = mViewFlags ^ old;
9337        if (changed == 0) {
9338            return;
9339        }
9340        int privateFlags = mPrivateFlags;
9341
9342        /* Check if the FOCUSABLE bit has changed */
9343        if (((changed & FOCUSABLE_MASK) != 0) &&
9344                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9345            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9346                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9347                /* Give up focus if we are no longer focusable */
9348                clearFocus();
9349            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9350                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9351                /*
9352                 * Tell the view system that we are now available to take focus
9353                 * if no one else already has it.
9354                 */
9355                if (mParent != null) mParent.focusableViewAvailable(this);
9356            }
9357        }
9358
9359        final int newVisibility = flags & VISIBILITY_MASK;
9360        if (newVisibility == VISIBLE) {
9361            if ((changed & VISIBILITY_MASK) != 0) {
9362                /*
9363                 * If this view is becoming visible, invalidate it in case it changed while
9364                 * it was not visible. Marking it drawn ensures that the invalidation will
9365                 * go through.
9366                 */
9367                mPrivateFlags |= PFLAG_DRAWN;
9368                invalidate(true);
9369
9370                needGlobalAttributesUpdate(true);
9371
9372                // a view becoming visible is worth notifying the parent
9373                // about in case nothing has focus.  even if this specific view
9374                // isn't focusable, it may contain something that is, so let
9375                // the root view try to give this focus if nothing else does.
9376                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9377                    mParent.focusableViewAvailable(this);
9378                }
9379            }
9380        }
9381
9382        /* Check if the GONE bit has changed */
9383        if ((changed & GONE) != 0) {
9384            needGlobalAttributesUpdate(false);
9385            requestLayout();
9386
9387            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9388                if (hasFocus()) clearFocus();
9389                clearAccessibilityFocus();
9390                destroyDrawingCache();
9391                if (mParent instanceof View) {
9392                    // GONE views noop invalidation, so invalidate the parent
9393                    ((View) mParent).invalidate(true);
9394                }
9395                // Mark the view drawn to ensure that it gets invalidated properly the next
9396                // time it is visible and gets invalidated
9397                mPrivateFlags |= PFLAG_DRAWN;
9398            }
9399            if (mAttachInfo != null) {
9400                mAttachInfo.mViewVisibilityChanged = true;
9401            }
9402        }
9403
9404        /* Check if the VISIBLE bit has changed */
9405        if ((changed & INVISIBLE) != 0) {
9406            needGlobalAttributesUpdate(false);
9407            /*
9408             * If this view is becoming invisible, set the DRAWN flag so that
9409             * the next invalidate() will not be skipped.
9410             */
9411            mPrivateFlags |= PFLAG_DRAWN;
9412
9413            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9414                // root view becoming invisible shouldn't clear focus and accessibility focus
9415                if (getRootView() != this) {
9416                    if (hasFocus()) clearFocus();
9417                    clearAccessibilityFocus();
9418                }
9419            }
9420            if (mAttachInfo != null) {
9421                mAttachInfo.mViewVisibilityChanged = true;
9422            }
9423        }
9424
9425        if ((changed & VISIBILITY_MASK) != 0) {
9426            // If the view is invisible, cleanup its display list to free up resources
9427            if (newVisibility != VISIBLE && mAttachInfo != null) {
9428                cleanupDraw();
9429            }
9430
9431            if (mParent instanceof ViewGroup) {
9432                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9433                        (changed & VISIBILITY_MASK), newVisibility);
9434                ((View) mParent).invalidate(true);
9435            } else if (mParent != null) {
9436                mParent.invalidateChild(this, null);
9437            }
9438            dispatchVisibilityChanged(this, newVisibility);
9439
9440            notifySubtreeAccessibilityStateChangedIfNeeded();
9441        }
9442
9443        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9444            destroyDrawingCache();
9445        }
9446
9447        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9448            destroyDrawingCache();
9449            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9450            invalidateParentCaches();
9451        }
9452
9453        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9454            destroyDrawingCache();
9455            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9456        }
9457
9458        if ((changed & DRAW_MASK) != 0) {
9459            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9460                if (mBackground != null) {
9461                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9462                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9463                } else {
9464                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9465                }
9466            } else {
9467                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9468            }
9469            requestLayout();
9470            invalidate(true);
9471        }
9472
9473        if ((changed & KEEP_SCREEN_ON) != 0) {
9474            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9475                mParent.recomputeViewAttributes(this);
9476            }
9477        }
9478
9479        if (accessibilityEnabled) {
9480            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9481                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9482                if (oldIncludeForAccessibility != includeForAccessibility()) {
9483                    notifySubtreeAccessibilityStateChangedIfNeeded();
9484                } else {
9485                    notifyViewAccessibilityStateChangedIfNeeded(
9486                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9487                }
9488            } else if ((changed & ENABLED_MASK) != 0) {
9489                notifyViewAccessibilityStateChangedIfNeeded(
9490                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9491            }
9492        }
9493    }
9494
9495    /**
9496     * Change the view's z order in the tree, so it's on top of other sibling
9497     * views. This ordering change may affect layout, if the parent container
9498     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9499     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9500     * method should be followed by calls to {@link #requestLayout()} and
9501     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9502     * with the new child ordering.
9503     *
9504     * @see ViewGroup#bringChildToFront(View)
9505     */
9506    public void bringToFront() {
9507        if (mParent != null) {
9508            mParent.bringChildToFront(this);
9509        }
9510    }
9511
9512    /**
9513     * This is called in response to an internal scroll in this view (i.e., the
9514     * view scrolled its own contents). This is typically as a result of
9515     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9516     * called.
9517     *
9518     * @param l Current horizontal scroll origin.
9519     * @param t Current vertical scroll origin.
9520     * @param oldl Previous horizontal scroll origin.
9521     * @param oldt Previous vertical scroll origin.
9522     */
9523    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9524        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9525            postSendViewScrolledAccessibilityEventCallback();
9526        }
9527
9528        mBackgroundSizeChanged = true;
9529
9530        final AttachInfo ai = mAttachInfo;
9531        if (ai != null) {
9532            ai.mViewScrollChanged = true;
9533        }
9534    }
9535
9536    /**
9537     * Interface definition for a callback to be invoked when the layout bounds of a view
9538     * changes due to layout processing.
9539     */
9540    public interface OnLayoutChangeListener {
9541        /**
9542         * Called when the layout bounds of a view changes due to layout processing.
9543         *
9544         * @param v The view whose bounds have changed.
9545         * @param left The new value of the view's left property.
9546         * @param top The new value of the view's top property.
9547         * @param right The new value of the view's right property.
9548         * @param bottom The new value of the view's bottom property.
9549         * @param oldLeft The previous value of the view's left property.
9550         * @param oldTop The previous value of the view's top property.
9551         * @param oldRight The previous value of the view's right property.
9552         * @param oldBottom The previous value of the view's bottom property.
9553         */
9554        void onLayoutChange(View v, int left, int top, int right, int bottom,
9555            int oldLeft, int oldTop, int oldRight, int oldBottom);
9556    }
9557
9558    /**
9559     * This is called during layout when the size of this view has changed. If
9560     * you were just added to the view hierarchy, you're called with the old
9561     * values of 0.
9562     *
9563     * @param w Current width of this view.
9564     * @param h Current height of this view.
9565     * @param oldw Old width of this view.
9566     * @param oldh Old height of this view.
9567     */
9568    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9569    }
9570
9571    /**
9572     * Called by draw to draw the child views. This may be overridden
9573     * by derived classes to gain control just before its children are drawn
9574     * (but after its own view has been drawn).
9575     * @param canvas the canvas on which to draw the view
9576     */
9577    protected void dispatchDraw(Canvas canvas) {
9578
9579    }
9580
9581    /**
9582     * Gets the parent of this view. Note that the parent is a
9583     * ViewParent and not necessarily a View.
9584     *
9585     * @return Parent of this view.
9586     */
9587    public final ViewParent getParent() {
9588        return mParent;
9589    }
9590
9591    /**
9592     * Set the horizontal scrolled position of your view. This will cause a call to
9593     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9594     * invalidated.
9595     * @param value the x position to scroll to
9596     */
9597    public void setScrollX(int value) {
9598        scrollTo(value, mScrollY);
9599    }
9600
9601    /**
9602     * Set the vertical scrolled position of your view. This will cause a call to
9603     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9604     * invalidated.
9605     * @param value the y position to scroll to
9606     */
9607    public void setScrollY(int value) {
9608        scrollTo(mScrollX, value);
9609    }
9610
9611    /**
9612     * Return the scrolled left position of this view. This is the left edge of
9613     * the displayed part of your view. You do not need to draw any pixels
9614     * farther left, since those are outside of the frame of your view on
9615     * screen.
9616     *
9617     * @return The left edge of the displayed part of your view, in pixels.
9618     */
9619    public final int getScrollX() {
9620        return mScrollX;
9621    }
9622
9623    /**
9624     * Return the scrolled top position of this view. This is the top edge of
9625     * the displayed part of your view. You do not need to draw any pixels above
9626     * it, since those are outside of the frame of your view on screen.
9627     *
9628     * @return The top edge of the displayed part of your view, in pixels.
9629     */
9630    public final int getScrollY() {
9631        return mScrollY;
9632    }
9633
9634    /**
9635     * Return the width of the your view.
9636     *
9637     * @return The width of your view, in pixels.
9638     */
9639    @ViewDebug.ExportedProperty(category = "layout")
9640    public final int getWidth() {
9641        return mRight - mLeft;
9642    }
9643
9644    /**
9645     * Return the height of your view.
9646     *
9647     * @return The height of your view, in pixels.
9648     */
9649    @ViewDebug.ExportedProperty(category = "layout")
9650    public final int getHeight() {
9651        return mBottom - mTop;
9652    }
9653
9654    /**
9655     * Return the visible drawing bounds of your view. Fills in the output
9656     * rectangle with the values from getScrollX(), getScrollY(),
9657     * getWidth(), and getHeight(). These bounds do not account for any
9658     * transformation properties currently set on the view, such as
9659     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9660     *
9661     * @param outRect The (scrolled) drawing bounds of the view.
9662     */
9663    public void getDrawingRect(Rect outRect) {
9664        outRect.left = mScrollX;
9665        outRect.top = mScrollY;
9666        outRect.right = mScrollX + (mRight - mLeft);
9667        outRect.bottom = mScrollY + (mBottom - mTop);
9668    }
9669
9670    /**
9671     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9672     * raw width component (that is the result is masked by
9673     * {@link #MEASURED_SIZE_MASK}).
9674     *
9675     * @return The raw measured width of this view.
9676     */
9677    public final int getMeasuredWidth() {
9678        return mMeasuredWidth & MEASURED_SIZE_MASK;
9679    }
9680
9681    /**
9682     * Return the full width measurement information for this view as computed
9683     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9684     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9685     * This should be used during measurement and layout calculations only. Use
9686     * {@link #getWidth()} to see how wide a view is after layout.
9687     *
9688     * @return The measured width of this view as a bit mask.
9689     */
9690    public final int getMeasuredWidthAndState() {
9691        return mMeasuredWidth;
9692    }
9693
9694    /**
9695     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9696     * raw width component (that is the result is masked by
9697     * {@link #MEASURED_SIZE_MASK}).
9698     *
9699     * @return The raw measured height of this view.
9700     */
9701    public final int getMeasuredHeight() {
9702        return mMeasuredHeight & MEASURED_SIZE_MASK;
9703    }
9704
9705    /**
9706     * Return the full height measurement information for this view as computed
9707     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9708     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9709     * This should be used during measurement and layout calculations only. Use
9710     * {@link #getHeight()} to see how wide a view is after layout.
9711     *
9712     * @return The measured width of this view as a bit mask.
9713     */
9714    public final int getMeasuredHeightAndState() {
9715        return mMeasuredHeight;
9716    }
9717
9718    /**
9719     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9720     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9721     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9722     * and the height component is at the shifted bits
9723     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9724     */
9725    public final int getMeasuredState() {
9726        return (mMeasuredWidth&MEASURED_STATE_MASK)
9727                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9728                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9729    }
9730
9731    /**
9732     * The transform matrix of this view, which is calculated based on the current
9733     * rotation, scale, and pivot properties.
9734     *
9735     * @see #getRotation()
9736     * @see #getScaleX()
9737     * @see #getScaleY()
9738     * @see #getPivotX()
9739     * @see #getPivotY()
9740     * @return The current transform matrix for the view
9741     */
9742    public Matrix getMatrix() {
9743        ensureTransformationInfo();
9744        final Matrix matrix = mTransformationInfo.mMatrix;
9745        mRenderNode.getMatrix(matrix);
9746        return matrix;
9747    }
9748
9749    /**
9750     * Returns true if the transform matrix is the identity matrix.
9751     * Recomputes the matrix if necessary.
9752     *
9753     * @return True if the transform matrix is the identity matrix, false otherwise.
9754     */
9755    final boolean hasIdentityMatrix() {
9756        return mRenderNode.hasIdentityMatrix();
9757    }
9758
9759    void ensureTransformationInfo() {
9760        if (mTransformationInfo == null) {
9761            mTransformationInfo = new TransformationInfo();
9762        }
9763    }
9764
9765   /**
9766     * Utility method to retrieve the inverse of the current mMatrix property.
9767     * We cache the matrix to avoid recalculating it when transform properties
9768     * have not changed.
9769     *
9770     * @return The inverse of the current matrix of this view.
9771     */
9772    final Matrix getInverseMatrix() {
9773        ensureTransformationInfo();
9774        if (mTransformationInfo.mInverseMatrix == null) {
9775            mTransformationInfo.mInverseMatrix = new Matrix();
9776        }
9777        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9778        mRenderNode.getInverseMatrix(matrix);
9779        return matrix;
9780    }
9781
9782    /**
9783     * Gets the distance along the Z axis from the camera to this view.
9784     *
9785     * @see #setCameraDistance(float)
9786     *
9787     * @return The distance along the Z axis.
9788     */
9789    public float getCameraDistance() {
9790        final float dpi = mResources.getDisplayMetrics().densityDpi;
9791        return -(mRenderNode.getCameraDistance() * dpi);
9792    }
9793
9794    /**
9795     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9796     * views are drawn) from the camera to this view. The camera's distance
9797     * affects 3D transformations, for instance rotations around the X and Y
9798     * axis. If the rotationX or rotationY properties are changed and this view is
9799     * large (more than half the size of the screen), it is recommended to always
9800     * use a camera distance that's greater than the height (X axis rotation) or
9801     * the width (Y axis rotation) of this view.</p>
9802     *
9803     * <p>The distance of the camera from the view plane can have an affect on the
9804     * perspective distortion of the view when it is rotated around the x or y axis.
9805     * For example, a large distance will result in a large viewing angle, and there
9806     * will not be much perspective distortion of the view as it rotates. A short
9807     * distance may cause much more perspective distortion upon rotation, and can
9808     * also result in some drawing artifacts if the rotated view ends up partially
9809     * behind the camera (which is why the recommendation is to use a distance at
9810     * least as far as the size of the view, if the view is to be rotated.)</p>
9811     *
9812     * <p>The distance is expressed in "depth pixels." The default distance depends
9813     * on the screen density. For instance, on a medium density display, the
9814     * default distance is 1280. On a high density display, the default distance
9815     * is 1920.</p>
9816     *
9817     * <p>If you want to specify a distance that leads to visually consistent
9818     * results across various densities, use the following formula:</p>
9819     * <pre>
9820     * float scale = context.getResources().getDisplayMetrics().density;
9821     * view.setCameraDistance(distance * scale);
9822     * </pre>
9823     *
9824     * <p>The density scale factor of a high density display is 1.5,
9825     * and 1920 = 1280 * 1.5.</p>
9826     *
9827     * @param distance The distance in "depth pixels", if negative the opposite
9828     *        value is used
9829     *
9830     * @see #setRotationX(float)
9831     * @see #setRotationY(float)
9832     */
9833    public void setCameraDistance(float distance) {
9834        final float dpi = mResources.getDisplayMetrics().densityDpi;
9835
9836        invalidateViewProperty(true, false);
9837        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9838        invalidateViewProperty(false, false);
9839
9840        invalidateParentIfNeededAndWasQuickRejected();
9841    }
9842
9843    /**
9844     * The degrees that the view is rotated around the pivot point.
9845     *
9846     * @see #setRotation(float)
9847     * @see #getPivotX()
9848     * @see #getPivotY()
9849     *
9850     * @return The degrees of rotation.
9851     */
9852    @ViewDebug.ExportedProperty(category = "drawing")
9853    public float getRotation() {
9854        return mRenderNode.getRotation();
9855    }
9856
9857    /**
9858     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9859     * result in clockwise rotation.
9860     *
9861     * @param rotation The degrees of rotation.
9862     *
9863     * @see #getRotation()
9864     * @see #getPivotX()
9865     * @see #getPivotY()
9866     * @see #setRotationX(float)
9867     * @see #setRotationY(float)
9868     *
9869     * @attr ref android.R.styleable#View_rotation
9870     */
9871    public void setRotation(float rotation) {
9872        if (rotation != getRotation()) {
9873            // Double-invalidation is necessary to capture view's old and new areas
9874            invalidateViewProperty(true, false);
9875            mRenderNode.setRotation(rotation);
9876            invalidateViewProperty(false, true);
9877
9878            invalidateParentIfNeededAndWasQuickRejected();
9879            notifySubtreeAccessibilityStateChangedIfNeeded();
9880        }
9881    }
9882
9883    /**
9884     * The degrees that the view is rotated around the vertical axis through the pivot point.
9885     *
9886     * @see #getPivotX()
9887     * @see #getPivotY()
9888     * @see #setRotationY(float)
9889     *
9890     * @return The degrees of Y rotation.
9891     */
9892    @ViewDebug.ExportedProperty(category = "drawing")
9893    public float getRotationY() {
9894        return mRenderNode.getRotationY();
9895    }
9896
9897    /**
9898     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9899     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9900     * down the y axis.
9901     *
9902     * When rotating large views, it is recommended to adjust the camera distance
9903     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9904     *
9905     * @param rotationY The degrees of Y rotation.
9906     *
9907     * @see #getRotationY()
9908     * @see #getPivotX()
9909     * @see #getPivotY()
9910     * @see #setRotation(float)
9911     * @see #setRotationX(float)
9912     * @see #setCameraDistance(float)
9913     *
9914     * @attr ref android.R.styleable#View_rotationY
9915     */
9916    public void setRotationY(float rotationY) {
9917        if (rotationY != getRotationY()) {
9918            invalidateViewProperty(true, false);
9919            mRenderNode.setRotationY(rotationY);
9920            invalidateViewProperty(false, true);
9921
9922            invalidateParentIfNeededAndWasQuickRejected();
9923            notifySubtreeAccessibilityStateChangedIfNeeded();
9924        }
9925    }
9926
9927    /**
9928     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9929     *
9930     * @see #getPivotX()
9931     * @see #getPivotY()
9932     * @see #setRotationX(float)
9933     *
9934     * @return The degrees of X rotation.
9935     */
9936    @ViewDebug.ExportedProperty(category = "drawing")
9937    public float getRotationX() {
9938        return mRenderNode.getRotationX();
9939    }
9940
9941    /**
9942     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9943     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9944     * x axis.
9945     *
9946     * When rotating large views, it is recommended to adjust the camera distance
9947     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9948     *
9949     * @param rotationX The degrees of X rotation.
9950     *
9951     * @see #getRotationX()
9952     * @see #getPivotX()
9953     * @see #getPivotY()
9954     * @see #setRotation(float)
9955     * @see #setRotationY(float)
9956     * @see #setCameraDistance(float)
9957     *
9958     * @attr ref android.R.styleable#View_rotationX
9959     */
9960    public void setRotationX(float rotationX) {
9961        if (rotationX != getRotationX()) {
9962            invalidateViewProperty(true, false);
9963            mRenderNode.setRotationX(rotationX);
9964            invalidateViewProperty(false, true);
9965
9966            invalidateParentIfNeededAndWasQuickRejected();
9967            notifySubtreeAccessibilityStateChangedIfNeeded();
9968        }
9969    }
9970
9971    /**
9972     * The amount that the view is scaled in x around the pivot point, as a proportion of
9973     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9974     *
9975     * <p>By default, this is 1.0f.
9976     *
9977     * @see #getPivotX()
9978     * @see #getPivotY()
9979     * @return The scaling factor.
9980     */
9981    @ViewDebug.ExportedProperty(category = "drawing")
9982    public float getScaleX() {
9983        return mRenderNode.getScaleX();
9984    }
9985
9986    /**
9987     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9988     * the view's unscaled width. A value of 1 means that no scaling is applied.
9989     *
9990     * @param scaleX The scaling factor.
9991     * @see #getPivotX()
9992     * @see #getPivotY()
9993     *
9994     * @attr ref android.R.styleable#View_scaleX
9995     */
9996    public void setScaleX(float scaleX) {
9997        if (scaleX != getScaleX()) {
9998            invalidateViewProperty(true, false);
9999            mRenderNode.setScaleX(scaleX);
10000            invalidateViewProperty(false, true);
10001
10002            invalidateParentIfNeededAndWasQuickRejected();
10003            notifySubtreeAccessibilityStateChangedIfNeeded();
10004        }
10005    }
10006
10007    /**
10008     * The amount that the view is scaled in y around the pivot point, as a proportion of
10009     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10010     *
10011     * <p>By default, this is 1.0f.
10012     *
10013     * @see #getPivotX()
10014     * @see #getPivotY()
10015     * @return The scaling factor.
10016     */
10017    @ViewDebug.ExportedProperty(category = "drawing")
10018    public float getScaleY() {
10019        return mRenderNode.getScaleY();
10020    }
10021
10022    /**
10023     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10024     * the view's unscaled width. A value of 1 means that no scaling is applied.
10025     *
10026     * @param scaleY The scaling factor.
10027     * @see #getPivotX()
10028     * @see #getPivotY()
10029     *
10030     * @attr ref android.R.styleable#View_scaleY
10031     */
10032    public void setScaleY(float scaleY) {
10033        if (scaleY != getScaleY()) {
10034            invalidateViewProperty(true, false);
10035            mRenderNode.setScaleY(scaleY);
10036            invalidateViewProperty(false, true);
10037
10038            invalidateParentIfNeededAndWasQuickRejected();
10039            notifySubtreeAccessibilityStateChangedIfNeeded();
10040        }
10041    }
10042
10043    /**
10044     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10045     * and {@link #setScaleX(float) scaled}.
10046     *
10047     * @see #getRotation()
10048     * @see #getScaleX()
10049     * @see #getScaleY()
10050     * @see #getPivotY()
10051     * @return The x location of the pivot point.
10052     *
10053     * @attr ref android.R.styleable#View_transformPivotX
10054     */
10055    @ViewDebug.ExportedProperty(category = "drawing")
10056    public float getPivotX() {
10057        return mRenderNode.getPivotX();
10058    }
10059
10060    /**
10061     * Sets the x location of the point around which the view is
10062     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10063     * By default, the pivot point is centered on the object.
10064     * Setting this property disables this behavior and causes the view to use only the
10065     * explicitly set pivotX and pivotY values.
10066     *
10067     * @param pivotX The x location of the pivot point.
10068     * @see #getRotation()
10069     * @see #getScaleX()
10070     * @see #getScaleY()
10071     * @see #getPivotY()
10072     *
10073     * @attr ref android.R.styleable#View_transformPivotX
10074     */
10075    public void setPivotX(float pivotX) {
10076        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10077            invalidateViewProperty(true, false);
10078            mRenderNode.setPivotX(pivotX);
10079            invalidateViewProperty(false, true);
10080
10081            invalidateParentIfNeededAndWasQuickRejected();
10082        }
10083    }
10084
10085    /**
10086     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10087     * and {@link #setScaleY(float) scaled}.
10088     *
10089     * @see #getRotation()
10090     * @see #getScaleX()
10091     * @see #getScaleY()
10092     * @see #getPivotY()
10093     * @return The y location of the pivot point.
10094     *
10095     * @attr ref android.R.styleable#View_transformPivotY
10096     */
10097    @ViewDebug.ExportedProperty(category = "drawing")
10098    public float getPivotY() {
10099        return mRenderNode.getPivotY();
10100    }
10101
10102    /**
10103     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10104     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10105     * Setting this property disables this behavior and causes the view to use only the
10106     * explicitly set pivotX and pivotY values.
10107     *
10108     * @param pivotY The y location of the pivot point.
10109     * @see #getRotation()
10110     * @see #getScaleX()
10111     * @see #getScaleY()
10112     * @see #getPivotY()
10113     *
10114     * @attr ref android.R.styleable#View_transformPivotY
10115     */
10116    public void setPivotY(float pivotY) {
10117        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10118            invalidateViewProperty(true, false);
10119            mRenderNode.setPivotY(pivotY);
10120            invalidateViewProperty(false, true);
10121
10122            invalidateParentIfNeededAndWasQuickRejected();
10123        }
10124    }
10125
10126    /**
10127     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10128     * completely transparent and 1 means the view is completely opaque.
10129     *
10130     * <p>By default this is 1.0f.
10131     * @return The opacity of the view.
10132     */
10133    @ViewDebug.ExportedProperty(category = "drawing")
10134    public float getAlpha() {
10135        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10136    }
10137
10138    /**
10139     * Returns whether this View has content which overlaps.
10140     *
10141     * <p>This function, intended to be overridden by specific View types, is an optimization when
10142     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10143     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10144     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10145     * directly. An example of overlapping rendering is a TextView with a background image, such as
10146     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10147     * ImageView with only the foreground image. The default implementation returns true; subclasses
10148     * should override if they have cases which can be optimized.</p>
10149     *
10150     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10151     * necessitates that a View return true if it uses the methods internally without passing the
10152     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10153     *
10154     * @return true if the content in this view might overlap, false otherwise.
10155     */
10156    public boolean hasOverlappingRendering() {
10157        return true;
10158    }
10159
10160    /**
10161     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10162     * completely transparent and 1 means the view is completely opaque.</p>
10163     *
10164     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10165     * performance implications, especially for large views. It is best to use the alpha property
10166     * sparingly and transiently, as in the case of fading animations.</p>
10167     *
10168     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10169     * strongly recommended for performance reasons to either override
10170     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10171     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10172     *
10173     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10174     * responsible for applying the opacity itself.</p>
10175     *
10176     * <p>Note that if the view is backed by a
10177     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10178     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10179     * 1.0 will supercede the alpha of the layer paint.</p>
10180     *
10181     * @param alpha The opacity of the view.
10182     *
10183     * @see #hasOverlappingRendering()
10184     * @see #setLayerType(int, android.graphics.Paint)
10185     *
10186     * @attr ref android.R.styleable#View_alpha
10187     */
10188    public void setAlpha(float alpha) {
10189        ensureTransformationInfo();
10190        if (mTransformationInfo.mAlpha != alpha) {
10191            mTransformationInfo.mAlpha = alpha;
10192            if (onSetAlpha((int) (alpha * 255))) {
10193                mPrivateFlags |= PFLAG_ALPHA_SET;
10194                // subclass is handling alpha - don't optimize rendering cache invalidation
10195                invalidateParentCaches();
10196                invalidate(true);
10197            } else {
10198                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10199                invalidateViewProperty(true, false);
10200                mRenderNode.setAlpha(getFinalAlpha());
10201                notifyViewAccessibilityStateChangedIfNeeded(
10202                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10203            }
10204        }
10205    }
10206
10207    /**
10208     * Faster version of setAlpha() which performs the same steps except there are
10209     * no calls to invalidate(). The caller of this function should perform proper invalidation
10210     * on the parent and this object. The return value indicates whether the subclass handles
10211     * alpha (the return value for onSetAlpha()).
10212     *
10213     * @param alpha The new value for the alpha property
10214     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10215     *         the new value for the alpha property is different from the old value
10216     */
10217    boolean setAlphaNoInvalidation(float alpha) {
10218        ensureTransformationInfo();
10219        if (mTransformationInfo.mAlpha != alpha) {
10220            mTransformationInfo.mAlpha = alpha;
10221            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10222            if (subclassHandlesAlpha) {
10223                mPrivateFlags |= PFLAG_ALPHA_SET;
10224                return true;
10225            } else {
10226                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10227                mRenderNode.setAlpha(getFinalAlpha());
10228            }
10229        }
10230        return false;
10231    }
10232
10233    /**
10234     * This property is hidden and intended only for use by the Fade transition, which
10235     * animates it to produce a visual translucency that does not side-effect (or get
10236     * affected by) the real alpha property. This value is composited with the other
10237     * alpha value (and the AlphaAnimation value, when that is present) to produce
10238     * a final visual translucency result, which is what is passed into the DisplayList.
10239     *
10240     * @hide
10241     */
10242    public void setTransitionAlpha(float alpha) {
10243        ensureTransformationInfo();
10244        if (mTransformationInfo.mTransitionAlpha != alpha) {
10245            mTransformationInfo.mTransitionAlpha = alpha;
10246            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10247            invalidateViewProperty(true, false);
10248            mRenderNode.setAlpha(getFinalAlpha());
10249        }
10250    }
10251
10252    /**
10253     * Calculates the visual alpha of this view, which is a combination of the actual
10254     * alpha value and the transitionAlpha value (if set).
10255     */
10256    private float getFinalAlpha() {
10257        if (mTransformationInfo != null) {
10258            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10259        }
10260        return 1;
10261    }
10262
10263    /**
10264     * This property is hidden and intended only for use by the Fade transition, which
10265     * animates it to produce a visual translucency that does not side-effect (or get
10266     * affected by) the real alpha property. This value is composited with the other
10267     * alpha value (and the AlphaAnimation value, when that is present) to produce
10268     * a final visual translucency result, which is what is passed into the DisplayList.
10269     *
10270     * @hide
10271     */
10272    public float getTransitionAlpha() {
10273        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10274    }
10275
10276    /**
10277     * Top position of this view relative to its parent.
10278     *
10279     * @return The top of this view, in pixels.
10280     */
10281    @ViewDebug.CapturedViewProperty
10282    public final int getTop() {
10283        return mTop;
10284    }
10285
10286    /**
10287     * Sets the top position of this view relative to its parent. This method is meant to be called
10288     * by the layout system and should not generally be called otherwise, because the property
10289     * may be changed at any time by the layout.
10290     *
10291     * @param top The top of this view, in pixels.
10292     */
10293    public final void setTop(int top) {
10294        if (top != mTop) {
10295            final boolean matrixIsIdentity = hasIdentityMatrix();
10296            if (matrixIsIdentity) {
10297                if (mAttachInfo != null) {
10298                    int minTop;
10299                    int yLoc;
10300                    if (top < mTop) {
10301                        minTop = top;
10302                        yLoc = top - mTop;
10303                    } else {
10304                        minTop = mTop;
10305                        yLoc = 0;
10306                    }
10307                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10308                }
10309            } else {
10310                // Double-invalidation is necessary to capture view's old and new areas
10311                invalidate(true);
10312            }
10313
10314            int width = mRight - mLeft;
10315            int oldHeight = mBottom - mTop;
10316
10317            mTop = top;
10318            mRenderNode.setTop(mTop);
10319
10320            sizeChange(width, mBottom - mTop, width, oldHeight);
10321
10322            if (!matrixIsIdentity) {
10323                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10324                invalidate(true);
10325            }
10326            mBackgroundSizeChanged = true;
10327            invalidateParentIfNeeded();
10328            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10329                // View was rejected last time it was drawn by its parent; this may have changed
10330                invalidateParentIfNeeded();
10331            }
10332        }
10333    }
10334
10335    /**
10336     * Bottom position of this view relative to its parent.
10337     *
10338     * @return The bottom of this view, in pixels.
10339     */
10340    @ViewDebug.CapturedViewProperty
10341    public final int getBottom() {
10342        return mBottom;
10343    }
10344
10345    /**
10346     * True if this view has changed since the last time being drawn.
10347     *
10348     * @return The dirty state of this view.
10349     */
10350    public boolean isDirty() {
10351        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10352    }
10353
10354    /**
10355     * Sets the bottom position of this view relative to its parent. This method is meant to be
10356     * called by the layout system and should not generally be called otherwise, because the
10357     * property may be changed at any time by the layout.
10358     *
10359     * @param bottom The bottom of this view, in pixels.
10360     */
10361    public final void setBottom(int bottom) {
10362        if (bottom != mBottom) {
10363            final boolean matrixIsIdentity = hasIdentityMatrix();
10364            if (matrixIsIdentity) {
10365                if (mAttachInfo != null) {
10366                    int maxBottom;
10367                    if (bottom < mBottom) {
10368                        maxBottom = mBottom;
10369                    } else {
10370                        maxBottom = bottom;
10371                    }
10372                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10373                }
10374            } else {
10375                // Double-invalidation is necessary to capture view's old and new areas
10376                invalidate(true);
10377            }
10378
10379            int width = mRight - mLeft;
10380            int oldHeight = mBottom - mTop;
10381
10382            mBottom = bottom;
10383            mRenderNode.setBottom(mBottom);
10384
10385            sizeChange(width, mBottom - mTop, width, oldHeight);
10386
10387            if (!matrixIsIdentity) {
10388                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10389                invalidate(true);
10390            }
10391            mBackgroundSizeChanged = true;
10392            invalidateParentIfNeeded();
10393            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10394                // View was rejected last time it was drawn by its parent; this may have changed
10395                invalidateParentIfNeeded();
10396            }
10397        }
10398    }
10399
10400    /**
10401     * Left position of this view relative to its parent.
10402     *
10403     * @return The left edge of this view, in pixels.
10404     */
10405    @ViewDebug.CapturedViewProperty
10406    public final int getLeft() {
10407        return mLeft;
10408    }
10409
10410    /**
10411     * Sets the left position of this view relative to its parent. This method is meant to be called
10412     * by the layout system and should not generally be called otherwise, because the property
10413     * may be changed at any time by the layout.
10414     *
10415     * @param left The left of this view, in pixels.
10416     */
10417    public final void setLeft(int left) {
10418        if (left != mLeft) {
10419            final boolean matrixIsIdentity = hasIdentityMatrix();
10420            if (matrixIsIdentity) {
10421                if (mAttachInfo != null) {
10422                    int minLeft;
10423                    int xLoc;
10424                    if (left < mLeft) {
10425                        minLeft = left;
10426                        xLoc = left - mLeft;
10427                    } else {
10428                        minLeft = mLeft;
10429                        xLoc = 0;
10430                    }
10431                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10432                }
10433            } else {
10434                // Double-invalidation is necessary to capture view's old and new areas
10435                invalidate(true);
10436            }
10437
10438            int oldWidth = mRight - mLeft;
10439            int height = mBottom - mTop;
10440
10441            mLeft = left;
10442            mRenderNode.setLeft(left);
10443
10444            sizeChange(mRight - mLeft, height, oldWidth, height);
10445
10446            if (!matrixIsIdentity) {
10447                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10448                invalidate(true);
10449            }
10450            mBackgroundSizeChanged = true;
10451            invalidateParentIfNeeded();
10452            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10453                // View was rejected last time it was drawn by its parent; this may have changed
10454                invalidateParentIfNeeded();
10455            }
10456        }
10457    }
10458
10459    /**
10460     * Right position of this view relative to its parent.
10461     *
10462     * @return The right edge of this view, in pixels.
10463     */
10464    @ViewDebug.CapturedViewProperty
10465    public final int getRight() {
10466        return mRight;
10467    }
10468
10469    /**
10470     * Sets the right position of this view relative to its parent. This method is meant to be called
10471     * by the layout system and should not generally be called otherwise, because the property
10472     * may be changed at any time by the layout.
10473     *
10474     * @param right The right of this view, in pixels.
10475     */
10476    public final void setRight(int right) {
10477        if (right != mRight) {
10478            final boolean matrixIsIdentity = hasIdentityMatrix();
10479            if (matrixIsIdentity) {
10480                if (mAttachInfo != null) {
10481                    int maxRight;
10482                    if (right < mRight) {
10483                        maxRight = mRight;
10484                    } else {
10485                        maxRight = right;
10486                    }
10487                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10488                }
10489            } else {
10490                // Double-invalidation is necessary to capture view's old and new areas
10491                invalidate(true);
10492            }
10493
10494            int oldWidth = mRight - mLeft;
10495            int height = mBottom - mTop;
10496
10497            mRight = right;
10498            mRenderNode.setRight(mRight);
10499
10500            sizeChange(mRight - mLeft, height, oldWidth, height);
10501
10502            if (!matrixIsIdentity) {
10503                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10504                invalidate(true);
10505            }
10506            mBackgroundSizeChanged = true;
10507            invalidateParentIfNeeded();
10508            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10509                // View was rejected last time it was drawn by its parent; this may have changed
10510                invalidateParentIfNeeded();
10511            }
10512        }
10513    }
10514
10515    /**
10516     * The visual x position of this view, in pixels. This is equivalent to the
10517     * {@link #setTranslationX(float) translationX} property plus the current
10518     * {@link #getLeft() left} property.
10519     *
10520     * @return The visual x position of this view, in pixels.
10521     */
10522    @ViewDebug.ExportedProperty(category = "drawing")
10523    public float getX() {
10524        return mLeft + getTranslationX();
10525    }
10526
10527    /**
10528     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10529     * {@link #setTranslationX(float) translationX} property to be the difference between
10530     * the x value passed in and the current {@link #getLeft() left} property.
10531     *
10532     * @param x The visual x position of this view, in pixels.
10533     */
10534    public void setX(float x) {
10535        setTranslationX(x - mLeft);
10536    }
10537
10538    /**
10539     * The visual y position of this view, in pixels. This is equivalent to the
10540     * {@link #setTranslationY(float) translationY} property plus the current
10541     * {@link #getTop() top} property.
10542     *
10543     * @return The visual y position of this view, in pixels.
10544     */
10545    @ViewDebug.ExportedProperty(category = "drawing")
10546    public float getY() {
10547        return mTop + getTranslationY();
10548    }
10549
10550    /**
10551     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10552     * {@link #setTranslationY(float) translationY} property to be the difference between
10553     * the y value passed in and the current {@link #getTop() top} property.
10554     *
10555     * @param y The visual y position of this view, in pixels.
10556     */
10557    public void setY(float y) {
10558        setTranslationY(y - mTop);
10559    }
10560
10561    /**
10562     * The visual z position of this view, in pixels. This is equivalent to the
10563     * {@link #setTranslationZ(float) translationZ} property plus the current
10564     * {@link #getElevation() elevation} property.
10565     *
10566     * @return The visual z position of this view, in pixels.
10567     */
10568    @ViewDebug.ExportedProperty(category = "drawing")
10569    public float getZ() {
10570        return getElevation() + getTranslationZ();
10571    }
10572
10573    /**
10574     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10575     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10576     * the x value passed in and the current {@link #getElevation() elevation} property.
10577     *
10578     * @param z The visual z position of this view, in pixels.
10579     */
10580    public void setZ(float z) {
10581        setTranslationZ(z - getElevation());
10582    }
10583
10584    /**
10585     * The base elevation of this view relative to its parent, in pixels.
10586     *
10587     * @return The base depth position of the view, in pixels.
10588     */
10589    @ViewDebug.ExportedProperty(category = "drawing")
10590    public float getElevation() {
10591        return mRenderNode.getElevation();
10592    }
10593
10594    /**
10595     * Sets the base elevation of this view, in pixels.
10596     *
10597     * @attr ref android.R.styleable#View_elevation
10598     */
10599    public void setElevation(float elevation) {
10600        if (elevation != getElevation()) {
10601            invalidateViewProperty(true, false);
10602            mRenderNode.setElevation(elevation);
10603            invalidateViewProperty(false, true);
10604
10605            invalidateParentIfNeededAndWasQuickRejected();
10606        }
10607    }
10608
10609    /**
10610     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10611     * This position is post-layout, in addition to wherever the object's
10612     * layout placed it.
10613     *
10614     * @return The horizontal position of this view relative to its left position, in pixels.
10615     */
10616    @ViewDebug.ExportedProperty(category = "drawing")
10617    public float getTranslationX() {
10618        return mRenderNode.getTranslationX();
10619    }
10620
10621    /**
10622     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10623     * This effectively positions the object post-layout, in addition to wherever the object's
10624     * layout placed it.
10625     *
10626     * @param translationX The horizontal position of this view relative to its left position,
10627     * in pixels.
10628     *
10629     * @attr ref android.R.styleable#View_translationX
10630     */
10631    public void setTranslationX(float translationX) {
10632        if (translationX != getTranslationX()) {
10633            invalidateViewProperty(true, false);
10634            mRenderNode.setTranslationX(translationX);
10635            invalidateViewProperty(false, true);
10636
10637            invalidateParentIfNeededAndWasQuickRejected();
10638            notifySubtreeAccessibilityStateChangedIfNeeded();
10639        }
10640    }
10641
10642    /**
10643     * The vertical location of this view relative to its {@link #getTop() top} position.
10644     * This position is post-layout, in addition to wherever the object's
10645     * layout placed it.
10646     *
10647     * @return The vertical position of this view relative to its top position,
10648     * in pixels.
10649     */
10650    @ViewDebug.ExportedProperty(category = "drawing")
10651    public float getTranslationY() {
10652        return mRenderNode.getTranslationY();
10653    }
10654
10655    /**
10656     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10657     * This effectively positions the object post-layout, in addition to wherever the object's
10658     * layout placed it.
10659     *
10660     * @param translationY The vertical position of this view relative to its top position,
10661     * in pixels.
10662     *
10663     * @attr ref android.R.styleable#View_translationY
10664     */
10665    public void setTranslationY(float translationY) {
10666        if (translationY != getTranslationY()) {
10667            invalidateViewProperty(true, false);
10668            mRenderNode.setTranslationY(translationY);
10669            invalidateViewProperty(false, true);
10670
10671            invalidateParentIfNeededAndWasQuickRejected();
10672        }
10673    }
10674
10675    /**
10676     * The depth location of this view relative to its {@link #getElevation() elevation}.
10677     *
10678     * @return The depth of this view relative to its elevation.
10679     */
10680    @ViewDebug.ExportedProperty(category = "drawing")
10681    public float getTranslationZ() {
10682        return mRenderNode.getTranslationZ();
10683    }
10684
10685    /**
10686     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10687     *
10688     * @attr ref android.R.styleable#View_translationZ
10689     */
10690    public void setTranslationZ(float translationZ) {
10691        if (translationZ != getTranslationZ()) {
10692            invalidateViewProperty(true, false);
10693            mRenderNode.setTranslationZ(translationZ);
10694            invalidateViewProperty(false, true);
10695
10696            invalidateParentIfNeededAndWasQuickRejected();
10697        }
10698    }
10699
10700    /**
10701     * Returns a ValueAnimator which can animate a clearing circle.
10702     * <p>
10703     * The View is prevented from drawing within the circle, so the content
10704     * behind the View shows through.
10705     *
10706     * @param centerX The x coordinate of the center of the animating circle.
10707     * @param centerY The y coordinate of the center of the animating circle.
10708     * @param startRadius The starting radius of the animating circle.
10709     * @param endRadius The ending radius of the animating circle.
10710     *
10711     * @hide
10712     */
10713    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10714            float startRadius, float endRadius) {
10715        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10716                startRadius, endRadius, true);
10717    }
10718
10719    /**
10720     * Returns the current StateListAnimator if exists.
10721     *
10722     * @return StateListAnimator or null if it does not exists
10723     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10724     */
10725    public StateListAnimator getStateListAnimator() {
10726        return mStateListAnimator;
10727    }
10728
10729    /**
10730     * Attaches the provided StateListAnimator to this View.
10731     * <p>
10732     * Any previously attached StateListAnimator will be detached.
10733     *
10734     * @param stateListAnimator The StateListAnimator to update the view
10735     * @see {@link android.animation.StateListAnimator}
10736     */
10737    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10738        if (mStateListAnimator == stateListAnimator) {
10739            return;
10740        }
10741        if (mStateListAnimator != null) {
10742            mStateListAnimator.setTarget(null);
10743        }
10744        mStateListAnimator = stateListAnimator;
10745        if (stateListAnimator != null) {
10746            stateListAnimator.setTarget(this);
10747            if (isAttachedToWindow()) {
10748                stateListAnimator.setState(getDrawableState());
10749            }
10750        }
10751    }
10752
10753    @Deprecated
10754    public void setOutline(@Nullable Outline outline) {
10755        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10756
10757        if (outline == null || outline.isEmpty()) {
10758            if (mOutline != null) {
10759                mOutline.setEmpty();
10760            }
10761        } else {
10762            // always copy the path since caller may reuse
10763            if (mOutline == null) {
10764                mOutline = new Outline();
10765            }
10766            mOutline.set(outline);
10767        }
10768        mRenderNode.setOutline(mOutline);
10769    }
10770
10771    /**
10772     * Returns whether the Outline should be used to clip the contents of the View.
10773     * <p>
10774     * Note that this flag will only be respected if the View's Outline returns true from
10775     * {@link Outline#canClip()}.
10776     *
10777     * @see #setOutlineProvider(ViewOutlineProvider)
10778     * @see #setClipToOutline(boolean)
10779     */
10780    public final boolean getClipToOutline() {
10781        return mRenderNode.getClipToOutline();
10782    }
10783
10784    /**
10785     * Sets whether the View's Outline should be used to clip the contents of the View.
10786     * <p>
10787     * Note that this flag will only be respected if the View's Outline returns true from
10788     * {@link Outline#canClip()}.
10789     *
10790     * @see #setOutlineProvider(ViewOutlineProvider)
10791     * @see #getClipToOutline()
10792     */
10793    public void setClipToOutline(boolean clipToOutline) {
10794        damageInParent();
10795        if (getClipToOutline() != clipToOutline) {
10796            mRenderNode.setClipToOutline(clipToOutline);
10797        }
10798    }
10799
10800    /**
10801     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10802     * the shape of the shadow it casts, and enables outline clipping.
10803     * <p>
10804     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10805     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10806     * outline provider with this method allows this behavior to be overridden.
10807     * <p>
10808     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10809     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10810     * <p>
10811     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10812     *
10813     * @see #setClipToOutline(boolean)
10814     * @see #getClipToOutline()
10815     * @see #getOutlineProvider()
10816     */
10817    public void setOutlineProvider(ViewOutlineProvider provider) {
10818        mOutlineProvider = provider;
10819        invalidateOutline();
10820    }
10821
10822    /**
10823     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10824     * that defines the shape of the shadow it casts, and enables outline clipping.
10825     *
10826     * @see #setOutlineProvider(ViewOutlineProvider)
10827     */
10828    public ViewOutlineProvider getOutlineProvider() {
10829        return mOutlineProvider;
10830    }
10831
10832    /**
10833     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10834     *
10835     * @see #setOutlineProvider(ViewOutlineProvider)
10836     */
10837    public void invalidateOutline() {
10838        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) != 0) {
10839            // TODO: remove this when removing old outline code
10840            // setOutline() was called to manually set outline, ignore provider
10841            return;
10842        }
10843
10844        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10845        if (mAttachInfo == null) return;
10846
10847        final Outline outline = mAttachInfo.mTmpOutline;
10848        outline.setEmpty();
10849
10850        if (mOutlineProvider == null) {
10851            // no provider, remove outline
10852            mRenderNode.setOutline(null);
10853        } else {
10854            if (mOutlineProvider.getOutline(this, outline)) {
10855                if (outline.isEmpty()) {
10856                    throw new IllegalStateException("Outline provider failed to build outline");
10857                }
10858                // provider has provided
10859                mRenderNode.setOutline(outline);
10860            } else {
10861                // provider failed to provide
10862                mRenderNode.setOutline(null);
10863            }
10864        }
10865
10866        notifySubtreeAccessibilityStateChangedIfNeeded();
10867        invalidateViewProperty(false, false);
10868    }
10869
10870    /**
10871     * Private API to be used for reveal animation
10872     *
10873     * @hide
10874     */
10875    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10876            float x, float y, float radius) {
10877        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10878        // TODO: Handle this invalidate in a better way, or purely in native.
10879        invalidate();
10880    }
10881
10882    /**
10883     * Hit rectangle in parent's coordinates
10884     *
10885     * @param outRect The hit rectangle of the view.
10886     */
10887    public void getHitRect(Rect outRect) {
10888        if (hasIdentityMatrix() || mAttachInfo == null) {
10889            outRect.set(mLeft, mTop, mRight, mBottom);
10890        } else {
10891            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10892            tmpRect.set(0, 0, getWidth(), getHeight());
10893            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10894            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10895                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10896        }
10897    }
10898
10899    /**
10900     * Determines whether the given point, in local coordinates is inside the view.
10901     */
10902    /*package*/ final boolean pointInView(float localX, float localY) {
10903        return localX >= 0 && localX < (mRight - mLeft)
10904                && localY >= 0 && localY < (mBottom - mTop);
10905    }
10906
10907    /**
10908     * Utility method to determine whether the given point, in local coordinates,
10909     * is inside the view, where the area of the view is expanded by the slop factor.
10910     * This method is called while processing touch-move events to determine if the event
10911     * is still within the view.
10912     *
10913     * @hide
10914     */
10915    public boolean pointInView(float localX, float localY, float slop) {
10916        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10917                localY < ((mBottom - mTop) + slop);
10918    }
10919
10920    /**
10921     * When a view has focus and the user navigates away from it, the next view is searched for
10922     * starting from the rectangle filled in by this method.
10923     *
10924     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10925     * of the view.  However, if your view maintains some idea of internal selection,
10926     * such as a cursor, or a selected row or column, you should override this method and
10927     * fill in a more specific rectangle.
10928     *
10929     * @param r The rectangle to fill in, in this view's coordinates.
10930     */
10931    public void getFocusedRect(Rect r) {
10932        getDrawingRect(r);
10933    }
10934
10935    /**
10936     * If some part of this view is not clipped by any of its parents, then
10937     * return that area in r in global (root) coordinates. To convert r to local
10938     * coordinates (without taking possible View rotations into account), offset
10939     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10940     * If the view is completely clipped or translated out, return false.
10941     *
10942     * @param r If true is returned, r holds the global coordinates of the
10943     *        visible portion of this view.
10944     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10945     *        between this view and its root. globalOffet may be null.
10946     * @return true if r is non-empty (i.e. part of the view is visible at the
10947     *         root level.
10948     */
10949    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10950        int width = mRight - mLeft;
10951        int height = mBottom - mTop;
10952        if (width > 0 && height > 0) {
10953            r.set(0, 0, width, height);
10954            if (globalOffset != null) {
10955                globalOffset.set(-mScrollX, -mScrollY);
10956            }
10957            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10958        }
10959        return false;
10960    }
10961
10962    public final boolean getGlobalVisibleRect(Rect r) {
10963        return getGlobalVisibleRect(r, null);
10964    }
10965
10966    public final boolean getLocalVisibleRect(Rect r) {
10967        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10968        if (getGlobalVisibleRect(r, offset)) {
10969            r.offset(-offset.x, -offset.y); // make r local
10970            return true;
10971        }
10972        return false;
10973    }
10974
10975    /**
10976     * Offset this view's vertical location by the specified number of pixels.
10977     *
10978     * @param offset the number of pixels to offset the view by
10979     */
10980    public void offsetTopAndBottom(int offset) {
10981        if (offset != 0) {
10982            final boolean matrixIsIdentity = hasIdentityMatrix();
10983            if (matrixIsIdentity) {
10984                if (isHardwareAccelerated()) {
10985                    invalidateViewProperty(false, false);
10986                } else {
10987                    final ViewParent p = mParent;
10988                    if (p != null && mAttachInfo != null) {
10989                        final Rect r = mAttachInfo.mTmpInvalRect;
10990                        int minTop;
10991                        int maxBottom;
10992                        int yLoc;
10993                        if (offset < 0) {
10994                            minTop = mTop + offset;
10995                            maxBottom = mBottom;
10996                            yLoc = offset;
10997                        } else {
10998                            minTop = mTop;
10999                            maxBottom = mBottom + offset;
11000                            yLoc = 0;
11001                        }
11002                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11003                        p.invalidateChild(this, r);
11004                    }
11005                }
11006            } else {
11007                invalidateViewProperty(false, false);
11008            }
11009
11010            mTop += offset;
11011            mBottom += offset;
11012            mRenderNode.offsetTopAndBottom(offset);
11013            if (isHardwareAccelerated()) {
11014                invalidateViewProperty(false, false);
11015            } else {
11016                if (!matrixIsIdentity) {
11017                    invalidateViewProperty(false, true);
11018                }
11019                invalidateParentIfNeeded();
11020            }
11021            notifySubtreeAccessibilityStateChangedIfNeeded();
11022        }
11023    }
11024
11025    /**
11026     * Offset this view's horizontal location by the specified amount of pixels.
11027     *
11028     * @param offset the number of pixels to offset the view by
11029     */
11030    public void offsetLeftAndRight(int offset) {
11031        if (offset != 0) {
11032            final boolean matrixIsIdentity = hasIdentityMatrix();
11033            if (matrixIsIdentity) {
11034                if (isHardwareAccelerated()) {
11035                    invalidateViewProperty(false, false);
11036                } else {
11037                    final ViewParent p = mParent;
11038                    if (p != null && mAttachInfo != null) {
11039                        final Rect r = mAttachInfo.mTmpInvalRect;
11040                        int minLeft;
11041                        int maxRight;
11042                        if (offset < 0) {
11043                            minLeft = mLeft + offset;
11044                            maxRight = mRight;
11045                        } else {
11046                            minLeft = mLeft;
11047                            maxRight = mRight + offset;
11048                        }
11049                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11050                        p.invalidateChild(this, r);
11051                    }
11052                }
11053            } else {
11054                invalidateViewProperty(false, false);
11055            }
11056
11057            mLeft += offset;
11058            mRight += offset;
11059            mRenderNode.offsetLeftAndRight(offset);
11060            if (isHardwareAccelerated()) {
11061                invalidateViewProperty(false, false);
11062            } else {
11063                if (!matrixIsIdentity) {
11064                    invalidateViewProperty(false, true);
11065                }
11066                invalidateParentIfNeeded();
11067            }
11068            notifySubtreeAccessibilityStateChangedIfNeeded();
11069        }
11070    }
11071
11072    /**
11073     * Get the LayoutParams associated with this view. All views should have
11074     * layout parameters. These supply parameters to the <i>parent</i> of this
11075     * view specifying how it should be arranged. There are many subclasses of
11076     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11077     * of ViewGroup that are responsible for arranging their children.
11078     *
11079     * This method may return null if this View is not attached to a parent
11080     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11081     * was not invoked successfully. When a View is attached to a parent
11082     * ViewGroup, this method must not return null.
11083     *
11084     * @return The LayoutParams associated with this view, or null if no
11085     *         parameters have been set yet
11086     */
11087    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11088    public ViewGroup.LayoutParams getLayoutParams() {
11089        return mLayoutParams;
11090    }
11091
11092    /**
11093     * Set the layout parameters associated with this view. These supply
11094     * parameters to the <i>parent</i> of this view specifying how it should be
11095     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11096     * correspond to the different subclasses of ViewGroup that are responsible
11097     * for arranging their children.
11098     *
11099     * @param params The layout parameters for this view, cannot be null
11100     */
11101    public void setLayoutParams(ViewGroup.LayoutParams params) {
11102        if (params == null) {
11103            throw new NullPointerException("Layout parameters cannot be null");
11104        }
11105        mLayoutParams = params;
11106        resolveLayoutParams();
11107        if (mParent instanceof ViewGroup) {
11108            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11109        }
11110        requestLayout();
11111    }
11112
11113    /**
11114     * Resolve the layout parameters depending on the resolved layout direction
11115     *
11116     * @hide
11117     */
11118    public void resolveLayoutParams() {
11119        if (mLayoutParams != null) {
11120            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11121        }
11122    }
11123
11124    /**
11125     * Set the scrolled position of your view. This will cause a call to
11126     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11127     * invalidated.
11128     * @param x the x position to scroll to
11129     * @param y the y position to scroll to
11130     */
11131    public void scrollTo(int x, int y) {
11132        if (mScrollX != x || mScrollY != y) {
11133            int oldX = mScrollX;
11134            int oldY = mScrollY;
11135            mScrollX = x;
11136            mScrollY = y;
11137            invalidateParentCaches();
11138            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11139            if (!awakenScrollBars()) {
11140                postInvalidateOnAnimation();
11141            }
11142        }
11143    }
11144
11145    /**
11146     * Move the scrolled position of your view. This will cause a call to
11147     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11148     * invalidated.
11149     * @param x the amount of pixels to scroll by horizontally
11150     * @param y the amount of pixels to scroll by vertically
11151     */
11152    public void scrollBy(int x, int y) {
11153        scrollTo(mScrollX + x, mScrollY + y);
11154    }
11155
11156    /**
11157     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11158     * animation to fade the scrollbars out after a default delay. If a subclass
11159     * provides animated scrolling, the start delay should equal the duration
11160     * of the scrolling animation.</p>
11161     *
11162     * <p>The animation starts only if at least one of the scrollbars is
11163     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11164     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11165     * this method returns true, and false otherwise. If the animation is
11166     * started, this method calls {@link #invalidate()}; in that case the
11167     * caller should not call {@link #invalidate()}.</p>
11168     *
11169     * <p>This method should be invoked every time a subclass directly updates
11170     * the scroll parameters.</p>
11171     *
11172     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11173     * and {@link #scrollTo(int, int)}.</p>
11174     *
11175     * @return true if the animation is played, false otherwise
11176     *
11177     * @see #awakenScrollBars(int)
11178     * @see #scrollBy(int, int)
11179     * @see #scrollTo(int, int)
11180     * @see #isHorizontalScrollBarEnabled()
11181     * @see #isVerticalScrollBarEnabled()
11182     * @see #setHorizontalScrollBarEnabled(boolean)
11183     * @see #setVerticalScrollBarEnabled(boolean)
11184     */
11185    protected boolean awakenScrollBars() {
11186        return mScrollCache != null &&
11187                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11188    }
11189
11190    /**
11191     * Trigger the scrollbars to draw.
11192     * This method differs from awakenScrollBars() only in its default duration.
11193     * initialAwakenScrollBars() will show the scroll bars for longer than
11194     * usual to give the user more of a chance to notice them.
11195     *
11196     * @return true if the animation is played, false otherwise.
11197     */
11198    private boolean initialAwakenScrollBars() {
11199        return mScrollCache != null &&
11200                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11201    }
11202
11203    /**
11204     * <p>
11205     * Trigger the scrollbars to draw. When invoked this method starts an
11206     * animation to fade the scrollbars out after a fixed delay. If a subclass
11207     * provides animated scrolling, the start delay should equal the duration of
11208     * the scrolling animation.
11209     * </p>
11210     *
11211     * <p>
11212     * The animation starts only if at least one of the scrollbars is enabled,
11213     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11214     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11215     * this method returns true, and false otherwise. If the animation is
11216     * started, this method calls {@link #invalidate()}; in that case the caller
11217     * should not call {@link #invalidate()}.
11218     * </p>
11219     *
11220     * <p>
11221     * This method should be invoked everytime a subclass directly updates the
11222     * scroll parameters.
11223     * </p>
11224     *
11225     * @param startDelay the delay, in milliseconds, after which the animation
11226     *        should start; when the delay is 0, the animation starts
11227     *        immediately
11228     * @return true if the animation is played, false otherwise
11229     *
11230     * @see #scrollBy(int, int)
11231     * @see #scrollTo(int, int)
11232     * @see #isHorizontalScrollBarEnabled()
11233     * @see #isVerticalScrollBarEnabled()
11234     * @see #setHorizontalScrollBarEnabled(boolean)
11235     * @see #setVerticalScrollBarEnabled(boolean)
11236     */
11237    protected boolean awakenScrollBars(int startDelay) {
11238        return awakenScrollBars(startDelay, true);
11239    }
11240
11241    /**
11242     * <p>
11243     * Trigger the scrollbars to draw. When invoked this method starts an
11244     * animation to fade the scrollbars out after a fixed delay. If a subclass
11245     * provides animated scrolling, the start delay should equal the duration of
11246     * the scrolling animation.
11247     * </p>
11248     *
11249     * <p>
11250     * The animation starts only if at least one of the scrollbars is enabled,
11251     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11252     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11253     * this method returns true, and false otherwise. If the animation is
11254     * started, this method calls {@link #invalidate()} if the invalidate parameter
11255     * is set to true; in that case the caller
11256     * should not call {@link #invalidate()}.
11257     * </p>
11258     *
11259     * <p>
11260     * This method should be invoked everytime a subclass directly updates the
11261     * scroll parameters.
11262     * </p>
11263     *
11264     * @param startDelay the delay, in milliseconds, after which the animation
11265     *        should start; when the delay is 0, the animation starts
11266     *        immediately
11267     *
11268     * @param invalidate Wheter this method should call invalidate
11269     *
11270     * @return true if the animation is played, false otherwise
11271     *
11272     * @see #scrollBy(int, int)
11273     * @see #scrollTo(int, int)
11274     * @see #isHorizontalScrollBarEnabled()
11275     * @see #isVerticalScrollBarEnabled()
11276     * @see #setHorizontalScrollBarEnabled(boolean)
11277     * @see #setVerticalScrollBarEnabled(boolean)
11278     */
11279    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11280        final ScrollabilityCache scrollCache = mScrollCache;
11281
11282        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11283            return false;
11284        }
11285
11286        if (scrollCache.scrollBar == null) {
11287            scrollCache.scrollBar = new ScrollBarDrawable();
11288        }
11289
11290        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11291
11292            if (invalidate) {
11293                // Invalidate to show the scrollbars
11294                postInvalidateOnAnimation();
11295            }
11296
11297            if (scrollCache.state == ScrollabilityCache.OFF) {
11298                // FIXME: this is copied from WindowManagerService.
11299                // We should get this value from the system when it
11300                // is possible to do so.
11301                final int KEY_REPEAT_FIRST_DELAY = 750;
11302                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11303            }
11304
11305            // Tell mScrollCache when we should start fading. This may
11306            // extend the fade start time if one was already scheduled
11307            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11308            scrollCache.fadeStartTime = fadeStartTime;
11309            scrollCache.state = ScrollabilityCache.ON;
11310
11311            // Schedule our fader to run, unscheduling any old ones first
11312            if (mAttachInfo != null) {
11313                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11314                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11315            }
11316
11317            return true;
11318        }
11319
11320        return false;
11321    }
11322
11323    /**
11324     * Do not invalidate views which are not visible and which are not running an animation. They
11325     * will not get drawn and they should not set dirty flags as if they will be drawn
11326     */
11327    private boolean skipInvalidate() {
11328        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11329                (!(mParent instanceof ViewGroup) ||
11330                        !((ViewGroup) mParent).isViewTransitioning(this));
11331    }
11332
11333    /**
11334     * Mark the area defined by dirty as needing to be drawn. If the view is
11335     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11336     * point in the future.
11337     * <p>
11338     * This must be called from a UI thread. To call from a non-UI thread, call
11339     * {@link #postInvalidate()}.
11340     * <p>
11341     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11342     * {@code dirty}.
11343     *
11344     * @param dirty the rectangle representing the bounds of the dirty region
11345     */
11346    public void invalidate(Rect dirty) {
11347        final int scrollX = mScrollX;
11348        final int scrollY = mScrollY;
11349        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11350                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11351    }
11352
11353    /**
11354     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11355     * coordinates of the dirty rect are relative to the view. If the view is
11356     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11357     * point in the future.
11358     * <p>
11359     * This must be called from a UI thread. To call from a non-UI thread, call
11360     * {@link #postInvalidate()}.
11361     *
11362     * @param l the left position of the dirty region
11363     * @param t the top position of the dirty region
11364     * @param r the right position of the dirty region
11365     * @param b the bottom position of the dirty region
11366     */
11367    public void invalidate(int l, int t, int r, int b) {
11368        final int scrollX = mScrollX;
11369        final int scrollY = mScrollY;
11370        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11371    }
11372
11373    /**
11374     * Invalidate the whole view. If the view is visible,
11375     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11376     * the future.
11377     * <p>
11378     * This must be called from a UI thread. To call from a non-UI thread, call
11379     * {@link #postInvalidate()}.
11380     */
11381    public void invalidate() {
11382        invalidate(true);
11383    }
11384
11385    /**
11386     * This is where the invalidate() work actually happens. A full invalidate()
11387     * causes the drawing cache to be invalidated, but this function can be
11388     * called with invalidateCache set to false to skip that invalidation step
11389     * for cases that do not need it (for example, a component that remains at
11390     * the same dimensions with the same content).
11391     *
11392     * @param invalidateCache Whether the drawing cache for this view should be
11393     *            invalidated as well. This is usually true for a full
11394     *            invalidate, but may be set to false if the View's contents or
11395     *            dimensions have not changed.
11396     */
11397    void invalidate(boolean invalidateCache) {
11398        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11399    }
11400
11401    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11402            boolean fullInvalidate) {
11403        if (skipInvalidate()) {
11404            return;
11405        }
11406
11407        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11408                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11409                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11410                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11411            if (fullInvalidate) {
11412                mLastIsOpaque = isOpaque();
11413                mPrivateFlags &= ~PFLAG_DRAWN;
11414            }
11415
11416            mPrivateFlags |= PFLAG_DIRTY;
11417
11418            if (invalidateCache) {
11419                mPrivateFlags |= PFLAG_INVALIDATED;
11420                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11421            }
11422
11423            // Propagate the damage rectangle to the parent view.
11424            final AttachInfo ai = mAttachInfo;
11425            final ViewParent p = mParent;
11426            if (p != null && ai != null && l < r && t < b) {
11427                final Rect damage = ai.mTmpInvalRect;
11428                damage.set(l, t, r, b);
11429                p.invalidateChild(this, damage);
11430            }
11431
11432            // Damage the entire projection receiver, if necessary.
11433            if (mBackground != null && mBackground.isProjected()) {
11434                final View receiver = getProjectionReceiver();
11435                if (receiver != null) {
11436                    receiver.damageInParent();
11437                }
11438            }
11439
11440            // Damage the entire IsolatedZVolume recieving this view's shadow.
11441            if (isHardwareAccelerated() && getZ() != 0) {
11442                damageShadowReceiver();
11443            }
11444        }
11445    }
11446
11447    /**
11448     * @return this view's projection receiver, or {@code null} if none exists
11449     */
11450    private View getProjectionReceiver() {
11451        ViewParent p = getParent();
11452        while (p != null && p instanceof View) {
11453            final View v = (View) p;
11454            if (v.isProjectionReceiver()) {
11455                return v;
11456            }
11457            p = p.getParent();
11458        }
11459
11460        return null;
11461    }
11462
11463    /**
11464     * @return whether the view is a projection receiver
11465     */
11466    private boolean isProjectionReceiver() {
11467        return mBackground != null;
11468    }
11469
11470    /**
11471     * Damage area of the screen that can be covered by this View's shadow.
11472     *
11473     * This method will guarantee that any changes to shadows cast by a View
11474     * are damaged on the screen for future redraw.
11475     */
11476    private void damageShadowReceiver() {
11477        final AttachInfo ai = mAttachInfo;
11478        if (ai != null) {
11479            ViewParent p = getParent();
11480            if (p != null && p instanceof ViewGroup) {
11481                final ViewGroup vg = (ViewGroup) p;
11482                vg.damageInParent();
11483            }
11484        }
11485    }
11486
11487    /**
11488     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11489     * set any flags or handle all of the cases handled by the default invalidation methods.
11490     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11491     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11492     * walk up the hierarchy, transforming the dirty rect as necessary.
11493     *
11494     * The method also handles normal invalidation logic if display list properties are not
11495     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11496     * backup approach, to handle these cases used in the various property-setting methods.
11497     *
11498     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11499     * are not being used in this view
11500     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11501     * list properties are not being used in this view
11502     */
11503    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11504        if (!isHardwareAccelerated()
11505                || !mRenderNode.isValid()
11506                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11507            if (invalidateParent) {
11508                invalidateParentCaches();
11509            }
11510            if (forceRedraw) {
11511                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11512            }
11513            invalidate(false);
11514        } else {
11515            damageInParent();
11516        }
11517        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11518            damageShadowReceiver();
11519        }
11520    }
11521
11522    /**
11523     * Tells the parent view to damage this view's bounds.
11524     *
11525     * @hide
11526     */
11527    protected void damageInParent() {
11528        final AttachInfo ai = mAttachInfo;
11529        final ViewParent p = mParent;
11530        if (p != null && ai != null) {
11531            final Rect r = ai.mTmpInvalRect;
11532            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11533            if (mParent instanceof ViewGroup) {
11534                ((ViewGroup) mParent).damageChild(this, r);
11535            } else {
11536                mParent.invalidateChild(this, r);
11537            }
11538        }
11539    }
11540
11541    /**
11542     * Utility method to transform a given Rect by the current matrix of this view.
11543     */
11544    void transformRect(final Rect rect) {
11545        if (!getMatrix().isIdentity()) {
11546            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11547            boundingRect.set(rect);
11548            getMatrix().mapRect(boundingRect);
11549            rect.set((int) Math.floor(boundingRect.left),
11550                    (int) Math.floor(boundingRect.top),
11551                    (int) Math.ceil(boundingRect.right),
11552                    (int) Math.ceil(boundingRect.bottom));
11553        }
11554    }
11555
11556    /**
11557     * Used to indicate that the parent of this view should clear its caches. This functionality
11558     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11559     * which is necessary when various parent-managed properties of the view change, such as
11560     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11561     * clears the parent caches and does not causes an invalidate event.
11562     *
11563     * @hide
11564     */
11565    protected void invalidateParentCaches() {
11566        if (mParent instanceof View) {
11567            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11568        }
11569    }
11570
11571    /**
11572     * Used to indicate that the parent of this view should be invalidated. This functionality
11573     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11574     * which is necessary when various parent-managed properties of the view change, such as
11575     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11576     * an invalidation event to the parent.
11577     *
11578     * @hide
11579     */
11580    protected void invalidateParentIfNeeded() {
11581        if (isHardwareAccelerated() && mParent instanceof View) {
11582            ((View) mParent).invalidate(true);
11583        }
11584    }
11585
11586    /**
11587     * @hide
11588     */
11589    protected void invalidateParentIfNeededAndWasQuickRejected() {
11590        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11591            // View was rejected last time it was drawn by its parent; this may have changed
11592            invalidateParentIfNeeded();
11593        }
11594    }
11595
11596    /**
11597     * Indicates whether this View is opaque. An opaque View guarantees that it will
11598     * draw all the pixels overlapping its bounds using a fully opaque color.
11599     *
11600     * Subclasses of View should override this method whenever possible to indicate
11601     * whether an instance is opaque. Opaque Views are treated in a special way by
11602     * the View hierarchy, possibly allowing it to perform optimizations during
11603     * invalidate/draw passes.
11604     *
11605     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11606     */
11607    @ViewDebug.ExportedProperty(category = "drawing")
11608    public boolean isOpaque() {
11609        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11610                getFinalAlpha() >= 1.0f;
11611    }
11612
11613    /**
11614     * @hide
11615     */
11616    protected void computeOpaqueFlags() {
11617        // Opaque if:
11618        //   - Has a background
11619        //   - Background is opaque
11620        //   - Doesn't have scrollbars or scrollbars overlay
11621
11622        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11623            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11624        } else {
11625            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11626        }
11627
11628        final int flags = mViewFlags;
11629        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11630                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11631                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11632            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11633        } else {
11634            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11635        }
11636    }
11637
11638    /**
11639     * @hide
11640     */
11641    protected boolean hasOpaqueScrollbars() {
11642        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11643    }
11644
11645    /**
11646     * @return A handler associated with the thread running the View. This
11647     * handler can be used to pump events in the UI events queue.
11648     */
11649    public Handler getHandler() {
11650        final AttachInfo attachInfo = mAttachInfo;
11651        if (attachInfo != null) {
11652            return attachInfo.mHandler;
11653        }
11654        return null;
11655    }
11656
11657    /**
11658     * Gets the view root associated with the View.
11659     * @return The view root, or null if none.
11660     * @hide
11661     */
11662    public ViewRootImpl getViewRootImpl() {
11663        if (mAttachInfo != null) {
11664            return mAttachInfo.mViewRootImpl;
11665        }
11666        return null;
11667    }
11668
11669    /**
11670     * @hide
11671     */
11672    public HardwareRenderer getHardwareRenderer() {
11673        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11674    }
11675
11676    /**
11677     * <p>Causes the Runnable to be added to the message queue.
11678     * The runnable will be run on the user interface thread.</p>
11679     *
11680     * @param action The Runnable that will be executed.
11681     *
11682     * @return Returns true if the Runnable was successfully placed in to the
11683     *         message queue.  Returns false on failure, usually because the
11684     *         looper processing the message queue is exiting.
11685     *
11686     * @see #postDelayed
11687     * @see #removeCallbacks
11688     */
11689    public boolean post(Runnable action) {
11690        final AttachInfo attachInfo = mAttachInfo;
11691        if (attachInfo != null) {
11692            return attachInfo.mHandler.post(action);
11693        }
11694        // Assume that post will succeed later
11695        ViewRootImpl.getRunQueue().post(action);
11696        return true;
11697    }
11698
11699    /**
11700     * <p>Causes the Runnable to be added to the message queue, to be run
11701     * after the specified amount of time elapses.
11702     * The runnable will be run on the user interface thread.</p>
11703     *
11704     * @param action The Runnable that will be executed.
11705     * @param delayMillis The delay (in milliseconds) until the Runnable
11706     *        will be executed.
11707     *
11708     * @return true if the Runnable was successfully placed in to the
11709     *         message queue.  Returns false on failure, usually because the
11710     *         looper processing the message queue is exiting.  Note that a
11711     *         result of true does not mean the Runnable will be processed --
11712     *         if the looper is quit before the delivery time of the message
11713     *         occurs then the message will be dropped.
11714     *
11715     * @see #post
11716     * @see #removeCallbacks
11717     */
11718    public boolean postDelayed(Runnable action, long delayMillis) {
11719        final AttachInfo attachInfo = mAttachInfo;
11720        if (attachInfo != null) {
11721            return attachInfo.mHandler.postDelayed(action, delayMillis);
11722        }
11723        // Assume that post will succeed later
11724        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11725        return true;
11726    }
11727
11728    /**
11729     * <p>Causes the Runnable to execute on the next animation time step.
11730     * The runnable will be run on the user interface thread.</p>
11731     *
11732     * @param action The Runnable that will be executed.
11733     *
11734     * @see #postOnAnimationDelayed
11735     * @see #removeCallbacks
11736     */
11737    public void postOnAnimation(Runnable action) {
11738        final AttachInfo attachInfo = mAttachInfo;
11739        if (attachInfo != null) {
11740            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11741                    Choreographer.CALLBACK_ANIMATION, action, null);
11742        } else {
11743            // Assume that post will succeed later
11744            ViewRootImpl.getRunQueue().post(action);
11745        }
11746    }
11747
11748    /**
11749     * <p>Causes the Runnable to execute on the next animation time step,
11750     * after the specified amount of time elapses.
11751     * The runnable will be run on the user interface thread.</p>
11752     *
11753     * @param action The Runnable that will be executed.
11754     * @param delayMillis The delay (in milliseconds) until the Runnable
11755     *        will be executed.
11756     *
11757     * @see #postOnAnimation
11758     * @see #removeCallbacks
11759     */
11760    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11761        final AttachInfo attachInfo = mAttachInfo;
11762        if (attachInfo != null) {
11763            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11764                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11765        } else {
11766            // Assume that post will succeed later
11767            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11768        }
11769    }
11770
11771    /**
11772     * <p>Removes the specified Runnable from the message queue.</p>
11773     *
11774     * @param action The Runnable to remove from the message handling queue
11775     *
11776     * @return true if this view could ask the Handler to remove the Runnable,
11777     *         false otherwise. When the returned value is true, the Runnable
11778     *         may or may not have been actually removed from the message queue
11779     *         (for instance, if the Runnable was not in the queue already.)
11780     *
11781     * @see #post
11782     * @see #postDelayed
11783     * @see #postOnAnimation
11784     * @see #postOnAnimationDelayed
11785     */
11786    public boolean removeCallbacks(Runnable action) {
11787        if (action != null) {
11788            final AttachInfo attachInfo = mAttachInfo;
11789            if (attachInfo != null) {
11790                attachInfo.mHandler.removeCallbacks(action);
11791                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11792                        Choreographer.CALLBACK_ANIMATION, action, null);
11793            }
11794            // Assume that post will succeed later
11795            ViewRootImpl.getRunQueue().removeCallbacks(action);
11796        }
11797        return true;
11798    }
11799
11800    /**
11801     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11802     * Use this to invalidate the View from a non-UI thread.</p>
11803     *
11804     * <p>This method can be invoked from outside of the UI thread
11805     * only when this View is attached to a window.</p>
11806     *
11807     * @see #invalidate()
11808     * @see #postInvalidateDelayed(long)
11809     */
11810    public void postInvalidate() {
11811        postInvalidateDelayed(0);
11812    }
11813
11814    /**
11815     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11816     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11817     *
11818     * <p>This method can be invoked from outside of the UI thread
11819     * only when this View is attached to a window.</p>
11820     *
11821     * @param left The left coordinate of the rectangle to invalidate.
11822     * @param top The top coordinate of the rectangle to invalidate.
11823     * @param right The right coordinate of the rectangle to invalidate.
11824     * @param bottom The bottom coordinate of the rectangle to invalidate.
11825     *
11826     * @see #invalidate(int, int, int, int)
11827     * @see #invalidate(Rect)
11828     * @see #postInvalidateDelayed(long, int, int, int, int)
11829     */
11830    public void postInvalidate(int left, int top, int right, int bottom) {
11831        postInvalidateDelayed(0, left, top, right, bottom);
11832    }
11833
11834    /**
11835     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11836     * loop. Waits for the specified amount of time.</p>
11837     *
11838     * <p>This method can be invoked from outside of the UI thread
11839     * only when this View is attached to a window.</p>
11840     *
11841     * @param delayMilliseconds the duration in milliseconds to delay the
11842     *         invalidation by
11843     *
11844     * @see #invalidate()
11845     * @see #postInvalidate()
11846     */
11847    public void postInvalidateDelayed(long delayMilliseconds) {
11848        // We try only with the AttachInfo because there's no point in invalidating
11849        // if we are not attached to our window
11850        final AttachInfo attachInfo = mAttachInfo;
11851        if (attachInfo != null) {
11852            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11853        }
11854    }
11855
11856    /**
11857     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11858     * through the event loop. Waits for the specified amount of time.</p>
11859     *
11860     * <p>This method can be invoked from outside of the UI thread
11861     * only when this View is attached to a window.</p>
11862     *
11863     * @param delayMilliseconds the duration in milliseconds to delay the
11864     *         invalidation by
11865     * @param left The left coordinate of the rectangle to invalidate.
11866     * @param top The top coordinate of the rectangle to invalidate.
11867     * @param right The right coordinate of the rectangle to invalidate.
11868     * @param bottom The bottom coordinate of the rectangle to invalidate.
11869     *
11870     * @see #invalidate(int, int, int, int)
11871     * @see #invalidate(Rect)
11872     * @see #postInvalidate(int, int, int, int)
11873     */
11874    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11875            int right, int bottom) {
11876
11877        // We try only with the AttachInfo because there's no point in invalidating
11878        // if we are not attached to our window
11879        final AttachInfo attachInfo = mAttachInfo;
11880        if (attachInfo != null) {
11881            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11882            info.target = this;
11883            info.left = left;
11884            info.top = top;
11885            info.right = right;
11886            info.bottom = bottom;
11887
11888            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11889        }
11890    }
11891
11892    /**
11893     * <p>Cause an invalidate to happen on the next animation time step, typically the
11894     * next display frame.</p>
11895     *
11896     * <p>This method can be invoked from outside of the UI thread
11897     * only when this View is attached to a window.</p>
11898     *
11899     * @see #invalidate()
11900     */
11901    public void postInvalidateOnAnimation() {
11902        // We try only with the AttachInfo because there's no point in invalidating
11903        // if we are not attached to our window
11904        final AttachInfo attachInfo = mAttachInfo;
11905        if (attachInfo != null) {
11906            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11907        }
11908    }
11909
11910    /**
11911     * <p>Cause an invalidate of the specified area to happen on the next animation
11912     * time step, typically the next display frame.</p>
11913     *
11914     * <p>This method can be invoked from outside of the UI thread
11915     * only when this View is attached to a window.</p>
11916     *
11917     * @param left The left coordinate of the rectangle to invalidate.
11918     * @param top The top coordinate of the rectangle to invalidate.
11919     * @param right The right coordinate of the rectangle to invalidate.
11920     * @param bottom The bottom coordinate of the rectangle to invalidate.
11921     *
11922     * @see #invalidate(int, int, int, int)
11923     * @see #invalidate(Rect)
11924     */
11925    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11926        // We try only with the AttachInfo because there's no point in invalidating
11927        // if we are not attached to our window
11928        final AttachInfo attachInfo = mAttachInfo;
11929        if (attachInfo != null) {
11930            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11931            info.target = this;
11932            info.left = left;
11933            info.top = top;
11934            info.right = right;
11935            info.bottom = bottom;
11936
11937            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11938        }
11939    }
11940
11941    /**
11942     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11943     * This event is sent at most once every
11944     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11945     */
11946    private void postSendViewScrolledAccessibilityEventCallback() {
11947        if (mSendViewScrolledAccessibilityEvent == null) {
11948            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11949        }
11950        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11951            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11952            postDelayed(mSendViewScrolledAccessibilityEvent,
11953                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11954        }
11955    }
11956
11957    /**
11958     * Called by a parent to request that a child update its values for mScrollX
11959     * and mScrollY if necessary. This will typically be done if the child is
11960     * animating a scroll using a {@link android.widget.Scroller Scroller}
11961     * object.
11962     */
11963    public void computeScroll() {
11964    }
11965
11966    /**
11967     * <p>Indicate whether the horizontal edges are faded when the view is
11968     * scrolled horizontally.</p>
11969     *
11970     * @return true if the horizontal edges should are faded on scroll, false
11971     *         otherwise
11972     *
11973     * @see #setHorizontalFadingEdgeEnabled(boolean)
11974     *
11975     * @attr ref android.R.styleable#View_requiresFadingEdge
11976     */
11977    public boolean isHorizontalFadingEdgeEnabled() {
11978        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11979    }
11980
11981    /**
11982     * <p>Define whether the horizontal edges should be faded when this view
11983     * is scrolled horizontally.</p>
11984     *
11985     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11986     *                                    be faded when the view is scrolled
11987     *                                    horizontally
11988     *
11989     * @see #isHorizontalFadingEdgeEnabled()
11990     *
11991     * @attr ref android.R.styleable#View_requiresFadingEdge
11992     */
11993    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11994        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11995            if (horizontalFadingEdgeEnabled) {
11996                initScrollCache();
11997            }
11998
11999            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12000        }
12001    }
12002
12003    /**
12004     * <p>Indicate whether the vertical edges are faded when the view is
12005     * scrolled horizontally.</p>
12006     *
12007     * @return true if the vertical edges should are faded on scroll, false
12008     *         otherwise
12009     *
12010     * @see #setVerticalFadingEdgeEnabled(boolean)
12011     *
12012     * @attr ref android.R.styleable#View_requiresFadingEdge
12013     */
12014    public boolean isVerticalFadingEdgeEnabled() {
12015        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12016    }
12017
12018    /**
12019     * <p>Define whether the vertical edges should be faded when this view
12020     * is scrolled vertically.</p>
12021     *
12022     * @param verticalFadingEdgeEnabled true if the vertical edges should
12023     *                                  be faded when the view is scrolled
12024     *                                  vertically
12025     *
12026     * @see #isVerticalFadingEdgeEnabled()
12027     *
12028     * @attr ref android.R.styleable#View_requiresFadingEdge
12029     */
12030    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12031        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12032            if (verticalFadingEdgeEnabled) {
12033                initScrollCache();
12034            }
12035
12036            mViewFlags ^= FADING_EDGE_VERTICAL;
12037        }
12038    }
12039
12040    /**
12041     * Returns the strength, or intensity, of the top faded edge. The strength is
12042     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12043     * returns 0.0 or 1.0 but no value in between.
12044     *
12045     * Subclasses should override this method to provide a smoother fade transition
12046     * when scrolling occurs.
12047     *
12048     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12049     */
12050    protected float getTopFadingEdgeStrength() {
12051        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12052    }
12053
12054    /**
12055     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12056     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12057     * returns 0.0 or 1.0 but no value in between.
12058     *
12059     * Subclasses should override this method to provide a smoother fade transition
12060     * when scrolling occurs.
12061     *
12062     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12063     */
12064    protected float getBottomFadingEdgeStrength() {
12065        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12066                computeVerticalScrollRange() ? 1.0f : 0.0f;
12067    }
12068
12069    /**
12070     * Returns the strength, or intensity, of the left faded edge. The strength is
12071     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12072     * returns 0.0 or 1.0 but no value in between.
12073     *
12074     * Subclasses should override this method to provide a smoother fade transition
12075     * when scrolling occurs.
12076     *
12077     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12078     */
12079    protected float getLeftFadingEdgeStrength() {
12080        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12081    }
12082
12083    /**
12084     * Returns the strength, or intensity, of the right faded edge. The strength is
12085     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12086     * returns 0.0 or 1.0 but no value in between.
12087     *
12088     * Subclasses should override this method to provide a smoother fade transition
12089     * when scrolling occurs.
12090     *
12091     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12092     */
12093    protected float getRightFadingEdgeStrength() {
12094        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12095                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12096    }
12097
12098    /**
12099     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12100     * scrollbar is not drawn by default.</p>
12101     *
12102     * @return true if the horizontal scrollbar should be painted, false
12103     *         otherwise
12104     *
12105     * @see #setHorizontalScrollBarEnabled(boolean)
12106     */
12107    public boolean isHorizontalScrollBarEnabled() {
12108        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12109    }
12110
12111    /**
12112     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12113     * scrollbar is not drawn by default.</p>
12114     *
12115     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12116     *                                   be painted
12117     *
12118     * @see #isHorizontalScrollBarEnabled()
12119     */
12120    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12121        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12122            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12123            computeOpaqueFlags();
12124            resolvePadding();
12125        }
12126    }
12127
12128    /**
12129     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12130     * scrollbar is not drawn by default.</p>
12131     *
12132     * @return true if the vertical scrollbar should be painted, false
12133     *         otherwise
12134     *
12135     * @see #setVerticalScrollBarEnabled(boolean)
12136     */
12137    public boolean isVerticalScrollBarEnabled() {
12138        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12139    }
12140
12141    /**
12142     * <p>Define whether the vertical scrollbar should be drawn or not. The
12143     * scrollbar is not drawn by default.</p>
12144     *
12145     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12146     *                                 be painted
12147     *
12148     * @see #isVerticalScrollBarEnabled()
12149     */
12150    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12151        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12152            mViewFlags ^= SCROLLBARS_VERTICAL;
12153            computeOpaqueFlags();
12154            resolvePadding();
12155        }
12156    }
12157
12158    /**
12159     * @hide
12160     */
12161    protected void recomputePadding() {
12162        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12163    }
12164
12165    /**
12166     * Define whether scrollbars will fade when the view is not scrolling.
12167     *
12168     * @param fadeScrollbars wheter to enable fading
12169     *
12170     * @attr ref android.R.styleable#View_fadeScrollbars
12171     */
12172    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12173        initScrollCache();
12174        final ScrollabilityCache scrollabilityCache = mScrollCache;
12175        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12176        if (fadeScrollbars) {
12177            scrollabilityCache.state = ScrollabilityCache.OFF;
12178        } else {
12179            scrollabilityCache.state = ScrollabilityCache.ON;
12180        }
12181    }
12182
12183    /**
12184     *
12185     * Returns true if scrollbars will fade when this view is not scrolling
12186     *
12187     * @return true if scrollbar fading is enabled
12188     *
12189     * @attr ref android.R.styleable#View_fadeScrollbars
12190     */
12191    public boolean isScrollbarFadingEnabled() {
12192        return mScrollCache != null && mScrollCache.fadeScrollBars;
12193    }
12194
12195    /**
12196     *
12197     * Returns the delay before scrollbars fade.
12198     *
12199     * @return the delay before scrollbars fade
12200     *
12201     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12202     */
12203    public int getScrollBarDefaultDelayBeforeFade() {
12204        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12205                mScrollCache.scrollBarDefaultDelayBeforeFade;
12206    }
12207
12208    /**
12209     * Define the delay before scrollbars fade.
12210     *
12211     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12212     *
12213     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12214     */
12215    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12216        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12217    }
12218
12219    /**
12220     *
12221     * Returns the scrollbar fade duration.
12222     *
12223     * @return the scrollbar fade duration
12224     *
12225     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12226     */
12227    public int getScrollBarFadeDuration() {
12228        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12229                mScrollCache.scrollBarFadeDuration;
12230    }
12231
12232    /**
12233     * Define the scrollbar fade duration.
12234     *
12235     * @param scrollBarFadeDuration - the scrollbar fade duration
12236     *
12237     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12238     */
12239    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12240        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12241    }
12242
12243    /**
12244     *
12245     * Returns the scrollbar size.
12246     *
12247     * @return the scrollbar size
12248     *
12249     * @attr ref android.R.styleable#View_scrollbarSize
12250     */
12251    public int getScrollBarSize() {
12252        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12253                mScrollCache.scrollBarSize;
12254    }
12255
12256    /**
12257     * Define the scrollbar size.
12258     *
12259     * @param scrollBarSize - the scrollbar size
12260     *
12261     * @attr ref android.R.styleable#View_scrollbarSize
12262     */
12263    public void setScrollBarSize(int scrollBarSize) {
12264        getScrollCache().scrollBarSize = scrollBarSize;
12265    }
12266
12267    /**
12268     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12269     * inset. When inset, they add to the padding of the view. And the scrollbars
12270     * can be drawn inside the padding area or on the edge of the view. For example,
12271     * if a view has a background drawable and you want to draw the scrollbars
12272     * inside the padding specified by the drawable, you can use
12273     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12274     * appear at the edge of the view, ignoring the padding, then you can use
12275     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12276     * @param style the style of the scrollbars. Should be one of
12277     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12278     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12279     * @see #SCROLLBARS_INSIDE_OVERLAY
12280     * @see #SCROLLBARS_INSIDE_INSET
12281     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12282     * @see #SCROLLBARS_OUTSIDE_INSET
12283     *
12284     * @attr ref android.R.styleable#View_scrollbarStyle
12285     */
12286    public void setScrollBarStyle(@ScrollBarStyle int style) {
12287        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12288            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12289            computeOpaqueFlags();
12290            resolvePadding();
12291        }
12292    }
12293
12294    /**
12295     * <p>Returns the current scrollbar style.</p>
12296     * @return the current scrollbar style
12297     * @see #SCROLLBARS_INSIDE_OVERLAY
12298     * @see #SCROLLBARS_INSIDE_INSET
12299     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12300     * @see #SCROLLBARS_OUTSIDE_INSET
12301     *
12302     * @attr ref android.R.styleable#View_scrollbarStyle
12303     */
12304    @ViewDebug.ExportedProperty(mapping = {
12305            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12306            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12307            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12308            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12309    })
12310    @ScrollBarStyle
12311    public int getScrollBarStyle() {
12312        return mViewFlags & SCROLLBARS_STYLE_MASK;
12313    }
12314
12315    /**
12316     * <p>Compute the horizontal range that the horizontal scrollbar
12317     * represents.</p>
12318     *
12319     * <p>The range is expressed in arbitrary units that must be the same as the
12320     * units used by {@link #computeHorizontalScrollExtent()} and
12321     * {@link #computeHorizontalScrollOffset()}.</p>
12322     *
12323     * <p>The default range is the drawing width of this view.</p>
12324     *
12325     * @return the total horizontal range represented by the horizontal
12326     *         scrollbar
12327     *
12328     * @see #computeHorizontalScrollExtent()
12329     * @see #computeHorizontalScrollOffset()
12330     * @see android.widget.ScrollBarDrawable
12331     */
12332    protected int computeHorizontalScrollRange() {
12333        return getWidth();
12334    }
12335
12336    /**
12337     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12338     * within the horizontal range. This value is used to compute the position
12339     * of the thumb within the scrollbar's track.</p>
12340     *
12341     * <p>The range is expressed in arbitrary units that must be the same as the
12342     * units used by {@link #computeHorizontalScrollRange()} and
12343     * {@link #computeHorizontalScrollExtent()}.</p>
12344     *
12345     * <p>The default offset is the scroll offset of this view.</p>
12346     *
12347     * @return the horizontal offset of the scrollbar's thumb
12348     *
12349     * @see #computeHorizontalScrollRange()
12350     * @see #computeHorizontalScrollExtent()
12351     * @see android.widget.ScrollBarDrawable
12352     */
12353    protected int computeHorizontalScrollOffset() {
12354        return mScrollX;
12355    }
12356
12357    /**
12358     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12359     * within the horizontal range. This value is used to compute the length
12360     * of the thumb within the scrollbar's track.</p>
12361     *
12362     * <p>The range is expressed in arbitrary units that must be the same as the
12363     * units used by {@link #computeHorizontalScrollRange()} and
12364     * {@link #computeHorizontalScrollOffset()}.</p>
12365     *
12366     * <p>The default extent is the drawing width of this view.</p>
12367     *
12368     * @return the horizontal extent of the scrollbar's thumb
12369     *
12370     * @see #computeHorizontalScrollRange()
12371     * @see #computeHorizontalScrollOffset()
12372     * @see android.widget.ScrollBarDrawable
12373     */
12374    protected int computeHorizontalScrollExtent() {
12375        return getWidth();
12376    }
12377
12378    /**
12379     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12380     *
12381     * <p>The range is expressed in arbitrary units that must be the same as the
12382     * units used by {@link #computeVerticalScrollExtent()} and
12383     * {@link #computeVerticalScrollOffset()}.</p>
12384     *
12385     * @return the total vertical range represented by the vertical scrollbar
12386     *
12387     * <p>The default range is the drawing height of this view.</p>
12388     *
12389     * @see #computeVerticalScrollExtent()
12390     * @see #computeVerticalScrollOffset()
12391     * @see android.widget.ScrollBarDrawable
12392     */
12393    protected int computeVerticalScrollRange() {
12394        return getHeight();
12395    }
12396
12397    /**
12398     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12399     * within the horizontal range. This value is used to compute the position
12400     * of the thumb within the scrollbar's track.</p>
12401     *
12402     * <p>The range is expressed in arbitrary units that must be the same as the
12403     * units used by {@link #computeVerticalScrollRange()} and
12404     * {@link #computeVerticalScrollExtent()}.</p>
12405     *
12406     * <p>The default offset is the scroll offset of this view.</p>
12407     *
12408     * @return the vertical offset of the scrollbar's thumb
12409     *
12410     * @see #computeVerticalScrollRange()
12411     * @see #computeVerticalScrollExtent()
12412     * @see android.widget.ScrollBarDrawable
12413     */
12414    protected int computeVerticalScrollOffset() {
12415        return mScrollY;
12416    }
12417
12418    /**
12419     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12420     * within the vertical range. This value is used to compute the length
12421     * of the thumb within the scrollbar's track.</p>
12422     *
12423     * <p>The range is expressed in arbitrary units that must be the same as the
12424     * units used by {@link #computeVerticalScrollRange()} and
12425     * {@link #computeVerticalScrollOffset()}.</p>
12426     *
12427     * <p>The default extent is the drawing height of this view.</p>
12428     *
12429     * @return the vertical extent of the scrollbar's thumb
12430     *
12431     * @see #computeVerticalScrollRange()
12432     * @see #computeVerticalScrollOffset()
12433     * @see android.widget.ScrollBarDrawable
12434     */
12435    protected int computeVerticalScrollExtent() {
12436        return getHeight();
12437    }
12438
12439    /**
12440     * Check if this view can be scrolled horizontally in a certain direction.
12441     *
12442     * @param direction Negative to check scrolling left, positive to check scrolling right.
12443     * @return true if this view can be scrolled in the specified direction, false otherwise.
12444     */
12445    public boolean canScrollHorizontally(int direction) {
12446        final int offset = computeHorizontalScrollOffset();
12447        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12448        if (range == 0) return false;
12449        if (direction < 0) {
12450            return offset > 0;
12451        } else {
12452            return offset < range - 1;
12453        }
12454    }
12455
12456    /**
12457     * Check if this view can be scrolled vertically in a certain direction.
12458     *
12459     * @param direction Negative to check scrolling up, positive to check scrolling down.
12460     * @return true if this view can be scrolled in the specified direction, false otherwise.
12461     */
12462    public boolean canScrollVertically(int direction) {
12463        final int offset = computeVerticalScrollOffset();
12464        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12465        if (range == 0) return false;
12466        if (direction < 0) {
12467            return offset > 0;
12468        } else {
12469            return offset < range - 1;
12470        }
12471    }
12472
12473    /**
12474     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12475     * scrollbars are painted only if they have been awakened first.</p>
12476     *
12477     * @param canvas the canvas on which to draw the scrollbars
12478     *
12479     * @see #awakenScrollBars(int)
12480     */
12481    protected final void onDrawScrollBars(Canvas canvas) {
12482        // scrollbars are drawn only when the animation is running
12483        final ScrollabilityCache cache = mScrollCache;
12484        if (cache != null) {
12485
12486            int state = cache.state;
12487
12488            if (state == ScrollabilityCache.OFF) {
12489                return;
12490            }
12491
12492            boolean invalidate = false;
12493
12494            if (state == ScrollabilityCache.FADING) {
12495                // We're fading -- get our fade interpolation
12496                if (cache.interpolatorValues == null) {
12497                    cache.interpolatorValues = new float[1];
12498                }
12499
12500                float[] values = cache.interpolatorValues;
12501
12502                // Stops the animation if we're done
12503                if (cache.scrollBarInterpolator.timeToValues(values) ==
12504                        Interpolator.Result.FREEZE_END) {
12505                    cache.state = ScrollabilityCache.OFF;
12506                } else {
12507                    cache.scrollBar.setAlpha(Math.round(values[0]));
12508                }
12509
12510                // This will make the scroll bars inval themselves after
12511                // drawing. We only want this when we're fading so that
12512                // we prevent excessive redraws
12513                invalidate = true;
12514            } else {
12515                // We're just on -- but we may have been fading before so
12516                // reset alpha
12517                cache.scrollBar.setAlpha(255);
12518            }
12519
12520
12521            final int viewFlags = mViewFlags;
12522
12523            final boolean drawHorizontalScrollBar =
12524                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12525            final boolean drawVerticalScrollBar =
12526                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12527                && !isVerticalScrollBarHidden();
12528
12529            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12530                final int width = mRight - mLeft;
12531                final int height = mBottom - mTop;
12532
12533                final ScrollBarDrawable scrollBar = cache.scrollBar;
12534
12535                final int scrollX = mScrollX;
12536                final int scrollY = mScrollY;
12537                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12538
12539                int left;
12540                int top;
12541                int right;
12542                int bottom;
12543
12544                if (drawHorizontalScrollBar) {
12545                    int size = scrollBar.getSize(false);
12546                    if (size <= 0) {
12547                        size = cache.scrollBarSize;
12548                    }
12549
12550                    scrollBar.setParameters(computeHorizontalScrollRange(),
12551                                            computeHorizontalScrollOffset(),
12552                                            computeHorizontalScrollExtent(), false);
12553                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12554                            getVerticalScrollbarWidth() : 0;
12555                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12556                    left = scrollX + (mPaddingLeft & inside);
12557                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12558                    bottom = top + size;
12559                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12560                    if (invalidate) {
12561                        invalidate(left, top, right, bottom);
12562                    }
12563                }
12564
12565                if (drawVerticalScrollBar) {
12566                    int size = scrollBar.getSize(true);
12567                    if (size <= 0) {
12568                        size = cache.scrollBarSize;
12569                    }
12570
12571                    scrollBar.setParameters(computeVerticalScrollRange(),
12572                                            computeVerticalScrollOffset(),
12573                                            computeVerticalScrollExtent(), true);
12574                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12575                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12576                        verticalScrollbarPosition = isLayoutRtl() ?
12577                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12578                    }
12579                    switch (verticalScrollbarPosition) {
12580                        default:
12581                        case SCROLLBAR_POSITION_RIGHT:
12582                            left = scrollX + width - size - (mUserPaddingRight & inside);
12583                            break;
12584                        case SCROLLBAR_POSITION_LEFT:
12585                            left = scrollX + (mUserPaddingLeft & inside);
12586                            break;
12587                    }
12588                    top = scrollY + (mPaddingTop & inside);
12589                    right = left + size;
12590                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12591                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12592                    if (invalidate) {
12593                        invalidate(left, top, right, bottom);
12594                    }
12595                }
12596            }
12597        }
12598    }
12599
12600    /**
12601     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12602     * FastScroller is visible.
12603     * @return whether to temporarily hide the vertical scrollbar
12604     * @hide
12605     */
12606    protected boolean isVerticalScrollBarHidden() {
12607        return false;
12608    }
12609
12610    /**
12611     * <p>Draw the horizontal scrollbar if
12612     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12613     *
12614     * @param canvas the canvas on which to draw the scrollbar
12615     * @param scrollBar the scrollbar's drawable
12616     *
12617     * @see #isHorizontalScrollBarEnabled()
12618     * @see #computeHorizontalScrollRange()
12619     * @see #computeHorizontalScrollExtent()
12620     * @see #computeHorizontalScrollOffset()
12621     * @see android.widget.ScrollBarDrawable
12622     * @hide
12623     */
12624    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12625            int l, int t, int r, int b) {
12626        scrollBar.setBounds(l, t, r, b);
12627        scrollBar.draw(canvas);
12628    }
12629
12630    /**
12631     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12632     * returns true.</p>
12633     *
12634     * @param canvas the canvas on which to draw the scrollbar
12635     * @param scrollBar the scrollbar's drawable
12636     *
12637     * @see #isVerticalScrollBarEnabled()
12638     * @see #computeVerticalScrollRange()
12639     * @see #computeVerticalScrollExtent()
12640     * @see #computeVerticalScrollOffset()
12641     * @see android.widget.ScrollBarDrawable
12642     * @hide
12643     */
12644    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12645            int l, int t, int r, int b) {
12646        scrollBar.setBounds(l, t, r, b);
12647        scrollBar.draw(canvas);
12648    }
12649
12650    /**
12651     * Implement this to do your drawing.
12652     *
12653     * @param canvas the canvas on which the background will be drawn
12654     */
12655    protected void onDraw(Canvas canvas) {
12656    }
12657
12658    /*
12659     * Caller is responsible for calling requestLayout if necessary.
12660     * (This allows addViewInLayout to not request a new layout.)
12661     */
12662    void assignParent(ViewParent parent) {
12663        if (mParent == null) {
12664            mParent = parent;
12665        } else if (parent == null) {
12666            mParent = null;
12667        } else {
12668            throw new RuntimeException("view " + this + " being added, but"
12669                    + " it already has a parent");
12670        }
12671    }
12672
12673    /**
12674     * This is called when the view is attached to a window.  At this point it
12675     * has a Surface and will start drawing.  Note that this function is
12676     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12677     * however it may be called any time before the first onDraw -- including
12678     * before or after {@link #onMeasure(int, int)}.
12679     *
12680     * @see #onDetachedFromWindow()
12681     */
12682    protected void onAttachedToWindow() {
12683        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12684            mParent.requestTransparentRegion(this);
12685        }
12686
12687        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12688            initialAwakenScrollBars();
12689            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12690        }
12691
12692        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12693
12694        jumpDrawablesToCurrentState();
12695
12696        resetSubtreeAccessibilityStateChanged();
12697
12698        invalidateOutline();
12699
12700        if (isFocused()) {
12701            InputMethodManager imm = InputMethodManager.peekInstance();
12702            imm.focusIn(this);
12703        }
12704    }
12705
12706    /**
12707     * Resolve all RTL related properties.
12708     *
12709     * @return true if resolution of RTL properties has been done
12710     *
12711     * @hide
12712     */
12713    public boolean resolveRtlPropertiesIfNeeded() {
12714        if (!needRtlPropertiesResolution()) return false;
12715
12716        // Order is important here: LayoutDirection MUST be resolved first
12717        if (!isLayoutDirectionResolved()) {
12718            resolveLayoutDirection();
12719            resolveLayoutParams();
12720        }
12721        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12722        if (!isTextDirectionResolved()) {
12723            resolveTextDirection();
12724        }
12725        if (!isTextAlignmentResolved()) {
12726            resolveTextAlignment();
12727        }
12728        // Should resolve Drawables before Padding because we need the layout direction of the
12729        // Drawable to correctly resolve Padding.
12730        if (!isDrawablesResolved()) {
12731            resolveDrawables();
12732        }
12733        if (!isPaddingResolved()) {
12734            resolvePadding();
12735        }
12736        onRtlPropertiesChanged(getLayoutDirection());
12737        return true;
12738    }
12739
12740    /**
12741     * Reset resolution of all RTL related properties.
12742     *
12743     * @hide
12744     */
12745    public void resetRtlProperties() {
12746        resetResolvedLayoutDirection();
12747        resetResolvedTextDirection();
12748        resetResolvedTextAlignment();
12749        resetResolvedPadding();
12750        resetResolvedDrawables();
12751    }
12752
12753    /**
12754     * @see #onScreenStateChanged(int)
12755     */
12756    void dispatchScreenStateChanged(int screenState) {
12757        onScreenStateChanged(screenState);
12758    }
12759
12760    /**
12761     * This method is called whenever the state of the screen this view is
12762     * attached to changes. A state change will usually occurs when the screen
12763     * turns on or off (whether it happens automatically or the user does it
12764     * manually.)
12765     *
12766     * @param screenState The new state of the screen. Can be either
12767     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12768     */
12769    public void onScreenStateChanged(int screenState) {
12770    }
12771
12772    /**
12773     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12774     */
12775    private boolean hasRtlSupport() {
12776        return mContext.getApplicationInfo().hasRtlSupport();
12777    }
12778
12779    /**
12780     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12781     * RTL not supported)
12782     */
12783    private boolean isRtlCompatibilityMode() {
12784        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12785        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12786    }
12787
12788    /**
12789     * @return true if RTL properties need resolution.
12790     *
12791     */
12792    private boolean needRtlPropertiesResolution() {
12793        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12794    }
12795
12796    /**
12797     * Called when any RTL property (layout direction or text direction or text alignment) has
12798     * been changed.
12799     *
12800     * Subclasses need to override this method to take care of cached information that depends on the
12801     * resolved layout direction, or to inform child views that inherit their layout direction.
12802     *
12803     * The default implementation does nothing.
12804     *
12805     * @param layoutDirection the direction of the layout
12806     *
12807     * @see #LAYOUT_DIRECTION_LTR
12808     * @see #LAYOUT_DIRECTION_RTL
12809     */
12810    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12811    }
12812
12813    /**
12814     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12815     * that the parent directionality can and will be resolved before its children.
12816     *
12817     * @return true if resolution has been done, false otherwise.
12818     *
12819     * @hide
12820     */
12821    public boolean resolveLayoutDirection() {
12822        // Clear any previous layout direction resolution
12823        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12824
12825        if (hasRtlSupport()) {
12826            // Set resolved depending on layout direction
12827            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12828                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12829                case LAYOUT_DIRECTION_INHERIT:
12830                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12831                    // later to get the correct resolved value
12832                    if (!canResolveLayoutDirection()) return false;
12833
12834                    // Parent has not yet resolved, LTR is still the default
12835                    try {
12836                        if (!mParent.isLayoutDirectionResolved()) return false;
12837
12838                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12839                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12840                        }
12841                    } catch (AbstractMethodError e) {
12842                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12843                                " does not fully implement ViewParent", e);
12844                    }
12845                    break;
12846                case LAYOUT_DIRECTION_RTL:
12847                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12848                    break;
12849                case LAYOUT_DIRECTION_LOCALE:
12850                    if((LAYOUT_DIRECTION_RTL ==
12851                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12852                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12853                    }
12854                    break;
12855                default:
12856                    // Nothing to do, LTR by default
12857            }
12858        }
12859
12860        // Set to resolved
12861        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12862        return true;
12863    }
12864
12865    /**
12866     * Check if layout direction resolution can be done.
12867     *
12868     * @return true if layout direction resolution can be done otherwise return false.
12869     */
12870    public boolean canResolveLayoutDirection() {
12871        switch (getRawLayoutDirection()) {
12872            case LAYOUT_DIRECTION_INHERIT:
12873                if (mParent != null) {
12874                    try {
12875                        return mParent.canResolveLayoutDirection();
12876                    } catch (AbstractMethodError e) {
12877                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12878                                " does not fully implement ViewParent", e);
12879                    }
12880                }
12881                return false;
12882
12883            default:
12884                return true;
12885        }
12886    }
12887
12888    /**
12889     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12890     * {@link #onMeasure(int, int)}.
12891     *
12892     * @hide
12893     */
12894    public void resetResolvedLayoutDirection() {
12895        // Reset the current resolved bits
12896        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12897    }
12898
12899    /**
12900     * @return true if the layout direction is inherited.
12901     *
12902     * @hide
12903     */
12904    public boolean isLayoutDirectionInherited() {
12905        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12906    }
12907
12908    /**
12909     * @return true if layout direction has been resolved.
12910     */
12911    public boolean isLayoutDirectionResolved() {
12912        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12913    }
12914
12915    /**
12916     * Return if padding has been resolved
12917     *
12918     * @hide
12919     */
12920    boolean isPaddingResolved() {
12921        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12922    }
12923
12924    /**
12925     * Resolves padding depending on layout direction, if applicable, and
12926     * recomputes internal padding values to adjust for scroll bars.
12927     *
12928     * @hide
12929     */
12930    public void resolvePadding() {
12931        final int resolvedLayoutDirection = getLayoutDirection();
12932
12933        if (!isRtlCompatibilityMode()) {
12934            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12935            // If start / end padding are defined, they will be resolved (hence overriding) to
12936            // left / right or right / left depending on the resolved layout direction.
12937            // If start / end padding are not defined, use the left / right ones.
12938            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12939                Rect padding = sThreadLocal.get();
12940                if (padding == null) {
12941                    padding = new Rect();
12942                    sThreadLocal.set(padding);
12943                }
12944                mBackground.getPadding(padding);
12945                if (!mLeftPaddingDefined) {
12946                    mUserPaddingLeftInitial = padding.left;
12947                }
12948                if (!mRightPaddingDefined) {
12949                    mUserPaddingRightInitial = padding.right;
12950                }
12951            }
12952            switch (resolvedLayoutDirection) {
12953                case LAYOUT_DIRECTION_RTL:
12954                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12955                        mUserPaddingRight = mUserPaddingStart;
12956                    } else {
12957                        mUserPaddingRight = mUserPaddingRightInitial;
12958                    }
12959                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12960                        mUserPaddingLeft = mUserPaddingEnd;
12961                    } else {
12962                        mUserPaddingLeft = mUserPaddingLeftInitial;
12963                    }
12964                    break;
12965                case LAYOUT_DIRECTION_LTR:
12966                default:
12967                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12968                        mUserPaddingLeft = mUserPaddingStart;
12969                    } else {
12970                        mUserPaddingLeft = mUserPaddingLeftInitial;
12971                    }
12972                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12973                        mUserPaddingRight = mUserPaddingEnd;
12974                    } else {
12975                        mUserPaddingRight = mUserPaddingRightInitial;
12976                    }
12977            }
12978
12979            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12980        }
12981
12982        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12983        onRtlPropertiesChanged(resolvedLayoutDirection);
12984
12985        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12986    }
12987
12988    /**
12989     * Reset the resolved layout direction.
12990     *
12991     * @hide
12992     */
12993    public void resetResolvedPadding() {
12994        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12995    }
12996
12997    /**
12998     * This is called when the view is detached from a window.  At this point it
12999     * no longer has a surface for drawing.
13000     *
13001     * @see #onAttachedToWindow()
13002     */
13003    protected void onDetachedFromWindow() {
13004    }
13005
13006    /**
13007     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13008     * after onDetachedFromWindow().
13009     *
13010     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13011     * The super method should be called at the end of the overriden method to ensure
13012     * subclasses are destroyed first
13013     *
13014     * @hide
13015     */
13016    protected void onDetachedFromWindowInternal() {
13017        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13018        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13019
13020        removeUnsetPressCallback();
13021        removeLongPressCallback();
13022        removePerformClickCallback();
13023        removeSendViewScrolledAccessibilityEventCallback();
13024        stopNestedScroll();
13025
13026        destroyDrawingCache();
13027
13028        cleanupDraw();
13029        mCurrentAnimation = null;
13030    }
13031
13032    private void cleanupDraw() {
13033        resetDisplayList();
13034        if (mAttachInfo != null) {
13035            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13036        }
13037    }
13038
13039    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13040    }
13041
13042    /**
13043     * @return The number of times this view has been attached to a window
13044     */
13045    protected int getWindowAttachCount() {
13046        return mWindowAttachCount;
13047    }
13048
13049    /**
13050     * Retrieve a unique token identifying the window this view is attached to.
13051     * @return Return the window's token for use in
13052     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13053     */
13054    public IBinder getWindowToken() {
13055        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13056    }
13057
13058    /**
13059     * Retrieve the {@link WindowId} for the window this view is
13060     * currently attached to.
13061     */
13062    public WindowId getWindowId() {
13063        if (mAttachInfo == null) {
13064            return null;
13065        }
13066        if (mAttachInfo.mWindowId == null) {
13067            try {
13068                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13069                        mAttachInfo.mWindowToken);
13070                mAttachInfo.mWindowId = new WindowId(
13071                        mAttachInfo.mIWindowId);
13072            } catch (RemoteException e) {
13073            }
13074        }
13075        return mAttachInfo.mWindowId;
13076    }
13077
13078    /**
13079     * Retrieve a unique token identifying the top-level "real" window of
13080     * the window that this view is attached to.  That is, this is like
13081     * {@link #getWindowToken}, except if the window this view in is a panel
13082     * window (attached to another containing window), then the token of
13083     * the containing window is returned instead.
13084     *
13085     * @return Returns the associated window token, either
13086     * {@link #getWindowToken()} or the containing window's token.
13087     */
13088    public IBinder getApplicationWindowToken() {
13089        AttachInfo ai = mAttachInfo;
13090        if (ai != null) {
13091            IBinder appWindowToken = ai.mPanelParentWindowToken;
13092            if (appWindowToken == null) {
13093                appWindowToken = ai.mWindowToken;
13094            }
13095            return appWindowToken;
13096        }
13097        return null;
13098    }
13099
13100    /**
13101     * Gets the logical display to which the view's window has been attached.
13102     *
13103     * @return The logical display, or null if the view is not currently attached to a window.
13104     */
13105    public Display getDisplay() {
13106        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13107    }
13108
13109    /**
13110     * Retrieve private session object this view hierarchy is using to
13111     * communicate with the window manager.
13112     * @return the session object to communicate with the window manager
13113     */
13114    /*package*/ IWindowSession getWindowSession() {
13115        return mAttachInfo != null ? mAttachInfo.mSession : null;
13116    }
13117
13118    /**
13119     * @param info the {@link android.view.View.AttachInfo} to associated with
13120     *        this view
13121     */
13122    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13123        //System.out.println("Attached! " + this);
13124        mAttachInfo = info;
13125        if (mOverlay != null) {
13126            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13127        }
13128        mWindowAttachCount++;
13129        // We will need to evaluate the drawable state at least once.
13130        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13131        if (mFloatingTreeObserver != null) {
13132            info.mTreeObserver.merge(mFloatingTreeObserver);
13133            mFloatingTreeObserver = null;
13134        }
13135        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13136            mAttachInfo.mScrollContainers.add(this);
13137            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13138        }
13139        performCollectViewAttributes(mAttachInfo, visibility);
13140        onAttachedToWindow();
13141
13142        ListenerInfo li = mListenerInfo;
13143        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13144                li != null ? li.mOnAttachStateChangeListeners : null;
13145        if (listeners != null && listeners.size() > 0) {
13146            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13147            // perform the dispatching. The iterator is a safe guard against listeners that
13148            // could mutate the list by calling the various add/remove methods. This prevents
13149            // the array from being modified while we iterate it.
13150            for (OnAttachStateChangeListener listener : listeners) {
13151                listener.onViewAttachedToWindow(this);
13152            }
13153        }
13154
13155        int vis = info.mWindowVisibility;
13156        if (vis != GONE) {
13157            onWindowVisibilityChanged(vis);
13158        }
13159        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13160            // If nobody has evaluated the drawable state yet, then do it now.
13161            refreshDrawableState();
13162        }
13163        needGlobalAttributesUpdate(false);
13164    }
13165
13166    void dispatchDetachedFromWindow() {
13167        AttachInfo info = mAttachInfo;
13168        if (info != null) {
13169            int vis = info.mWindowVisibility;
13170            if (vis != GONE) {
13171                onWindowVisibilityChanged(GONE);
13172            }
13173        }
13174
13175        onDetachedFromWindow();
13176        onDetachedFromWindowInternal();
13177
13178        ListenerInfo li = mListenerInfo;
13179        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13180                li != null ? li.mOnAttachStateChangeListeners : null;
13181        if (listeners != null && listeners.size() > 0) {
13182            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13183            // perform the dispatching. The iterator is a safe guard against listeners that
13184            // could mutate the list by calling the various add/remove methods. This prevents
13185            // the array from being modified while we iterate it.
13186            for (OnAttachStateChangeListener listener : listeners) {
13187                listener.onViewDetachedFromWindow(this);
13188            }
13189        }
13190
13191        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13192            mAttachInfo.mScrollContainers.remove(this);
13193            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13194        }
13195
13196        mAttachInfo = null;
13197        if (mOverlay != null) {
13198            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13199        }
13200    }
13201
13202    /**
13203     * Cancel any deferred high-level input events that were previously posted to the event queue.
13204     *
13205     * <p>Many views post high-level events such as click handlers to the event queue
13206     * to run deferred in order to preserve a desired user experience - clearing visible
13207     * pressed states before executing, etc. This method will abort any events of this nature
13208     * that are currently in flight.</p>
13209     *
13210     * <p>Custom views that generate their own high-level deferred input events should override
13211     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13212     *
13213     * <p>This will also cancel pending input events for any child views.</p>
13214     *
13215     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13216     * This will not impact newer events posted after this call that may occur as a result of
13217     * lower-level input events still waiting in the queue. If you are trying to prevent
13218     * double-submitted  events for the duration of some sort of asynchronous transaction
13219     * you should also take other steps to protect against unexpected double inputs e.g. calling
13220     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13221     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13222     */
13223    public final void cancelPendingInputEvents() {
13224        dispatchCancelPendingInputEvents();
13225    }
13226
13227    /**
13228     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13229     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13230     */
13231    void dispatchCancelPendingInputEvents() {
13232        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13233        onCancelPendingInputEvents();
13234        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13235            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13236                    " did not call through to super.onCancelPendingInputEvents()");
13237        }
13238    }
13239
13240    /**
13241     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13242     * a parent view.
13243     *
13244     * <p>This method is responsible for removing any pending high-level input events that were
13245     * posted to the event queue to run later. Custom view classes that post their own deferred
13246     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13247     * {@link android.os.Handler} should override this method, call
13248     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13249     * </p>
13250     */
13251    public void onCancelPendingInputEvents() {
13252        removePerformClickCallback();
13253        cancelLongPress();
13254        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13255    }
13256
13257    /**
13258     * Store this view hierarchy's frozen state into the given container.
13259     *
13260     * @param container The SparseArray in which to save the view's state.
13261     *
13262     * @see #restoreHierarchyState(android.util.SparseArray)
13263     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13264     * @see #onSaveInstanceState()
13265     */
13266    public void saveHierarchyState(SparseArray<Parcelable> container) {
13267        dispatchSaveInstanceState(container);
13268    }
13269
13270    /**
13271     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13272     * this view and its children. May be overridden to modify how freezing happens to a
13273     * view's children; for example, some views may want to not store state for their children.
13274     *
13275     * @param container The SparseArray in which to save the view's state.
13276     *
13277     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13278     * @see #saveHierarchyState(android.util.SparseArray)
13279     * @see #onSaveInstanceState()
13280     */
13281    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13282        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13283            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13284            Parcelable state = onSaveInstanceState();
13285            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13286                throw new IllegalStateException(
13287                        "Derived class did not call super.onSaveInstanceState()");
13288            }
13289            if (state != null) {
13290                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13291                // + ": " + state);
13292                container.put(mID, state);
13293            }
13294        }
13295    }
13296
13297    /**
13298     * Hook allowing a view to generate a representation of its internal state
13299     * that can later be used to create a new instance with that same state.
13300     * This state should only contain information that is not persistent or can
13301     * not be reconstructed later. For example, you will never store your
13302     * current position on screen because that will be computed again when a
13303     * new instance of the view is placed in its view hierarchy.
13304     * <p>
13305     * Some examples of things you may store here: the current cursor position
13306     * in a text view (but usually not the text itself since that is stored in a
13307     * content provider or other persistent storage), the currently selected
13308     * item in a list view.
13309     *
13310     * @return Returns a Parcelable object containing the view's current dynamic
13311     *         state, or null if there is nothing interesting to save. The
13312     *         default implementation returns null.
13313     * @see #onRestoreInstanceState(android.os.Parcelable)
13314     * @see #saveHierarchyState(android.util.SparseArray)
13315     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13316     * @see #setSaveEnabled(boolean)
13317     */
13318    protected Parcelable onSaveInstanceState() {
13319        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13320        return BaseSavedState.EMPTY_STATE;
13321    }
13322
13323    /**
13324     * Restore this view hierarchy's frozen state from the given container.
13325     *
13326     * @param container The SparseArray which holds previously frozen states.
13327     *
13328     * @see #saveHierarchyState(android.util.SparseArray)
13329     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13330     * @see #onRestoreInstanceState(android.os.Parcelable)
13331     */
13332    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13333        dispatchRestoreInstanceState(container);
13334    }
13335
13336    /**
13337     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13338     * state for this view and its children. May be overridden to modify how restoring
13339     * happens to a view's children; for example, some views may want to not store state
13340     * for their children.
13341     *
13342     * @param container The SparseArray which holds previously saved state.
13343     *
13344     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13345     * @see #restoreHierarchyState(android.util.SparseArray)
13346     * @see #onRestoreInstanceState(android.os.Parcelable)
13347     */
13348    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13349        if (mID != NO_ID) {
13350            Parcelable state = container.get(mID);
13351            if (state != null) {
13352                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13353                // + ": " + state);
13354                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13355                onRestoreInstanceState(state);
13356                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13357                    throw new IllegalStateException(
13358                            "Derived class did not call super.onRestoreInstanceState()");
13359                }
13360            }
13361        }
13362    }
13363
13364    /**
13365     * Hook allowing a view to re-apply a representation of its internal state that had previously
13366     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13367     * null state.
13368     *
13369     * @param state The frozen state that had previously been returned by
13370     *        {@link #onSaveInstanceState}.
13371     *
13372     * @see #onSaveInstanceState()
13373     * @see #restoreHierarchyState(android.util.SparseArray)
13374     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13375     */
13376    protected void onRestoreInstanceState(Parcelable state) {
13377        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13378        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13379            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13380                    + "received " + state.getClass().toString() + " instead. This usually happens "
13381                    + "when two views of different type have the same id in the same hierarchy. "
13382                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13383                    + "other views do not use the same id.");
13384        }
13385    }
13386
13387    /**
13388     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13389     *
13390     * @return the drawing start time in milliseconds
13391     */
13392    public long getDrawingTime() {
13393        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13394    }
13395
13396    /**
13397     * <p>Enables or disables the duplication of the parent's state into this view. When
13398     * duplication is enabled, this view gets its drawable state from its parent rather
13399     * than from its own internal properties.</p>
13400     *
13401     * <p>Note: in the current implementation, setting this property to true after the
13402     * view was added to a ViewGroup might have no effect at all. This property should
13403     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13404     *
13405     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13406     * property is enabled, an exception will be thrown.</p>
13407     *
13408     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13409     * parent, these states should not be affected by this method.</p>
13410     *
13411     * @param enabled True to enable duplication of the parent's drawable state, false
13412     *                to disable it.
13413     *
13414     * @see #getDrawableState()
13415     * @see #isDuplicateParentStateEnabled()
13416     */
13417    public void setDuplicateParentStateEnabled(boolean enabled) {
13418        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13419    }
13420
13421    /**
13422     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13423     *
13424     * @return True if this view's drawable state is duplicated from the parent,
13425     *         false otherwise
13426     *
13427     * @see #getDrawableState()
13428     * @see #setDuplicateParentStateEnabled(boolean)
13429     */
13430    public boolean isDuplicateParentStateEnabled() {
13431        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13432    }
13433
13434    /**
13435     * <p>Specifies the type of layer backing this view. The layer can be
13436     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13437     * {@link #LAYER_TYPE_HARDWARE}.</p>
13438     *
13439     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13440     * instance that controls how the layer is composed on screen. The following
13441     * properties of the paint are taken into account when composing the layer:</p>
13442     * <ul>
13443     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13444     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13445     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13446     * </ul>
13447     *
13448     * <p>If this view has an alpha value set to < 1.0 by calling
13449     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13450     * by this view's alpha value.</p>
13451     *
13452     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13453     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13454     * for more information on when and how to use layers.</p>
13455     *
13456     * @param layerType The type of layer to use with this view, must be one of
13457     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13458     *        {@link #LAYER_TYPE_HARDWARE}
13459     * @param paint The paint used to compose the layer. This argument is optional
13460     *        and can be null. It is ignored when the layer type is
13461     *        {@link #LAYER_TYPE_NONE}
13462     *
13463     * @see #getLayerType()
13464     * @see #LAYER_TYPE_NONE
13465     * @see #LAYER_TYPE_SOFTWARE
13466     * @see #LAYER_TYPE_HARDWARE
13467     * @see #setAlpha(float)
13468     *
13469     * @attr ref android.R.styleable#View_layerType
13470     */
13471    public void setLayerType(int layerType, Paint paint) {
13472        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13473            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13474                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13475        }
13476
13477        boolean typeChanged = mRenderNode.setLayerType(layerType);
13478
13479        if (!typeChanged) {
13480            setLayerPaint(paint);
13481            return;
13482        }
13483
13484        // Destroy any previous software drawing cache if needed
13485        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13486            destroyDrawingCache();
13487        }
13488
13489        mLayerType = layerType;
13490        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13491        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13492        mRenderNode.setLayerPaint(mLayerPaint);
13493
13494        // draw() behaves differently if we are on a layer, so we need to
13495        // invalidate() here
13496        invalidateParentCaches();
13497        invalidate(true);
13498    }
13499
13500    /**
13501     * Updates the {@link Paint} object used with the current layer (used only if the current
13502     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13503     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13504     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13505     * ensure that the view gets redrawn immediately.
13506     *
13507     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13508     * instance that controls how the layer is composed on screen. The following
13509     * properties of the paint are taken into account when composing the layer:</p>
13510     * <ul>
13511     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13512     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13513     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13514     * </ul>
13515     *
13516     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13517     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13518     *
13519     * @param paint The paint used to compose the layer. This argument is optional
13520     *        and can be null. It is ignored when the layer type is
13521     *        {@link #LAYER_TYPE_NONE}
13522     *
13523     * @see #setLayerType(int, android.graphics.Paint)
13524     */
13525    public void setLayerPaint(Paint paint) {
13526        int layerType = getLayerType();
13527        if (layerType != LAYER_TYPE_NONE) {
13528            mLayerPaint = paint == null ? new Paint() : paint;
13529            if (layerType == LAYER_TYPE_HARDWARE) {
13530                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13531                    invalidateViewProperty(false, false);
13532                }
13533            } else {
13534                invalidate();
13535            }
13536        }
13537    }
13538
13539    /**
13540     * Indicates whether this view has a static layer. A view with layer type
13541     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13542     * dynamic.
13543     */
13544    boolean hasStaticLayer() {
13545        return true;
13546    }
13547
13548    /**
13549     * Indicates what type of layer is currently associated with this view. By default
13550     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13551     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13552     * for more information on the different types of layers.
13553     *
13554     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13555     *         {@link #LAYER_TYPE_HARDWARE}
13556     *
13557     * @see #setLayerType(int, android.graphics.Paint)
13558     * @see #buildLayer()
13559     * @see #LAYER_TYPE_NONE
13560     * @see #LAYER_TYPE_SOFTWARE
13561     * @see #LAYER_TYPE_HARDWARE
13562     */
13563    public int getLayerType() {
13564        return mLayerType;
13565    }
13566
13567    /**
13568     * Forces this view's layer to be created and this view to be rendered
13569     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13570     * invoking this method will have no effect.
13571     *
13572     * This method can for instance be used to render a view into its layer before
13573     * starting an animation. If this view is complex, rendering into the layer
13574     * before starting the animation will avoid skipping frames.
13575     *
13576     * @throws IllegalStateException If this view is not attached to a window
13577     *
13578     * @see #setLayerType(int, android.graphics.Paint)
13579     */
13580    public void buildLayer() {
13581        if (mLayerType == LAYER_TYPE_NONE) return;
13582
13583        final AttachInfo attachInfo = mAttachInfo;
13584        if (attachInfo == null) {
13585            throw new IllegalStateException("This view must be attached to a window first");
13586        }
13587
13588        if (getWidth() == 0 || getHeight() == 0) {
13589            return;
13590        }
13591
13592        switch (mLayerType) {
13593            case LAYER_TYPE_HARDWARE:
13594                // The only part of a hardware layer we can build in response to
13595                // this call is to ensure the display list is up to date.
13596                // The actual rendering of the display list into the layer must
13597                // be done at playback time
13598                updateDisplayListIfDirty();
13599                break;
13600            case LAYER_TYPE_SOFTWARE:
13601                buildDrawingCache(true);
13602                break;
13603        }
13604    }
13605
13606    /**
13607     * If this View draws with a HardwareLayer, returns it.
13608     * Otherwise returns null
13609     *
13610     * TODO: Only TextureView uses this, can we eliminate it?
13611     */
13612    HardwareLayer getHardwareLayer() {
13613        return null;
13614    }
13615
13616    /**
13617     * Destroys all hardware rendering resources. This method is invoked
13618     * when the system needs to reclaim resources. Upon execution of this
13619     * method, you should free any OpenGL resources created by the view.
13620     *
13621     * Note: you <strong>must</strong> call
13622     * <code>super.destroyHardwareResources()</code> when overriding
13623     * this method.
13624     *
13625     * @hide
13626     */
13627    protected void destroyHardwareResources() {
13628        // Although the Layer will be destroyed by RenderNode, we want to release
13629        // the staging display list, which is also a signal to RenderNode that it's
13630        // safe to free its copy of the display list as it knows that we will
13631        // push an updated DisplayList if we try to draw again
13632        resetDisplayList();
13633    }
13634
13635    /**
13636     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13637     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13638     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13639     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13640     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13641     * null.</p>
13642     *
13643     * <p>Enabling the drawing cache is similar to
13644     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13645     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13646     * drawing cache has no effect on rendering because the system uses a different mechanism
13647     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13648     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13649     * for information on how to enable software and hardware layers.</p>
13650     *
13651     * <p>This API can be used to manually generate
13652     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13653     * {@link #getDrawingCache()}.</p>
13654     *
13655     * @param enabled true to enable the drawing cache, false otherwise
13656     *
13657     * @see #isDrawingCacheEnabled()
13658     * @see #getDrawingCache()
13659     * @see #buildDrawingCache()
13660     * @see #setLayerType(int, android.graphics.Paint)
13661     */
13662    public void setDrawingCacheEnabled(boolean enabled) {
13663        mCachingFailed = false;
13664        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13665    }
13666
13667    /**
13668     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13669     *
13670     * @return true if the drawing cache is enabled
13671     *
13672     * @see #setDrawingCacheEnabled(boolean)
13673     * @see #getDrawingCache()
13674     */
13675    @ViewDebug.ExportedProperty(category = "drawing")
13676    public boolean isDrawingCacheEnabled() {
13677        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13678    }
13679
13680    /**
13681     * Debugging utility which recursively outputs the dirty state of a view and its
13682     * descendants.
13683     *
13684     * @hide
13685     */
13686    @SuppressWarnings({"UnusedDeclaration"})
13687    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13688        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13689                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13690                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13691                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13692        if (clear) {
13693            mPrivateFlags &= clearMask;
13694        }
13695        if (this instanceof ViewGroup) {
13696            ViewGroup parent = (ViewGroup) this;
13697            final int count = parent.getChildCount();
13698            for (int i = 0; i < count; i++) {
13699                final View child = parent.getChildAt(i);
13700                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13701            }
13702        }
13703    }
13704
13705    /**
13706     * This method is used by ViewGroup to cause its children to restore or recreate their
13707     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13708     * to recreate its own display list, which would happen if it went through the normal
13709     * draw/dispatchDraw mechanisms.
13710     *
13711     * @hide
13712     */
13713    protected void dispatchGetDisplayList() {}
13714
13715    /**
13716     * A view that is not attached or hardware accelerated cannot create a display list.
13717     * This method checks these conditions and returns the appropriate result.
13718     *
13719     * @return true if view has the ability to create a display list, false otherwise.
13720     *
13721     * @hide
13722     */
13723    public boolean canHaveDisplayList() {
13724        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13725    }
13726
13727    private void updateDisplayListIfDirty() {
13728        final RenderNode renderNode = mRenderNode;
13729        if (!canHaveDisplayList()) {
13730            // can't populate RenderNode, don't try
13731            return;
13732        }
13733
13734        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13735                || !renderNode.isValid()
13736                || (mRecreateDisplayList)) {
13737            // Don't need to recreate the display list, just need to tell our
13738            // children to restore/recreate theirs
13739            if (renderNode.isValid()
13740                    && !mRecreateDisplayList) {
13741                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13742                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13743                dispatchGetDisplayList();
13744
13745                return; // no work needed
13746            }
13747
13748            // If we got here, we're recreating it. Mark it as such to ensure that
13749            // we copy in child display lists into ours in drawChild()
13750            mRecreateDisplayList = true;
13751
13752            int width = mRight - mLeft;
13753            int height = mBottom - mTop;
13754            int layerType = getLayerType();
13755
13756            final HardwareCanvas canvas = renderNode.start(width, height);
13757
13758            try {
13759                final HardwareLayer layer = getHardwareLayer();
13760                if (layer != null && layer.isValid()) {
13761                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13762                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13763                    buildDrawingCache(true);
13764                    Bitmap cache = getDrawingCache(true);
13765                    if (cache != null) {
13766                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13767                    }
13768                } else {
13769                    computeScroll();
13770
13771                    canvas.translate(-mScrollX, -mScrollY);
13772                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13773                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13774
13775                    // Fast path for layouts with no backgrounds
13776                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13777                        dispatchDraw(canvas);
13778                        if (mOverlay != null && !mOverlay.isEmpty()) {
13779                            mOverlay.getOverlayView().draw(canvas);
13780                        }
13781                    } else {
13782                        draw(canvas);
13783                    }
13784                }
13785            } finally {
13786                renderNode.end(canvas);
13787                setDisplayListProperties(renderNode);
13788            }
13789        } else {
13790            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13791            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13792        }
13793    }
13794
13795    /**
13796     * Returns a RenderNode with View draw content recorded, which can be
13797     * used to draw this view again without executing its draw method.
13798     *
13799     * @return A RenderNode ready to replay, or null if caching is not enabled.
13800     *
13801     * @hide
13802     */
13803    public RenderNode getDisplayList() {
13804        updateDisplayListIfDirty();
13805        return mRenderNode;
13806    }
13807
13808    private void resetDisplayList() {
13809        if (mRenderNode.isValid()) {
13810            mRenderNode.destroyDisplayListData();
13811        }
13812
13813        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13814            mBackgroundRenderNode.destroyDisplayListData();
13815        }
13816    }
13817
13818    /**
13819     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13820     *
13821     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13822     *
13823     * @see #getDrawingCache(boolean)
13824     */
13825    public Bitmap getDrawingCache() {
13826        return getDrawingCache(false);
13827    }
13828
13829    /**
13830     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13831     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13832     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13833     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13834     * request the drawing cache by calling this method and draw it on screen if the
13835     * returned bitmap is not null.</p>
13836     *
13837     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13838     * this method will create a bitmap of the same size as this view. Because this bitmap
13839     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13840     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13841     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13842     * size than the view. This implies that your application must be able to handle this
13843     * size.</p>
13844     *
13845     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13846     *        the current density of the screen when the application is in compatibility
13847     *        mode.
13848     *
13849     * @return A bitmap representing this view or null if cache is disabled.
13850     *
13851     * @see #setDrawingCacheEnabled(boolean)
13852     * @see #isDrawingCacheEnabled()
13853     * @see #buildDrawingCache(boolean)
13854     * @see #destroyDrawingCache()
13855     */
13856    public Bitmap getDrawingCache(boolean autoScale) {
13857        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13858            return null;
13859        }
13860        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13861            buildDrawingCache(autoScale);
13862        }
13863        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13864    }
13865
13866    /**
13867     * <p>Frees the resources used by the drawing cache. If you call
13868     * {@link #buildDrawingCache()} manually without calling
13869     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13870     * should cleanup the cache with this method afterwards.</p>
13871     *
13872     * @see #setDrawingCacheEnabled(boolean)
13873     * @see #buildDrawingCache()
13874     * @see #getDrawingCache()
13875     */
13876    public void destroyDrawingCache() {
13877        if (mDrawingCache != null) {
13878            mDrawingCache.recycle();
13879            mDrawingCache = null;
13880        }
13881        if (mUnscaledDrawingCache != null) {
13882            mUnscaledDrawingCache.recycle();
13883            mUnscaledDrawingCache = null;
13884        }
13885    }
13886
13887    /**
13888     * Setting a solid background color for the drawing cache's bitmaps will improve
13889     * performance and memory usage. Note, though that this should only be used if this
13890     * view will always be drawn on top of a solid color.
13891     *
13892     * @param color The background color to use for the drawing cache's bitmap
13893     *
13894     * @see #setDrawingCacheEnabled(boolean)
13895     * @see #buildDrawingCache()
13896     * @see #getDrawingCache()
13897     */
13898    public void setDrawingCacheBackgroundColor(int color) {
13899        if (color != mDrawingCacheBackgroundColor) {
13900            mDrawingCacheBackgroundColor = color;
13901            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13902        }
13903    }
13904
13905    /**
13906     * @see #setDrawingCacheBackgroundColor(int)
13907     *
13908     * @return The background color to used for the drawing cache's bitmap
13909     */
13910    public int getDrawingCacheBackgroundColor() {
13911        return mDrawingCacheBackgroundColor;
13912    }
13913
13914    /**
13915     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13916     *
13917     * @see #buildDrawingCache(boolean)
13918     */
13919    public void buildDrawingCache() {
13920        buildDrawingCache(false);
13921    }
13922
13923    /**
13924     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13925     *
13926     * <p>If you call {@link #buildDrawingCache()} manually without calling
13927     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13928     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13929     *
13930     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13931     * this method will create a bitmap of the same size as this view. Because this bitmap
13932     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13933     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13934     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13935     * size than the view. This implies that your application must be able to handle this
13936     * size.</p>
13937     *
13938     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13939     * you do not need the drawing cache bitmap, calling this method will increase memory
13940     * usage and cause the view to be rendered in software once, thus negatively impacting
13941     * performance.</p>
13942     *
13943     * @see #getDrawingCache()
13944     * @see #destroyDrawingCache()
13945     */
13946    public void buildDrawingCache(boolean autoScale) {
13947        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13948                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13949            mCachingFailed = false;
13950
13951            int width = mRight - mLeft;
13952            int height = mBottom - mTop;
13953
13954            final AttachInfo attachInfo = mAttachInfo;
13955            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13956
13957            if (autoScale && scalingRequired) {
13958                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13959                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13960            }
13961
13962            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13963            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13964            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13965
13966            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13967            final long drawingCacheSize =
13968                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13969            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13970                if (width > 0 && height > 0) {
13971                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13972                            + projectedBitmapSize + " bytes, only "
13973                            + drawingCacheSize + " available");
13974                }
13975                destroyDrawingCache();
13976                mCachingFailed = true;
13977                return;
13978            }
13979
13980            boolean clear = true;
13981            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13982
13983            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13984                Bitmap.Config quality;
13985                if (!opaque) {
13986                    // Never pick ARGB_4444 because it looks awful
13987                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13988                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13989                        case DRAWING_CACHE_QUALITY_AUTO:
13990                        case DRAWING_CACHE_QUALITY_LOW:
13991                        case DRAWING_CACHE_QUALITY_HIGH:
13992                        default:
13993                            quality = Bitmap.Config.ARGB_8888;
13994                            break;
13995                    }
13996                } else {
13997                    // Optimization for translucent windows
13998                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13999                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14000                }
14001
14002                // Try to cleanup memory
14003                if (bitmap != null) bitmap.recycle();
14004
14005                try {
14006                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14007                            width, height, quality);
14008                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14009                    if (autoScale) {
14010                        mDrawingCache = bitmap;
14011                    } else {
14012                        mUnscaledDrawingCache = bitmap;
14013                    }
14014                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14015                } catch (OutOfMemoryError e) {
14016                    // If there is not enough memory to create the bitmap cache, just
14017                    // ignore the issue as bitmap caches are not required to draw the
14018                    // view hierarchy
14019                    if (autoScale) {
14020                        mDrawingCache = null;
14021                    } else {
14022                        mUnscaledDrawingCache = null;
14023                    }
14024                    mCachingFailed = true;
14025                    return;
14026                }
14027
14028                clear = drawingCacheBackgroundColor != 0;
14029            }
14030
14031            Canvas canvas;
14032            if (attachInfo != null) {
14033                canvas = attachInfo.mCanvas;
14034                if (canvas == null) {
14035                    canvas = new Canvas();
14036                }
14037                canvas.setBitmap(bitmap);
14038                // Temporarily clobber the cached Canvas in case one of our children
14039                // is also using a drawing cache. Without this, the children would
14040                // steal the canvas by attaching their own bitmap to it and bad, bad
14041                // thing would happen (invisible views, corrupted drawings, etc.)
14042                attachInfo.mCanvas = null;
14043            } else {
14044                // This case should hopefully never or seldom happen
14045                canvas = new Canvas(bitmap);
14046            }
14047
14048            if (clear) {
14049                bitmap.eraseColor(drawingCacheBackgroundColor);
14050            }
14051
14052            computeScroll();
14053            final int restoreCount = canvas.save();
14054
14055            if (autoScale && scalingRequired) {
14056                final float scale = attachInfo.mApplicationScale;
14057                canvas.scale(scale, scale);
14058            }
14059
14060            canvas.translate(-mScrollX, -mScrollY);
14061
14062            mPrivateFlags |= PFLAG_DRAWN;
14063            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14064                    mLayerType != LAYER_TYPE_NONE) {
14065                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14066            }
14067
14068            // Fast path for layouts with no backgrounds
14069            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14070                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14071                dispatchDraw(canvas);
14072                if (mOverlay != null && !mOverlay.isEmpty()) {
14073                    mOverlay.getOverlayView().draw(canvas);
14074                }
14075            } else {
14076                draw(canvas);
14077            }
14078
14079            canvas.restoreToCount(restoreCount);
14080            canvas.setBitmap(null);
14081
14082            if (attachInfo != null) {
14083                // Restore the cached Canvas for our siblings
14084                attachInfo.mCanvas = canvas;
14085            }
14086        }
14087    }
14088
14089    /**
14090     * Create a snapshot of the view into a bitmap.  We should probably make
14091     * some form of this public, but should think about the API.
14092     */
14093    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14094        int width = mRight - mLeft;
14095        int height = mBottom - mTop;
14096
14097        final AttachInfo attachInfo = mAttachInfo;
14098        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14099        width = (int) ((width * scale) + 0.5f);
14100        height = (int) ((height * scale) + 0.5f);
14101
14102        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14103                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14104        if (bitmap == null) {
14105            throw new OutOfMemoryError();
14106        }
14107
14108        Resources resources = getResources();
14109        if (resources != null) {
14110            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14111        }
14112
14113        Canvas canvas;
14114        if (attachInfo != null) {
14115            canvas = attachInfo.mCanvas;
14116            if (canvas == null) {
14117                canvas = new Canvas();
14118            }
14119            canvas.setBitmap(bitmap);
14120            // Temporarily clobber the cached Canvas in case one of our children
14121            // is also using a drawing cache. Without this, the children would
14122            // steal the canvas by attaching their own bitmap to it and bad, bad
14123            // things would happen (invisible views, corrupted drawings, etc.)
14124            attachInfo.mCanvas = null;
14125        } else {
14126            // This case should hopefully never or seldom happen
14127            canvas = new Canvas(bitmap);
14128        }
14129
14130        if ((backgroundColor & 0xff000000) != 0) {
14131            bitmap.eraseColor(backgroundColor);
14132        }
14133
14134        computeScroll();
14135        final int restoreCount = canvas.save();
14136        canvas.scale(scale, scale);
14137        canvas.translate(-mScrollX, -mScrollY);
14138
14139        // Temporarily remove the dirty mask
14140        int flags = mPrivateFlags;
14141        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14142
14143        // Fast path for layouts with no backgrounds
14144        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14145            dispatchDraw(canvas);
14146            if (mOverlay != null && !mOverlay.isEmpty()) {
14147                mOverlay.getOverlayView().draw(canvas);
14148            }
14149        } else {
14150            draw(canvas);
14151        }
14152
14153        mPrivateFlags = flags;
14154
14155        canvas.restoreToCount(restoreCount);
14156        canvas.setBitmap(null);
14157
14158        if (attachInfo != null) {
14159            // Restore the cached Canvas for our siblings
14160            attachInfo.mCanvas = canvas;
14161        }
14162
14163        return bitmap;
14164    }
14165
14166    /**
14167     * Indicates whether this View is currently in edit mode. A View is usually
14168     * in edit mode when displayed within a developer tool. For instance, if
14169     * this View is being drawn by a visual user interface builder, this method
14170     * should return true.
14171     *
14172     * Subclasses should check the return value of this method to provide
14173     * different behaviors if their normal behavior might interfere with the
14174     * host environment. For instance: the class spawns a thread in its
14175     * constructor, the drawing code relies on device-specific features, etc.
14176     *
14177     * This method is usually checked in the drawing code of custom widgets.
14178     *
14179     * @return True if this View is in edit mode, false otherwise.
14180     */
14181    public boolean isInEditMode() {
14182        return false;
14183    }
14184
14185    /**
14186     * If the View draws content inside its padding and enables fading edges,
14187     * it needs to support padding offsets. Padding offsets are added to the
14188     * fading edges to extend the length of the fade so that it covers pixels
14189     * drawn inside the padding.
14190     *
14191     * Subclasses of this class should override this method if they need
14192     * to draw content inside the padding.
14193     *
14194     * @return True if padding offset must be applied, false otherwise.
14195     *
14196     * @see #getLeftPaddingOffset()
14197     * @see #getRightPaddingOffset()
14198     * @see #getTopPaddingOffset()
14199     * @see #getBottomPaddingOffset()
14200     *
14201     * @since CURRENT
14202     */
14203    protected boolean isPaddingOffsetRequired() {
14204        return false;
14205    }
14206
14207    /**
14208     * Amount by which to extend the left fading region. Called only when
14209     * {@link #isPaddingOffsetRequired()} returns true.
14210     *
14211     * @return The left padding offset in pixels.
14212     *
14213     * @see #isPaddingOffsetRequired()
14214     *
14215     * @since CURRENT
14216     */
14217    protected int getLeftPaddingOffset() {
14218        return 0;
14219    }
14220
14221    /**
14222     * Amount by which to extend the right fading region. Called only when
14223     * {@link #isPaddingOffsetRequired()} returns true.
14224     *
14225     * @return The right padding offset in pixels.
14226     *
14227     * @see #isPaddingOffsetRequired()
14228     *
14229     * @since CURRENT
14230     */
14231    protected int getRightPaddingOffset() {
14232        return 0;
14233    }
14234
14235    /**
14236     * Amount by which to extend the top fading region. Called only when
14237     * {@link #isPaddingOffsetRequired()} returns true.
14238     *
14239     * @return The top padding offset in pixels.
14240     *
14241     * @see #isPaddingOffsetRequired()
14242     *
14243     * @since CURRENT
14244     */
14245    protected int getTopPaddingOffset() {
14246        return 0;
14247    }
14248
14249    /**
14250     * Amount by which to extend the bottom fading region. Called only when
14251     * {@link #isPaddingOffsetRequired()} returns true.
14252     *
14253     * @return The bottom padding offset in pixels.
14254     *
14255     * @see #isPaddingOffsetRequired()
14256     *
14257     * @since CURRENT
14258     */
14259    protected int getBottomPaddingOffset() {
14260        return 0;
14261    }
14262
14263    /**
14264     * @hide
14265     * @param offsetRequired
14266     */
14267    protected int getFadeTop(boolean offsetRequired) {
14268        int top = mPaddingTop;
14269        if (offsetRequired) top += getTopPaddingOffset();
14270        return top;
14271    }
14272
14273    /**
14274     * @hide
14275     * @param offsetRequired
14276     */
14277    protected int getFadeHeight(boolean offsetRequired) {
14278        int padding = mPaddingTop;
14279        if (offsetRequired) padding += getTopPaddingOffset();
14280        return mBottom - mTop - mPaddingBottom - padding;
14281    }
14282
14283    /**
14284     * <p>Indicates whether this view is attached to a hardware accelerated
14285     * window or not.</p>
14286     *
14287     * <p>Even if this method returns true, it does not mean that every call
14288     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14289     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14290     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14291     * window is hardware accelerated,
14292     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14293     * return false, and this method will return true.</p>
14294     *
14295     * @return True if the view is attached to a window and the window is
14296     *         hardware accelerated; false in any other case.
14297     */
14298    @ViewDebug.ExportedProperty(category = "drawing")
14299    public boolean isHardwareAccelerated() {
14300        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14301    }
14302
14303    /**
14304     * Sets a rectangular area on this view to which the view will be clipped
14305     * when it is drawn. Setting the value to null will remove the clip bounds
14306     * and the view will draw normally, using its full bounds.
14307     *
14308     * @param clipBounds The rectangular area, in the local coordinates of
14309     * this view, to which future drawing operations will be clipped.
14310     */
14311    public void setClipBounds(Rect clipBounds) {
14312        if (clipBounds != null) {
14313            if (clipBounds.equals(mClipBounds)) {
14314                return;
14315            }
14316            if (mClipBounds == null) {
14317                invalidate();
14318                mClipBounds = new Rect(clipBounds);
14319            } else {
14320                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14321                        Math.min(mClipBounds.top, clipBounds.top),
14322                        Math.max(mClipBounds.right, clipBounds.right),
14323                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14324                mClipBounds.set(clipBounds);
14325            }
14326        } else {
14327            if (mClipBounds != null) {
14328                invalidate();
14329                mClipBounds = null;
14330            }
14331        }
14332    }
14333
14334    /**
14335     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14336     *
14337     * @return A copy of the current clip bounds if clip bounds are set,
14338     * otherwise null.
14339     */
14340    public Rect getClipBounds() {
14341        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14342    }
14343
14344    /**
14345     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14346     * case of an active Animation being run on the view.
14347     */
14348    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14349            Animation a, boolean scalingRequired) {
14350        Transformation invalidationTransform;
14351        final int flags = parent.mGroupFlags;
14352        final boolean initialized = a.isInitialized();
14353        if (!initialized) {
14354            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14355            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14356            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14357            onAnimationStart();
14358        }
14359
14360        final Transformation t = parent.getChildTransformation();
14361        boolean more = a.getTransformation(drawingTime, t, 1f);
14362        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14363            if (parent.mInvalidationTransformation == null) {
14364                parent.mInvalidationTransformation = new Transformation();
14365            }
14366            invalidationTransform = parent.mInvalidationTransformation;
14367            a.getTransformation(drawingTime, invalidationTransform, 1f);
14368        } else {
14369            invalidationTransform = t;
14370        }
14371
14372        if (more) {
14373            if (!a.willChangeBounds()) {
14374                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14375                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14376                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14377                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14378                    // The child need to draw an animation, potentially offscreen, so
14379                    // make sure we do not cancel invalidate requests
14380                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14381                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14382                }
14383            } else {
14384                if (parent.mInvalidateRegion == null) {
14385                    parent.mInvalidateRegion = new RectF();
14386                }
14387                final RectF region = parent.mInvalidateRegion;
14388                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14389                        invalidationTransform);
14390
14391                // The child need to draw an animation, potentially offscreen, so
14392                // make sure we do not cancel invalidate requests
14393                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14394
14395                final int left = mLeft + (int) region.left;
14396                final int top = mTop + (int) region.top;
14397                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14398                        top + (int) (region.height() + .5f));
14399            }
14400        }
14401        return more;
14402    }
14403
14404    /**
14405     * This method is called by getDisplayList() when a display list is recorded for a View.
14406     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14407     */
14408    void setDisplayListProperties(RenderNode renderNode) {
14409        if (renderNode != null) {
14410            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14411            if (mParent instanceof ViewGroup) {
14412                renderNode.setClipToBounds(
14413                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14414            }
14415            float alpha = 1;
14416            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14417                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14418                ViewGroup parentVG = (ViewGroup) mParent;
14419                final Transformation t = parentVG.getChildTransformation();
14420                if (parentVG.getChildStaticTransformation(this, t)) {
14421                    final int transformType = t.getTransformationType();
14422                    if (transformType != Transformation.TYPE_IDENTITY) {
14423                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14424                            alpha = t.getAlpha();
14425                        }
14426                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14427                            renderNode.setStaticMatrix(t.getMatrix());
14428                        }
14429                    }
14430                }
14431            }
14432            if (mTransformationInfo != null) {
14433                alpha *= getFinalAlpha();
14434                if (alpha < 1) {
14435                    final int multipliedAlpha = (int) (255 * alpha);
14436                    if (onSetAlpha(multipliedAlpha)) {
14437                        alpha = 1;
14438                    }
14439                }
14440                renderNode.setAlpha(alpha);
14441            } else if (alpha < 1) {
14442                renderNode.setAlpha(alpha);
14443            }
14444        }
14445    }
14446
14447    /**
14448     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14449     * This draw() method is an implementation detail and is not intended to be overridden or
14450     * to be called from anywhere else other than ViewGroup.drawChild().
14451     */
14452    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14453        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14454        boolean more = false;
14455        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14456        final int flags = parent.mGroupFlags;
14457
14458        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14459            parent.getChildTransformation().clear();
14460            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14461        }
14462
14463        Transformation transformToApply = null;
14464        boolean concatMatrix = false;
14465
14466        boolean scalingRequired = false;
14467        boolean caching;
14468        int layerType = getLayerType();
14469
14470        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14471        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14472                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14473            caching = true;
14474            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14475            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14476        } else {
14477            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14478        }
14479
14480        final Animation a = getAnimation();
14481        if (a != null) {
14482            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14483            concatMatrix = a.willChangeTransformationMatrix();
14484            if (concatMatrix) {
14485                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14486            }
14487            transformToApply = parent.getChildTransformation();
14488        } else {
14489            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14490                // No longer animating: clear out old animation matrix
14491                mRenderNode.setAnimationMatrix(null);
14492                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14493            }
14494            if (!useDisplayListProperties &&
14495                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14496                final Transformation t = parent.getChildTransformation();
14497                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14498                if (hasTransform) {
14499                    final int transformType = t.getTransformationType();
14500                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14501                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14502                }
14503            }
14504        }
14505
14506        concatMatrix |= !childHasIdentityMatrix;
14507
14508        // Sets the flag as early as possible to allow draw() implementations
14509        // to call invalidate() successfully when doing animations
14510        mPrivateFlags |= PFLAG_DRAWN;
14511
14512        if (!concatMatrix &&
14513                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14514                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14515                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14516                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14517            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14518            return more;
14519        }
14520        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14521
14522        if (hardwareAccelerated) {
14523            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14524            // retain the flag's value temporarily in the mRecreateDisplayList flag
14525            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14526            mPrivateFlags &= ~PFLAG_INVALIDATED;
14527        }
14528
14529        RenderNode renderNode = null;
14530        Bitmap cache = null;
14531        boolean hasDisplayList = false;
14532        if (caching) {
14533            if (!hardwareAccelerated) {
14534                if (layerType != LAYER_TYPE_NONE) {
14535                    layerType = LAYER_TYPE_SOFTWARE;
14536                    buildDrawingCache(true);
14537                }
14538                cache = getDrawingCache(true);
14539            } else {
14540                switch (layerType) {
14541                    case LAYER_TYPE_SOFTWARE:
14542                        if (useDisplayListProperties) {
14543                            hasDisplayList = canHaveDisplayList();
14544                        } else {
14545                            buildDrawingCache(true);
14546                            cache = getDrawingCache(true);
14547                        }
14548                        break;
14549                    case LAYER_TYPE_HARDWARE:
14550                        if (useDisplayListProperties) {
14551                            hasDisplayList = canHaveDisplayList();
14552                        }
14553                        break;
14554                    case LAYER_TYPE_NONE:
14555                        // Delay getting the display list until animation-driven alpha values are
14556                        // set up and possibly passed on to the view
14557                        hasDisplayList = canHaveDisplayList();
14558                        break;
14559                }
14560            }
14561        }
14562        useDisplayListProperties &= hasDisplayList;
14563        if (useDisplayListProperties) {
14564            renderNode = getDisplayList();
14565            if (!renderNode.isValid()) {
14566                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14567                // to getDisplayList(), the display list will be marked invalid and we should not
14568                // try to use it again.
14569                renderNode = null;
14570                hasDisplayList = false;
14571                useDisplayListProperties = false;
14572            }
14573        }
14574
14575        int sx = 0;
14576        int sy = 0;
14577        if (!hasDisplayList) {
14578            computeScroll();
14579            sx = mScrollX;
14580            sy = mScrollY;
14581        }
14582
14583        final boolean hasNoCache = cache == null || hasDisplayList;
14584        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14585                layerType != LAYER_TYPE_HARDWARE;
14586
14587        int restoreTo = -1;
14588        if (!useDisplayListProperties || transformToApply != null) {
14589            restoreTo = canvas.save();
14590        }
14591        if (offsetForScroll) {
14592            canvas.translate(mLeft - sx, mTop - sy);
14593        } else {
14594            if (!useDisplayListProperties) {
14595                canvas.translate(mLeft, mTop);
14596            }
14597            if (scalingRequired) {
14598                if (useDisplayListProperties) {
14599                    // TODO: Might not need this if we put everything inside the DL
14600                    restoreTo = canvas.save();
14601                }
14602                // mAttachInfo cannot be null, otherwise scalingRequired == false
14603                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14604                canvas.scale(scale, scale);
14605            }
14606        }
14607
14608        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14609        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14610                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14611            if (transformToApply != null || !childHasIdentityMatrix) {
14612                int transX = 0;
14613                int transY = 0;
14614
14615                if (offsetForScroll) {
14616                    transX = -sx;
14617                    transY = -sy;
14618                }
14619
14620                if (transformToApply != null) {
14621                    if (concatMatrix) {
14622                        if (useDisplayListProperties) {
14623                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14624                        } else {
14625                            // Undo the scroll translation, apply the transformation matrix,
14626                            // then redo the scroll translate to get the correct result.
14627                            canvas.translate(-transX, -transY);
14628                            canvas.concat(transformToApply.getMatrix());
14629                            canvas.translate(transX, transY);
14630                        }
14631                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14632                    }
14633
14634                    float transformAlpha = transformToApply.getAlpha();
14635                    if (transformAlpha < 1) {
14636                        alpha *= transformAlpha;
14637                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14638                    }
14639                }
14640
14641                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14642                    canvas.translate(-transX, -transY);
14643                    canvas.concat(getMatrix());
14644                    canvas.translate(transX, transY);
14645                }
14646            }
14647
14648            // Deal with alpha if it is or used to be <1
14649            if (alpha < 1 ||
14650                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14651                if (alpha < 1) {
14652                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14653                } else {
14654                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14655                }
14656                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14657                if (hasNoCache) {
14658                    final int multipliedAlpha = (int) (255 * alpha);
14659                    if (!onSetAlpha(multipliedAlpha)) {
14660                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14661                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14662                                layerType != LAYER_TYPE_NONE) {
14663                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14664                        }
14665                        if (useDisplayListProperties) {
14666                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14667                        } else  if (layerType == LAYER_TYPE_NONE) {
14668                            final int scrollX = hasDisplayList ? 0 : sx;
14669                            final int scrollY = hasDisplayList ? 0 : sy;
14670                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14671                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14672                        }
14673                    } else {
14674                        // Alpha is handled by the child directly, clobber the layer's alpha
14675                        mPrivateFlags |= PFLAG_ALPHA_SET;
14676                    }
14677                }
14678            }
14679        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14680            onSetAlpha(255);
14681            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14682        }
14683
14684        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14685                !useDisplayListProperties && cache == null) {
14686            if (offsetForScroll) {
14687                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14688            } else {
14689                if (!scalingRequired || cache == null) {
14690                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14691                } else {
14692                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14693                }
14694            }
14695        }
14696
14697        if (!useDisplayListProperties && hasDisplayList) {
14698            renderNode = getDisplayList();
14699            if (!renderNode.isValid()) {
14700                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14701                // to getDisplayList(), the display list will be marked invalid and we should not
14702                // try to use it again.
14703                renderNode = null;
14704                hasDisplayList = false;
14705            }
14706        }
14707
14708        if (hasNoCache) {
14709            boolean layerRendered = false;
14710            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14711                final HardwareLayer layer = getHardwareLayer();
14712                if (layer != null && layer.isValid()) {
14713                    mLayerPaint.setAlpha((int) (alpha * 255));
14714                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14715                    layerRendered = true;
14716                } else {
14717                    final int scrollX = hasDisplayList ? 0 : sx;
14718                    final int scrollY = hasDisplayList ? 0 : sy;
14719                    canvas.saveLayer(scrollX, scrollY,
14720                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14721                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14722                }
14723            }
14724
14725            if (!layerRendered) {
14726                if (!hasDisplayList) {
14727                    // Fast path for layouts with no backgrounds
14728                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14729                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14730                        dispatchDraw(canvas);
14731                    } else {
14732                        draw(canvas);
14733                    }
14734                } else {
14735                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14736                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14737                }
14738            }
14739        } else if (cache != null) {
14740            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14741            Paint cachePaint;
14742
14743            if (layerType == LAYER_TYPE_NONE) {
14744                cachePaint = parent.mCachePaint;
14745                if (cachePaint == null) {
14746                    cachePaint = new Paint();
14747                    cachePaint.setDither(false);
14748                    parent.mCachePaint = cachePaint;
14749                }
14750                if (alpha < 1) {
14751                    cachePaint.setAlpha((int) (alpha * 255));
14752                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14753                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14754                    cachePaint.setAlpha(255);
14755                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14756                }
14757            } else {
14758                cachePaint = mLayerPaint;
14759                cachePaint.setAlpha((int) (alpha * 255));
14760            }
14761            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14762        }
14763
14764        if (restoreTo >= 0) {
14765            canvas.restoreToCount(restoreTo);
14766        }
14767
14768        if (a != null && !more) {
14769            if (!hardwareAccelerated && !a.getFillAfter()) {
14770                onSetAlpha(255);
14771            }
14772            parent.finishAnimatingView(this, a);
14773        }
14774
14775        if (more && hardwareAccelerated) {
14776            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14777                // alpha animations should cause the child to recreate its display list
14778                invalidate(true);
14779            }
14780        }
14781
14782        mRecreateDisplayList = false;
14783
14784        return more;
14785    }
14786
14787    /**
14788     * Manually render this view (and all of its children) to the given Canvas.
14789     * The view must have already done a full layout before this function is
14790     * called.  When implementing a view, implement
14791     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14792     * If you do need to override this method, call the superclass version.
14793     *
14794     * @param canvas The Canvas to which the View is rendered.
14795     */
14796    public void draw(Canvas canvas) {
14797        if (mClipBounds != null) {
14798            canvas.clipRect(mClipBounds);
14799        }
14800        final int privateFlags = mPrivateFlags;
14801        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14802                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14803        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14804
14805        /*
14806         * Draw traversal performs several drawing steps which must be executed
14807         * in the appropriate order:
14808         *
14809         *      1. Draw the background
14810         *      2. If necessary, save the canvas' layers to prepare for fading
14811         *      3. Draw view's content
14812         *      4. Draw children
14813         *      5. If necessary, draw the fading edges and restore layers
14814         *      6. Draw decorations (scrollbars for instance)
14815         */
14816
14817        // Step 1, draw the background, if needed
14818        int saveCount;
14819
14820        if (!dirtyOpaque) {
14821            drawBackground(canvas);
14822        }
14823
14824        // skip step 2 & 5 if possible (common case)
14825        final int viewFlags = mViewFlags;
14826        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14827        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14828        if (!verticalEdges && !horizontalEdges) {
14829            // Step 3, draw the content
14830            if (!dirtyOpaque) onDraw(canvas);
14831
14832            // Step 4, draw the children
14833            dispatchDraw(canvas);
14834
14835            // Step 6, draw decorations (scrollbars)
14836            onDrawScrollBars(canvas);
14837
14838            if (mOverlay != null && !mOverlay.isEmpty()) {
14839                mOverlay.getOverlayView().dispatchDraw(canvas);
14840            }
14841
14842            // we're done...
14843            return;
14844        }
14845
14846        /*
14847         * Here we do the full fledged routine...
14848         * (this is an uncommon case where speed matters less,
14849         * this is why we repeat some of the tests that have been
14850         * done above)
14851         */
14852
14853        boolean drawTop = false;
14854        boolean drawBottom = false;
14855        boolean drawLeft = false;
14856        boolean drawRight = false;
14857
14858        float topFadeStrength = 0.0f;
14859        float bottomFadeStrength = 0.0f;
14860        float leftFadeStrength = 0.0f;
14861        float rightFadeStrength = 0.0f;
14862
14863        // Step 2, save the canvas' layers
14864        int paddingLeft = mPaddingLeft;
14865
14866        final boolean offsetRequired = isPaddingOffsetRequired();
14867        if (offsetRequired) {
14868            paddingLeft += getLeftPaddingOffset();
14869        }
14870
14871        int left = mScrollX + paddingLeft;
14872        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14873        int top = mScrollY + getFadeTop(offsetRequired);
14874        int bottom = top + getFadeHeight(offsetRequired);
14875
14876        if (offsetRequired) {
14877            right += getRightPaddingOffset();
14878            bottom += getBottomPaddingOffset();
14879        }
14880
14881        final ScrollabilityCache scrollabilityCache = mScrollCache;
14882        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14883        int length = (int) fadeHeight;
14884
14885        // clip the fade length if top and bottom fades overlap
14886        // overlapping fades produce odd-looking artifacts
14887        if (verticalEdges && (top + length > bottom - length)) {
14888            length = (bottom - top) / 2;
14889        }
14890
14891        // also clip horizontal fades if necessary
14892        if (horizontalEdges && (left + length > right - length)) {
14893            length = (right - left) / 2;
14894        }
14895
14896        if (verticalEdges) {
14897            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14898            drawTop = topFadeStrength * fadeHeight > 1.0f;
14899            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14900            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14901        }
14902
14903        if (horizontalEdges) {
14904            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14905            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14906            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14907            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14908        }
14909
14910        saveCount = canvas.getSaveCount();
14911
14912        int solidColor = getSolidColor();
14913        if (solidColor == 0) {
14914            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14915
14916            if (drawTop) {
14917                canvas.saveLayer(left, top, right, top + length, null, flags);
14918            }
14919
14920            if (drawBottom) {
14921                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14922            }
14923
14924            if (drawLeft) {
14925                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14926            }
14927
14928            if (drawRight) {
14929                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14930            }
14931        } else {
14932            scrollabilityCache.setFadeColor(solidColor);
14933        }
14934
14935        // Step 3, draw the content
14936        if (!dirtyOpaque) onDraw(canvas);
14937
14938        // Step 4, draw the children
14939        dispatchDraw(canvas);
14940
14941        // Step 5, draw the fade effect and restore layers
14942        final Paint p = scrollabilityCache.paint;
14943        final Matrix matrix = scrollabilityCache.matrix;
14944        final Shader fade = scrollabilityCache.shader;
14945
14946        if (drawTop) {
14947            matrix.setScale(1, fadeHeight * topFadeStrength);
14948            matrix.postTranslate(left, top);
14949            fade.setLocalMatrix(matrix);
14950            canvas.drawRect(left, top, right, top + length, p);
14951        }
14952
14953        if (drawBottom) {
14954            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14955            matrix.postRotate(180);
14956            matrix.postTranslate(left, bottom);
14957            fade.setLocalMatrix(matrix);
14958            canvas.drawRect(left, bottom - length, right, bottom, p);
14959        }
14960
14961        if (drawLeft) {
14962            matrix.setScale(1, fadeHeight * leftFadeStrength);
14963            matrix.postRotate(-90);
14964            matrix.postTranslate(left, top);
14965            fade.setLocalMatrix(matrix);
14966            canvas.drawRect(left, top, left + length, bottom, p);
14967        }
14968
14969        if (drawRight) {
14970            matrix.setScale(1, fadeHeight * rightFadeStrength);
14971            matrix.postRotate(90);
14972            matrix.postTranslate(right, top);
14973            fade.setLocalMatrix(matrix);
14974            canvas.drawRect(right - length, top, right, bottom, p);
14975        }
14976
14977        canvas.restoreToCount(saveCount);
14978
14979        // Step 6, draw decorations (scrollbars)
14980        onDrawScrollBars(canvas);
14981
14982        if (mOverlay != null && !mOverlay.isEmpty()) {
14983            mOverlay.getOverlayView().dispatchDraw(canvas);
14984        }
14985    }
14986
14987    /**
14988     * Draws the background onto the specified canvas.
14989     *
14990     * @param canvas Canvas on which to draw the background
14991     */
14992    private void drawBackground(Canvas canvas) {
14993        final Drawable background = mBackground;
14994        if (background == null) {
14995            return;
14996        }
14997
14998        if (mBackgroundSizeChanged) {
14999            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15000            mBackgroundSizeChanged = false;
15001            invalidateOutline();
15002        }
15003
15004        // Attempt to use a display list if requested.
15005        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15006                && mAttachInfo.mHardwareRenderer != null) {
15007            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15008
15009            final RenderNode displayList = mBackgroundRenderNode;
15010            if (displayList != null && displayList.isValid()) {
15011                setBackgroundDisplayListProperties(displayList);
15012                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15013                return;
15014            }
15015        }
15016
15017        final int scrollX = mScrollX;
15018        final int scrollY = mScrollY;
15019        if ((scrollX | scrollY) == 0) {
15020            background.draw(canvas);
15021        } else {
15022            canvas.translate(scrollX, scrollY);
15023            background.draw(canvas);
15024            canvas.translate(-scrollX, -scrollY);
15025        }
15026    }
15027
15028    /**
15029     * Set up background drawable display list properties.
15030     *
15031     * @param displayList Valid display list for the background drawable
15032     */
15033    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15034        displayList.setTranslationX(mScrollX);
15035        displayList.setTranslationY(mScrollY);
15036    }
15037
15038    /**
15039     * Creates a new display list or updates the existing display list for the
15040     * specified Drawable.
15041     *
15042     * @param drawable Drawable for which to create a display list
15043     * @param renderNode Existing RenderNode, or {@code null}
15044     * @return A valid display list for the specified drawable
15045     */
15046    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15047        if (renderNode == null) {
15048            renderNode = RenderNode.create(drawable.getClass().getName());
15049        }
15050
15051        final Rect bounds = drawable.getBounds();
15052        final int width = bounds.width();
15053        final int height = bounds.height();
15054        final HardwareCanvas canvas = renderNode.start(width, height);
15055        try {
15056            drawable.draw(canvas);
15057        } finally {
15058            renderNode.end(canvas);
15059        }
15060
15061        // Set up drawable properties that are view-independent.
15062        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15063        renderNode.setProjectBackwards(drawable.isProjected());
15064        renderNode.setProjectionReceiver(true);
15065        renderNode.setClipToBounds(false);
15066        return renderNode;
15067    }
15068
15069    /**
15070     * Returns the overlay for this view, creating it if it does not yet exist.
15071     * Adding drawables to the overlay will cause them to be displayed whenever
15072     * the view itself is redrawn. Objects in the overlay should be actively
15073     * managed: remove them when they should not be displayed anymore. The
15074     * overlay will always have the same size as its host view.
15075     *
15076     * <p>Note: Overlays do not currently work correctly with {@link
15077     * SurfaceView} or {@link TextureView}; contents in overlays for these
15078     * types of views may not display correctly.</p>
15079     *
15080     * @return The ViewOverlay object for this view.
15081     * @see ViewOverlay
15082     */
15083    public ViewOverlay getOverlay() {
15084        if (mOverlay == null) {
15085            mOverlay = new ViewOverlay(mContext, this);
15086        }
15087        return mOverlay;
15088    }
15089
15090    /**
15091     * Override this if your view is known to always be drawn on top of a solid color background,
15092     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15093     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15094     * should be set to 0xFF.
15095     *
15096     * @see #setVerticalFadingEdgeEnabled(boolean)
15097     * @see #setHorizontalFadingEdgeEnabled(boolean)
15098     *
15099     * @return The known solid color background for this view, or 0 if the color may vary
15100     */
15101    @ViewDebug.ExportedProperty(category = "drawing")
15102    public int getSolidColor() {
15103        return 0;
15104    }
15105
15106    /**
15107     * Build a human readable string representation of the specified view flags.
15108     *
15109     * @param flags the view flags to convert to a string
15110     * @return a String representing the supplied flags
15111     */
15112    private static String printFlags(int flags) {
15113        String output = "";
15114        int numFlags = 0;
15115        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15116            output += "TAKES_FOCUS";
15117            numFlags++;
15118        }
15119
15120        switch (flags & VISIBILITY_MASK) {
15121        case INVISIBLE:
15122            if (numFlags > 0) {
15123                output += " ";
15124            }
15125            output += "INVISIBLE";
15126            // USELESS HERE numFlags++;
15127            break;
15128        case GONE:
15129            if (numFlags > 0) {
15130                output += " ";
15131            }
15132            output += "GONE";
15133            // USELESS HERE numFlags++;
15134            break;
15135        default:
15136            break;
15137        }
15138        return output;
15139    }
15140
15141    /**
15142     * Build a human readable string representation of the specified private
15143     * view flags.
15144     *
15145     * @param privateFlags the private view flags to convert to a string
15146     * @return a String representing the supplied flags
15147     */
15148    private static String printPrivateFlags(int privateFlags) {
15149        String output = "";
15150        int numFlags = 0;
15151
15152        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15153            output += "WANTS_FOCUS";
15154            numFlags++;
15155        }
15156
15157        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15158            if (numFlags > 0) {
15159                output += " ";
15160            }
15161            output += "FOCUSED";
15162            numFlags++;
15163        }
15164
15165        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15166            if (numFlags > 0) {
15167                output += " ";
15168            }
15169            output += "SELECTED";
15170            numFlags++;
15171        }
15172
15173        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15174            if (numFlags > 0) {
15175                output += " ";
15176            }
15177            output += "IS_ROOT_NAMESPACE";
15178            numFlags++;
15179        }
15180
15181        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15182            if (numFlags > 0) {
15183                output += " ";
15184            }
15185            output += "HAS_BOUNDS";
15186            numFlags++;
15187        }
15188
15189        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15190            if (numFlags > 0) {
15191                output += " ";
15192            }
15193            output += "DRAWN";
15194            // USELESS HERE numFlags++;
15195        }
15196        return output;
15197    }
15198
15199    /**
15200     * <p>Indicates whether or not this view's layout will be requested during
15201     * the next hierarchy layout pass.</p>
15202     *
15203     * @return true if the layout will be forced during next layout pass
15204     */
15205    public boolean isLayoutRequested() {
15206        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15207    }
15208
15209    /**
15210     * Return true if o is a ViewGroup that is laying out using optical bounds.
15211     * @hide
15212     */
15213    public static boolean isLayoutModeOptical(Object o) {
15214        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15215    }
15216
15217    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15218        Insets parentInsets = mParent instanceof View ?
15219                ((View) mParent).getOpticalInsets() : Insets.NONE;
15220        Insets childInsets = getOpticalInsets();
15221        return setFrame(
15222                left   + parentInsets.left - childInsets.left,
15223                top    + parentInsets.top  - childInsets.top,
15224                right  + parentInsets.left + childInsets.right,
15225                bottom + parentInsets.top  + childInsets.bottom);
15226    }
15227
15228    /**
15229     * Assign a size and position to a view and all of its
15230     * descendants
15231     *
15232     * <p>This is the second phase of the layout mechanism.
15233     * (The first is measuring). In this phase, each parent calls
15234     * layout on all of its children to position them.
15235     * This is typically done using the child measurements
15236     * that were stored in the measure pass().</p>
15237     *
15238     * <p>Derived classes should not override this method.
15239     * Derived classes with children should override
15240     * onLayout. In that method, they should
15241     * call layout on each of their children.</p>
15242     *
15243     * @param l Left position, relative to parent
15244     * @param t Top position, relative to parent
15245     * @param r Right position, relative to parent
15246     * @param b Bottom position, relative to parent
15247     */
15248    @SuppressWarnings({"unchecked"})
15249    public void layout(int l, int t, int r, int b) {
15250        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15251            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15252            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15253        }
15254
15255        int oldL = mLeft;
15256        int oldT = mTop;
15257        int oldB = mBottom;
15258        int oldR = mRight;
15259
15260        boolean changed = isLayoutModeOptical(mParent) ?
15261                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15262
15263        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15264            onLayout(changed, l, t, r, b);
15265            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15266
15267            ListenerInfo li = mListenerInfo;
15268            if (li != null && li.mOnLayoutChangeListeners != null) {
15269                ArrayList<OnLayoutChangeListener> listenersCopy =
15270                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15271                int numListeners = listenersCopy.size();
15272                for (int i = 0; i < numListeners; ++i) {
15273                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15274                }
15275            }
15276        }
15277
15278        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15279        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15280    }
15281
15282    /**
15283     * Called from layout when this view should
15284     * assign a size and position to each of its children.
15285     *
15286     * Derived classes with children should override
15287     * this method and call layout on each of
15288     * their children.
15289     * @param changed This is a new size or position for this view
15290     * @param left Left position, relative to parent
15291     * @param top Top position, relative to parent
15292     * @param right Right position, relative to parent
15293     * @param bottom Bottom position, relative to parent
15294     */
15295    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15296    }
15297
15298    /**
15299     * Assign a size and position to this view.
15300     *
15301     * This is called from layout.
15302     *
15303     * @param left Left position, relative to parent
15304     * @param top Top position, relative to parent
15305     * @param right Right position, relative to parent
15306     * @param bottom Bottom position, relative to parent
15307     * @return true if the new size and position are different than the
15308     *         previous ones
15309     * {@hide}
15310     */
15311    protected boolean setFrame(int left, int top, int right, int bottom) {
15312        boolean changed = false;
15313
15314        if (DBG) {
15315            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15316                    + right + "," + bottom + ")");
15317        }
15318
15319        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15320            changed = true;
15321
15322            // Remember our drawn bit
15323            int drawn = mPrivateFlags & PFLAG_DRAWN;
15324
15325            int oldWidth = mRight - mLeft;
15326            int oldHeight = mBottom - mTop;
15327            int newWidth = right - left;
15328            int newHeight = bottom - top;
15329            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15330
15331            // Invalidate our old position
15332            invalidate(sizeChanged);
15333
15334            mLeft = left;
15335            mTop = top;
15336            mRight = right;
15337            mBottom = bottom;
15338            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15339
15340            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15341
15342
15343            if (sizeChanged) {
15344                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15345            }
15346
15347            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15348                // If we are visible, force the DRAWN bit to on so that
15349                // this invalidate will go through (at least to our parent).
15350                // This is because someone may have invalidated this view
15351                // before this call to setFrame came in, thereby clearing
15352                // the DRAWN bit.
15353                mPrivateFlags |= PFLAG_DRAWN;
15354                invalidate(sizeChanged);
15355                // parent display list may need to be recreated based on a change in the bounds
15356                // of any child
15357                invalidateParentCaches();
15358            }
15359
15360            // Reset drawn bit to original value (invalidate turns it off)
15361            mPrivateFlags |= drawn;
15362
15363            mBackgroundSizeChanged = true;
15364
15365            notifySubtreeAccessibilityStateChangedIfNeeded();
15366        }
15367        return changed;
15368    }
15369
15370    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15371        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15372        if (mOverlay != null) {
15373            mOverlay.getOverlayView().setRight(newWidth);
15374            mOverlay.getOverlayView().setBottom(newHeight);
15375        }
15376        invalidateOutline();
15377    }
15378
15379    /**
15380     * Finalize inflating a view from XML.  This is called as the last phase
15381     * of inflation, after all child views have been added.
15382     *
15383     * <p>Even if the subclass overrides onFinishInflate, they should always be
15384     * sure to call the super method, so that we get called.
15385     */
15386    protected void onFinishInflate() {
15387    }
15388
15389    /**
15390     * Returns the resources associated with this view.
15391     *
15392     * @return Resources object.
15393     */
15394    public Resources getResources() {
15395        return mResources;
15396    }
15397
15398    /**
15399     * Invalidates the specified Drawable.
15400     *
15401     * @param drawable the drawable to invalidate
15402     */
15403    @Override
15404    public void invalidateDrawable(@NonNull Drawable drawable) {
15405        if (verifyDrawable(drawable)) {
15406            final Rect dirty = drawable.getDirtyBounds();
15407            final int scrollX = mScrollX;
15408            final int scrollY = mScrollY;
15409
15410            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15411                    dirty.right + scrollX, dirty.bottom + scrollY);
15412
15413            invalidateOutline();
15414        }
15415    }
15416
15417    /**
15418     * Schedules an action on a drawable to occur at a specified time.
15419     *
15420     * @param who the recipient of the action
15421     * @param what the action to run on the drawable
15422     * @param when the time at which the action must occur. Uses the
15423     *        {@link SystemClock#uptimeMillis} timebase.
15424     */
15425    @Override
15426    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15427        if (verifyDrawable(who) && what != null) {
15428            final long delay = when - SystemClock.uptimeMillis();
15429            if (mAttachInfo != null) {
15430                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15431                        Choreographer.CALLBACK_ANIMATION, what, who,
15432                        Choreographer.subtractFrameDelay(delay));
15433            } else {
15434                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15435            }
15436        }
15437    }
15438
15439    /**
15440     * Cancels a scheduled action on a drawable.
15441     *
15442     * @param who the recipient of the action
15443     * @param what the action to cancel
15444     */
15445    @Override
15446    public void unscheduleDrawable(Drawable who, Runnable what) {
15447        if (verifyDrawable(who) && what != null) {
15448            if (mAttachInfo != null) {
15449                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15450                        Choreographer.CALLBACK_ANIMATION, what, who);
15451            }
15452            ViewRootImpl.getRunQueue().removeCallbacks(what);
15453        }
15454    }
15455
15456    /**
15457     * Unschedule any events associated with the given Drawable.  This can be
15458     * used when selecting a new Drawable into a view, so that the previous
15459     * one is completely unscheduled.
15460     *
15461     * @param who The Drawable to unschedule.
15462     *
15463     * @see #drawableStateChanged
15464     */
15465    public void unscheduleDrawable(Drawable who) {
15466        if (mAttachInfo != null && who != null) {
15467            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15468                    Choreographer.CALLBACK_ANIMATION, null, who);
15469        }
15470    }
15471
15472    /**
15473     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15474     * that the View directionality can and will be resolved before its Drawables.
15475     *
15476     * Will call {@link View#onResolveDrawables} when resolution is done.
15477     *
15478     * @hide
15479     */
15480    protected void resolveDrawables() {
15481        // Drawables resolution may need to happen before resolving the layout direction (which is
15482        // done only during the measure() call).
15483        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15484        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15485        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15486        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15487        // direction to be resolved as its resolved value will be the same as its raw value.
15488        if (!isLayoutDirectionResolved() &&
15489                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15490            return;
15491        }
15492
15493        final int layoutDirection = isLayoutDirectionResolved() ?
15494                getLayoutDirection() : getRawLayoutDirection();
15495
15496        if (mBackground != null) {
15497            mBackground.setLayoutDirection(layoutDirection);
15498        }
15499        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15500        onResolveDrawables(layoutDirection);
15501    }
15502
15503    /**
15504     * Called when layout direction has been resolved.
15505     *
15506     * The default implementation does nothing.
15507     *
15508     * @param layoutDirection The resolved layout direction.
15509     *
15510     * @see #LAYOUT_DIRECTION_LTR
15511     * @see #LAYOUT_DIRECTION_RTL
15512     *
15513     * @hide
15514     */
15515    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15516    }
15517
15518    /**
15519     * @hide
15520     */
15521    protected void resetResolvedDrawables() {
15522        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15523    }
15524
15525    private boolean isDrawablesResolved() {
15526        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15527    }
15528
15529    /**
15530     * If your view subclass is displaying its own Drawable objects, it should
15531     * override this function and return true for any Drawable it is
15532     * displaying.  This allows animations for those drawables to be
15533     * scheduled.
15534     *
15535     * <p>Be sure to call through to the super class when overriding this
15536     * function.
15537     *
15538     * @param who The Drawable to verify.  Return true if it is one you are
15539     *            displaying, else return the result of calling through to the
15540     *            super class.
15541     *
15542     * @return boolean If true than the Drawable is being displayed in the
15543     *         view; else false and it is not allowed to animate.
15544     *
15545     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15546     * @see #drawableStateChanged()
15547     */
15548    protected boolean verifyDrawable(Drawable who) {
15549        return who == mBackground;
15550    }
15551
15552    /**
15553     * This function is called whenever the state of the view changes in such
15554     * a way that it impacts the state of drawables being shown.
15555     * <p>
15556     * If the View has a StateListAnimator, it will also be called to run necessary state
15557     * change animations.
15558     * <p>
15559     * Be sure to call through to the superclass when overriding this function.
15560     *
15561     * @see Drawable#setState(int[])
15562     */
15563    protected void drawableStateChanged() {
15564        final Drawable d = mBackground;
15565        if (d != null && d.isStateful()) {
15566            d.setState(getDrawableState());
15567        }
15568
15569        if (mStateListAnimator != null) {
15570            mStateListAnimator.setState(getDrawableState());
15571        }
15572    }
15573
15574    /**
15575     * This function is called whenever the drawable hotspot changes.
15576     * <p>
15577     * Be sure to call through to the superclass when overriding this function.
15578     *
15579     * @param x hotspot x coordinate
15580     * @param y hotspot y coordinate
15581     */
15582    public void drawableHotspotChanged(float x, float y) {
15583        if (mBackground != null) {
15584            mBackground.setHotspot(x, y);
15585        }
15586    }
15587
15588    /**
15589     * Call this to force a view to update its drawable state. This will cause
15590     * drawableStateChanged to be called on this view. Views that are interested
15591     * in the new state should call getDrawableState.
15592     *
15593     * @see #drawableStateChanged
15594     * @see #getDrawableState
15595     */
15596    public void refreshDrawableState() {
15597        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15598        drawableStateChanged();
15599
15600        ViewParent parent = mParent;
15601        if (parent != null) {
15602            parent.childDrawableStateChanged(this);
15603        }
15604    }
15605
15606    /**
15607     * Return an array of resource IDs of the drawable states representing the
15608     * current state of the view.
15609     *
15610     * @return The current drawable state
15611     *
15612     * @see Drawable#setState(int[])
15613     * @see #drawableStateChanged()
15614     * @see #onCreateDrawableState(int)
15615     */
15616    public final int[] getDrawableState() {
15617        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15618            return mDrawableState;
15619        } else {
15620            mDrawableState = onCreateDrawableState(0);
15621            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15622            return mDrawableState;
15623        }
15624    }
15625
15626    /**
15627     * Generate the new {@link android.graphics.drawable.Drawable} state for
15628     * this view. This is called by the view
15629     * system when the cached Drawable state is determined to be invalid.  To
15630     * retrieve the current state, you should use {@link #getDrawableState}.
15631     *
15632     * @param extraSpace if non-zero, this is the number of extra entries you
15633     * would like in the returned array in which you can place your own
15634     * states.
15635     *
15636     * @return Returns an array holding the current {@link Drawable} state of
15637     * the view.
15638     *
15639     * @see #mergeDrawableStates(int[], int[])
15640     */
15641    protected int[] onCreateDrawableState(int extraSpace) {
15642        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15643                mParent instanceof View) {
15644            return ((View) mParent).onCreateDrawableState(extraSpace);
15645        }
15646
15647        int[] drawableState;
15648
15649        int privateFlags = mPrivateFlags;
15650
15651        int viewStateIndex = 0;
15652        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15653        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15654        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15655        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15656        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15657        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15658        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15659                HardwareRenderer.isAvailable()) {
15660            // This is set if HW acceleration is requested, even if the current
15661            // process doesn't allow it.  This is just to allow app preview
15662            // windows to better match their app.
15663            viewStateIndex |= VIEW_STATE_ACCELERATED;
15664        }
15665        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15666
15667        final int privateFlags2 = mPrivateFlags2;
15668        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15669        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15670
15671        drawableState = VIEW_STATE_SETS[viewStateIndex];
15672
15673        //noinspection ConstantIfStatement
15674        if (false) {
15675            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15676            Log.i("View", toString()
15677                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15678                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15679                    + " fo=" + hasFocus()
15680                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15681                    + " wf=" + hasWindowFocus()
15682                    + ": " + Arrays.toString(drawableState));
15683        }
15684
15685        if (extraSpace == 0) {
15686            return drawableState;
15687        }
15688
15689        final int[] fullState;
15690        if (drawableState != null) {
15691            fullState = new int[drawableState.length + extraSpace];
15692            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15693        } else {
15694            fullState = new int[extraSpace];
15695        }
15696
15697        return fullState;
15698    }
15699
15700    /**
15701     * Merge your own state values in <var>additionalState</var> into the base
15702     * state values <var>baseState</var> that were returned by
15703     * {@link #onCreateDrawableState(int)}.
15704     *
15705     * @param baseState The base state values returned by
15706     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15707     * own additional state values.
15708     *
15709     * @param additionalState The additional state values you would like
15710     * added to <var>baseState</var>; this array is not modified.
15711     *
15712     * @return As a convenience, the <var>baseState</var> array you originally
15713     * passed into the function is returned.
15714     *
15715     * @see #onCreateDrawableState(int)
15716     */
15717    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15718        final int N = baseState.length;
15719        int i = N - 1;
15720        while (i >= 0 && baseState[i] == 0) {
15721            i--;
15722        }
15723        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15724        return baseState;
15725    }
15726
15727    /**
15728     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15729     * on all Drawable objects associated with this view.
15730     * <p>
15731     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15732     * attached to this view.
15733     */
15734    public void jumpDrawablesToCurrentState() {
15735        if (mBackground != null) {
15736            mBackground.jumpToCurrentState();
15737        }
15738        if (mStateListAnimator != null) {
15739            mStateListAnimator.jumpToCurrentState();
15740        }
15741    }
15742
15743    /**
15744     * Sets the background color for this view.
15745     * @param color the color of the background
15746     */
15747    @RemotableViewMethod
15748    public void setBackgroundColor(int color) {
15749        if (mBackground instanceof ColorDrawable) {
15750            ((ColorDrawable) mBackground.mutate()).setColor(color);
15751            computeOpaqueFlags();
15752            mBackgroundResource = 0;
15753        } else {
15754            setBackground(new ColorDrawable(color));
15755        }
15756    }
15757
15758    /**
15759     * Set the background to a given resource. The resource should refer to
15760     * a Drawable object or 0 to remove the background.
15761     * @param resid The identifier of the resource.
15762     *
15763     * @attr ref android.R.styleable#View_background
15764     */
15765    @RemotableViewMethod
15766    public void setBackgroundResource(int resid) {
15767        if (resid != 0 && resid == mBackgroundResource) {
15768            return;
15769        }
15770
15771        Drawable d = null;
15772        if (resid != 0) {
15773            d = mContext.getDrawable(resid);
15774        }
15775        setBackground(d);
15776
15777        mBackgroundResource = resid;
15778    }
15779
15780    /**
15781     * Set the background to a given Drawable, or remove the background. If the
15782     * background has padding, this View's padding is set to the background's
15783     * padding. However, when a background is removed, this View's padding isn't
15784     * touched. If setting the padding is desired, please use
15785     * {@link #setPadding(int, int, int, int)}.
15786     *
15787     * @param background The Drawable to use as the background, or null to remove the
15788     *        background
15789     */
15790    public void setBackground(Drawable background) {
15791        //noinspection deprecation
15792        setBackgroundDrawable(background);
15793    }
15794
15795    /**
15796     * @deprecated use {@link #setBackground(Drawable)} instead
15797     */
15798    @Deprecated
15799    public void setBackgroundDrawable(Drawable background) {
15800        computeOpaqueFlags();
15801
15802        if (background == mBackground) {
15803            return;
15804        }
15805
15806        boolean requestLayout = false;
15807
15808        mBackgroundResource = 0;
15809
15810        /*
15811         * Regardless of whether we're setting a new background or not, we want
15812         * to clear the previous drawable.
15813         */
15814        if (mBackground != null) {
15815            mBackground.setCallback(null);
15816            unscheduleDrawable(mBackground);
15817        }
15818
15819        if (background != null) {
15820            Rect padding = sThreadLocal.get();
15821            if (padding == null) {
15822                padding = new Rect();
15823                sThreadLocal.set(padding);
15824            }
15825            resetResolvedDrawables();
15826            background.setLayoutDirection(getLayoutDirection());
15827            if (background.getPadding(padding)) {
15828                resetResolvedPadding();
15829                switch (background.getLayoutDirection()) {
15830                    case LAYOUT_DIRECTION_RTL:
15831                        mUserPaddingLeftInitial = padding.right;
15832                        mUserPaddingRightInitial = padding.left;
15833                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15834                        break;
15835                    case LAYOUT_DIRECTION_LTR:
15836                    default:
15837                        mUserPaddingLeftInitial = padding.left;
15838                        mUserPaddingRightInitial = padding.right;
15839                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15840                }
15841                mLeftPaddingDefined = false;
15842                mRightPaddingDefined = false;
15843            }
15844
15845            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15846            // if it has a different minimum size, we should layout again
15847            if (mBackground == null
15848                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15849                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15850                requestLayout = true;
15851            }
15852
15853            background.setCallback(this);
15854            if (background.isStateful()) {
15855                background.setState(getDrawableState());
15856            }
15857            background.setVisible(getVisibility() == VISIBLE, false);
15858            mBackground = background;
15859
15860            applyBackgroundTint();
15861
15862            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15863                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15864                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15865                requestLayout = true;
15866            }
15867        } else {
15868            /* Remove the background */
15869            mBackground = null;
15870
15871            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15872                /*
15873                 * This view ONLY drew the background before and we're removing
15874                 * the background, so now it won't draw anything
15875                 * (hence we SKIP_DRAW)
15876                 */
15877                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15878                mPrivateFlags |= PFLAG_SKIP_DRAW;
15879            }
15880
15881            /*
15882             * When the background is set, we try to apply its padding to this
15883             * View. When the background is removed, we don't touch this View's
15884             * padding. This is noted in the Javadocs. Hence, we don't need to
15885             * requestLayout(), the invalidate() below is sufficient.
15886             */
15887
15888            // The old background's minimum size could have affected this
15889            // View's layout, so let's requestLayout
15890            requestLayout = true;
15891        }
15892
15893        computeOpaqueFlags();
15894
15895        if (requestLayout) {
15896            requestLayout();
15897        }
15898
15899        mBackgroundSizeChanged = true;
15900        invalidate(true);
15901    }
15902
15903    /**
15904     * Gets the background drawable
15905     *
15906     * @return The drawable used as the background for this view, if any.
15907     *
15908     * @see #setBackground(Drawable)
15909     *
15910     * @attr ref android.R.styleable#View_background
15911     */
15912    public Drawable getBackground() {
15913        return mBackground;
15914    }
15915
15916    /**
15917     * Applies a tint to the background drawable.
15918     * <p>
15919     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15920     * mutate the drawable and apply the specified tint and tint mode using
15921     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15922     *
15923     * @param tint the tint to apply, may be {@code null} to clear tint
15924     * @param tintMode the blending mode used to apply the tint, may be
15925     *                 {@code null} to clear tint
15926     *
15927     * @attr ref android.R.styleable#View_backgroundTint
15928     * @attr ref android.R.styleable#View_backgroundTintMode
15929     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15930     */
15931    private void setBackgroundTint(@Nullable ColorStateList tint,
15932            @Nullable PorterDuff.Mode tintMode) {
15933        mBackgroundTint = tint;
15934        mBackgroundTintMode = tintMode;
15935        mHasBackgroundTint = true;
15936
15937        applyBackgroundTint();
15938    }
15939
15940    /**
15941     * Applies a tint to the background drawable. Does not modify the current tint
15942     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15943     * <p>
15944     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15945     * mutate the drawable and apply the specified tint and tint mode using
15946     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15947     *
15948     * @param tint the tint to apply, may be {@code null} to clear tint
15949     *
15950     * @attr ref android.R.styleable#View_backgroundTint
15951     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15952     */
15953    public void setBackgroundTint(@Nullable ColorStateList tint) {
15954        setBackgroundTint(tint, mBackgroundTintMode);
15955    }
15956
15957    /**
15958     * @return the tint applied to the background drawable
15959     * @attr ref android.R.styleable#View_backgroundTint
15960     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15961     */
15962    @Nullable
15963    public ColorStateList getBackgroundTint() {
15964        return mBackgroundTint;
15965    }
15966
15967    /**
15968     * Specifies the blending mode used to apply the tint specified by
15969     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15970     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15971     *
15972     * @param tintMode the blending mode used to apply the tint, may be
15973     *                 {@code null} to clear tint
15974     * @attr ref android.R.styleable#View_backgroundTintMode
15975     * @see #setBackgroundTint(ColorStateList)
15976     */
15977    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15978        setBackgroundTint(mBackgroundTint, tintMode);
15979    }
15980
15981    /**
15982     * @return the blending mode used to apply the tint to the background drawable
15983     * @attr ref android.R.styleable#View_backgroundTintMode
15984     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15985     */
15986    @Nullable
15987    public PorterDuff.Mode getBackgroundTintMode() {
15988        return mBackgroundTintMode;
15989    }
15990
15991    private void applyBackgroundTint() {
15992        if (mBackground != null && mHasBackgroundTint) {
15993            mBackground = mBackground.mutate();
15994            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15995        }
15996    }
15997
15998    /**
15999     * Sets the padding. The view may add on the space required to display
16000     * the scrollbars, depending on the style and visibility of the scrollbars.
16001     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16002     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16003     * from the values set in this call.
16004     *
16005     * @attr ref android.R.styleable#View_padding
16006     * @attr ref android.R.styleable#View_paddingBottom
16007     * @attr ref android.R.styleable#View_paddingLeft
16008     * @attr ref android.R.styleable#View_paddingRight
16009     * @attr ref android.R.styleable#View_paddingTop
16010     * @param left the left padding in pixels
16011     * @param top the top padding in pixels
16012     * @param right the right padding in pixels
16013     * @param bottom the bottom padding in pixels
16014     */
16015    public void setPadding(int left, int top, int right, int bottom) {
16016        resetResolvedPadding();
16017
16018        mUserPaddingStart = UNDEFINED_PADDING;
16019        mUserPaddingEnd = UNDEFINED_PADDING;
16020
16021        mUserPaddingLeftInitial = left;
16022        mUserPaddingRightInitial = right;
16023
16024        mLeftPaddingDefined = true;
16025        mRightPaddingDefined = true;
16026
16027        internalSetPadding(left, top, right, bottom);
16028    }
16029
16030    /**
16031     * @hide
16032     */
16033    protected void internalSetPadding(int left, int top, int right, int bottom) {
16034        mUserPaddingLeft = left;
16035        mUserPaddingRight = right;
16036        mUserPaddingBottom = bottom;
16037
16038        final int viewFlags = mViewFlags;
16039        boolean changed = false;
16040
16041        // Common case is there are no scroll bars.
16042        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16043            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16044                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16045                        ? 0 : getVerticalScrollbarWidth();
16046                switch (mVerticalScrollbarPosition) {
16047                    case SCROLLBAR_POSITION_DEFAULT:
16048                        if (isLayoutRtl()) {
16049                            left += offset;
16050                        } else {
16051                            right += offset;
16052                        }
16053                        break;
16054                    case SCROLLBAR_POSITION_RIGHT:
16055                        right += offset;
16056                        break;
16057                    case SCROLLBAR_POSITION_LEFT:
16058                        left += offset;
16059                        break;
16060                }
16061            }
16062            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16063                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16064                        ? 0 : getHorizontalScrollbarHeight();
16065            }
16066        }
16067
16068        if (mPaddingLeft != left) {
16069            changed = true;
16070            mPaddingLeft = left;
16071        }
16072        if (mPaddingTop != top) {
16073            changed = true;
16074            mPaddingTop = top;
16075        }
16076        if (mPaddingRight != right) {
16077            changed = true;
16078            mPaddingRight = right;
16079        }
16080        if (mPaddingBottom != bottom) {
16081            changed = true;
16082            mPaddingBottom = bottom;
16083        }
16084
16085        if (changed) {
16086            requestLayout();
16087        }
16088    }
16089
16090    /**
16091     * Sets the relative padding. The view may add on the space required to display
16092     * the scrollbars, depending on the style and visibility of the scrollbars.
16093     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16094     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16095     * from the values set in this call.
16096     *
16097     * @attr ref android.R.styleable#View_padding
16098     * @attr ref android.R.styleable#View_paddingBottom
16099     * @attr ref android.R.styleable#View_paddingStart
16100     * @attr ref android.R.styleable#View_paddingEnd
16101     * @attr ref android.R.styleable#View_paddingTop
16102     * @param start the start padding in pixels
16103     * @param top the top padding in pixels
16104     * @param end the end padding in pixels
16105     * @param bottom the bottom padding in pixels
16106     */
16107    public void setPaddingRelative(int start, int top, int end, int bottom) {
16108        resetResolvedPadding();
16109
16110        mUserPaddingStart = start;
16111        mUserPaddingEnd = end;
16112        mLeftPaddingDefined = true;
16113        mRightPaddingDefined = true;
16114
16115        switch(getLayoutDirection()) {
16116            case LAYOUT_DIRECTION_RTL:
16117                mUserPaddingLeftInitial = end;
16118                mUserPaddingRightInitial = start;
16119                internalSetPadding(end, top, start, bottom);
16120                break;
16121            case LAYOUT_DIRECTION_LTR:
16122            default:
16123                mUserPaddingLeftInitial = start;
16124                mUserPaddingRightInitial = end;
16125                internalSetPadding(start, top, end, bottom);
16126        }
16127    }
16128
16129    /**
16130     * Returns the top padding of this view.
16131     *
16132     * @return the top padding in pixels
16133     */
16134    public int getPaddingTop() {
16135        return mPaddingTop;
16136    }
16137
16138    /**
16139     * Returns the bottom padding of this view. If there are inset and enabled
16140     * scrollbars, this value may include the space required to display the
16141     * scrollbars as well.
16142     *
16143     * @return the bottom padding in pixels
16144     */
16145    public int getPaddingBottom() {
16146        return mPaddingBottom;
16147    }
16148
16149    /**
16150     * Returns the left padding of this view. If there are inset and enabled
16151     * scrollbars, this value may include the space required to display the
16152     * scrollbars as well.
16153     *
16154     * @return the left padding in pixels
16155     */
16156    public int getPaddingLeft() {
16157        if (!isPaddingResolved()) {
16158            resolvePadding();
16159        }
16160        return mPaddingLeft;
16161    }
16162
16163    /**
16164     * Returns the start padding of this view depending on its resolved layout direction.
16165     * If there are inset and enabled scrollbars, this value may include the space
16166     * required to display the scrollbars as well.
16167     *
16168     * @return the start padding in pixels
16169     */
16170    public int getPaddingStart() {
16171        if (!isPaddingResolved()) {
16172            resolvePadding();
16173        }
16174        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16175                mPaddingRight : mPaddingLeft;
16176    }
16177
16178    /**
16179     * Returns the right padding of this view. If there are inset and enabled
16180     * scrollbars, this value may include the space required to display the
16181     * scrollbars as well.
16182     *
16183     * @return the right padding in pixels
16184     */
16185    public int getPaddingRight() {
16186        if (!isPaddingResolved()) {
16187            resolvePadding();
16188        }
16189        return mPaddingRight;
16190    }
16191
16192    /**
16193     * Returns the end padding of this view depending on its resolved layout direction.
16194     * If there are inset and enabled scrollbars, this value may include the space
16195     * required to display the scrollbars as well.
16196     *
16197     * @return the end padding in pixels
16198     */
16199    public int getPaddingEnd() {
16200        if (!isPaddingResolved()) {
16201            resolvePadding();
16202        }
16203        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16204                mPaddingLeft : mPaddingRight;
16205    }
16206
16207    /**
16208     * Return if the padding as been set thru relative values
16209     * {@link #setPaddingRelative(int, int, int, int)} or thru
16210     * @attr ref android.R.styleable#View_paddingStart or
16211     * @attr ref android.R.styleable#View_paddingEnd
16212     *
16213     * @return true if the padding is relative or false if it is not.
16214     */
16215    public boolean isPaddingRelative() {
16216        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16217    }
16218
16219    Insets computeOpticalInsets() {
16220        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16221    }
16222
16223    /**
16224     * @hide
16225     */
16226    public void resetPaddingToInitialValues() {
16227        if (isRtlCompatibilityMode()) {
16228            mPaddingLeft = mUserPaddingLeftInitial;
16229            mPaddingRight = mUserPaddingRightInitial;
16230            return;
16231        }
16232        if (isLayoutRtl()) {
16233            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16234            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16235        } else {
16236            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16237            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16238        }
16239    }
16240
16241    /**
16242     * @hide
16243     */
16244    public Insets getOpticalInsets() {
16245        if (mLayoutInsets == null) {
16246            mLayoutInsets = computeOpticalInsets();
16247        }
16248        return mLayoutInsets;
16249    }
16250
16251    /**
16252     * Set this view's optical insets.
16253     *
16254     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16255     * property. Views that compute their own optical insets should call it as part of measurement.
16256     * This method does not request layout. If you are setting optical insets outside of
16257     * measure/layout itself you will want to call requestLayout() yourself.
16258     * </p>
16259     * @hide
16260     */
16261    public void setOpticalInsets(Insets insets) {
16262        mLayoutInsets = insets;
16263    }
16264
16265    /**
16266     * Changes the selection state of this view. A view can be selected or not.
16267     * Note that selection is not the same as focus. Views are typically
16268     * selected in the context of an AdapterView like ListView or GridView;
16269     * the selected view is the view that is highlighted.
16270     *
16271     * @param selected true if the view must be selected, false otherwise
16272     */
16273    public void setSelected(boolean selected) {
16274        //noinspection DoubleNegation
16275        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16276            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16277            if (!selected) resetPressedState();
16278            invalidate(true);
16279            refreshDrawableState();
16280            dispatchSetSelected(selected);
16281            notifyViewAccessibilityStateChangedIfNeeded(
16282                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16283        }
16284    }
16285
16286    /**
16287     * Dispatch setSelected to all of this View's children.
16288     *
16289     * @see #setSelected(boolean)
16290     *
16291     * @param selected The new selected state
16292     */
16293    protected void dispatchSetSelected(boolean selected) {
16294    }
16295
16296    /**
16297     * Indicates the selection state of this view.
16298     *
16299     * @return true if the view is selected, false otherwise
16300     */
16301    @ViewDebug.ExportedProperty
16302    public boolean isSelected() {
16303        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16304    }
16305
16306    /**
16307     * Changes the activated state of this view. A view can be activated or not.
16308     * Note that activation is not the same as selection.  Selection is
16309     * a transient property, representing the view (hierarchy) the user is
16310     * currently interacting with.  Activation is a longer-term state that the
16311     * user can move views in and out of.  For example, in a list view with
16312     * single or multiple selection enabled, the views in the current selection
16313     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16314     * here.)  The activated state is propagated down to children of the view it
16315     * is set on.
16316     *
16317     * @param activated true if the view must be activated, false otherwise
16318     */
16319    public void setActivated(boolean activated) {
16320        //noinspection DoubleNegation
16321        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16322            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16323            invalidate(true);
16324            refreshDrawableState();
16325            dispatchSetActivated(activated);
16326        }
16327    }
16328
16329    /**
16330     * Dispatch setActivated to all of this View's children.
16331     *
16332     * @see #setActivated(boolean)
16333     *
16334     * @param activated The new activated state
16335     */
16336    protected void dispatchSetActivated(boolean activated) {
16337    }
16338
16339    /**
16340     * Indicates the activation state of this view.
16341     *
16342     * @return true if the view is activated, false otherwise
16343     */
16344    @ViewDebug.ExportedProperty
16345    public boolean isActivated() {
16346        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16347    }
16348
16349    /**
16350     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16351     * observer can be used to get notifications when global events, like
16352     * layout, happen.
16353     *
16354     * The returned ViewTreeObserver observer is not guaranteed to remain
16355     * valid for the lifetime of this View. If the caller of this method keeps
16356     * a long-lived reference to ViewTreeObserver, it should always check for
16357     * the return value of {@link ViewTreeObserver#isAlive()}.
16358     *
16359     * @return The ViewTreeObserver for this view's hierarchy.
16360     */
16361    public ViewTreeObserver getViewTreeObserver() {
16362        if (mAttachInfo != null) {
16363            return mAttachInfo.mTreeObserver;
16364        }
16365        if (mFloatingTreeObserver == null) {
16366            mFloatingTreeObserver = new ViewTreeObserver();
16367        }
16368        return mFloatingTreeObserver;
16369    }
16370
16371    /**
16372     * <p>Finds the topmost view in the current view hierarchy.</p>
16373     *
16374     * @return the topmost view containing this view
16375     */
16376    public View getRootView() {
16377        if (mAttachInfo != null) {
16378            final View v = mAttachInfo.mRootView;
16379            if (v != null) {
16380                return v;
16381            }
16382        }
16383
16384        View parent = this;
16385
16386        while (parent.mParent != null && parent.mParent instanceof View) {
16387            parent = (View) parent.mParent;
16388        }
16389
16390        return parent;
16391    }
16392
16393    /**
16394     * Transforms a motion event from view-local coordinates to on-screen
16395     * coordinates.
16396     *
16397     * @param ev the view-local motion event
16398     * @return false if the transformation could not be applied
16399     * @hide
16400     */
16401    public boolean toGlobalMotionEvent(MotionEvent ev) {
16402        final AttachInfo info = mAttachInfo;
16403        if (info == null) {
16404            return false;
16405        }
16406
16407        final Matrix m = info.mTmpMatrix;
16408        m.set(Matrix.IDENTITY_MATRIX);
16409        transformMatrixToGlobal(m);
16410        ev.transform(m);
16411        return true;
16412    }
16413
16414    /**
16415     * Transforms a motion event from on-screen coordinates to view-local
16416     * coordinates.
16417     *
16418     * @param ev the on-screen motion event
16419     * @return false if the transformation could not be applied
16420     * @hide
16421     */
16422    public boolean toLocalMotionEvent(MotionEvent ev) {
16423        final AttachInfo info = mAttachInfo;
16424        if (info == null) {
16425            return false;
16426        }
16427
16428        final Matrix m = info.mTmpMatrix;
16429        m.set(Matrix.IDENTITY_MATRIX);
16430        transformMatrixToLocal(m);
16431        ev.transform(m);
16432        return true;
16433    }
16434
16435    /**
16436     * Modifies the input matrix such that it maps view-local coordinates to
16437     * on-screen coordinates.
16438     *
16439     * @param m input matrix to modify
16440     */
16441    void transformMatrixToGlobal(Matrix m) {
16442        final ViewParent parent = mParent;
16443        if (parent instanceof View) {
16444            final View vp = (View) parent;
16445            vp.transformMatrixToGlobal(m);
16446            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16447        } else if (parent instanceof ViewRootImpl) {
16448            final ViewRootImpl vr = (ViewRootImpl) parent;
16449            vr.transformMatrixToGlobal(m);
16450            m.postTranslate(0, -vr.mCurScrollY);
16451        }
16452
16453        m.postTranslate(mLeft, mTop);
16454
16455        if (!hasIdentityMatrix()) {
16456            m.postConcat(getMatrix());
16457        }
16458    }
16459
16460    /**
16461     * Modifies the input matrix such that it maps on-screen coordinates to
16462     * view-local coordinates.
16463     *
16464     * @param m input matrix to modify
16465     */
16466    void transformMatrixToLocal(Matrix m) {
16467        final ViewParent parent = mParent;
16468        if (parent instanceof View) {
16469            final View vp = (View) parent;
16470            vp.transformMatrixToLocal(m);
16471            m.preTranslate(vp.mScrollX, vp.mScrollY);
16472        } else if (parent instanceof ViewRootImpl) {
16473            final ViewRootImpl vr = (ViewRootImpl) parent;
16474            vr.transformMatrixToLocal(m);
16475            m.preTranslate(0, vr.mCurScrollY);
16476        }
16477
16478        m.preTranslate(-mLeft, -mTop);
16479
16480        if (!hasIdentityMatrix()) {
16481            m.preConcat(getInverseMatrix());
16482        }
16483    }
16484
16485    /**
16486     * <p>Computes the coordinates of this view on the screen. The argument
16487     * must be an array of two integers. After the method returns, the array
16488     * contains the x and y location in that order.</p>
16489     *
16490     * @param location an array of two integers in which to hold the coordinates
16491     */
16492    public void getLocationOnScreen(int[] location) {
16493        getLocationInWindow(location);
16494
16495        final AttachInfo info = mAttachInfo;
16496        if (info != null) {
16497            location[0] += info.mWindowLeft;
16498            location[1] += info.mWindowTop;
16499        }
16500    }
16501
16502    /**
16503     * <p>Computes the coordinates of this view in its window. The argument
16504     * must be an array of two integers. After the method returns, the array
16505     * contains the x and y location in that order.</p>
16506     *
16507     * @param location an array of two integers in which to hold the coordinates
16508     */
16509    public void getLocationInWindow(int[] location) {
16510        if (location == null || location.length < 2) {
16511            throw new IllegalArgumentException("location must be an array of two integers");
16512        }
16513
16514        if (mAttachInfo == null) {
16515            // When the view is not attached to a window, this method does not make sense
16516            location[0] = location[1] = 0;
16517            return;
16518        }
16519
16520        float[] position = mAttachInfo.mTmpTransformLocation;
16521        position[0] = position[1] = 0.0f;
16522
16523        if (!hasIdentityMatrix()) {
16524            getMatrix().mapPoints(position);
16525        }
16526
16527        position[0] += mLeft;
16528        position[1] += mTop;
16529
16530        ViewParent viewParent = mParent;
16531        while (viewParent instanceof View) {
16532            final View view = (View) viewParent;
16533
16534            position[0] -= view.mScrollX;
16535            position[1] -= view.mScrollY;
16536
16537            if (!view.hasIdentityMatrix()) {
16538                view.getMatrix().mapPoints(position);
16539            }
16540
16541            position[0] += view.mLeft;
16542            position[1] += view.mTop;
16543
16544            viewParent = view.mParent;
16545         }
16546
16547        if (viewParent instanceof ViewRootImpl) {
16548            // *cough*
16549            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16550            position[1] -= vr.mCurScrollY;
16551        }
16552
16553        location[0] = (int) (position[0] + 0.5f);
16554        location[1] = (int) (position[1] + 0.5f);
16555    }
16556
16557    /**
16558     * {@hide}
16559     * @param id the id of the view to be found
16560     * @return the view of the specified id, null if cannot be found
16561     */
16562    protected View findViewTraversal(int id) {
16563        if (id == mID) {
16564            return this;
16565        }
16566        return null;
16567    }
16568
16569    /**
16570     * {@hide}
16571     * @param tag the tag of the view to be found
16572     * @return the view of specified tag, null if cannot be found
16573     */
16574    protected View findViewWithTagTraversal(Object tag) {
16575        if (tag != null && tag.equals(mTag)) {
16576            return this;
16577        }
16578        return null;
16579    }
16580
16581    /**
16582     * {@hide}
16583     * @param predicate The predicate to evaluate.
16584     * @param childToSkip If not null, ignores this child during the recursive traversal.
16585     * @return The first view that matches the predicate or null.
16586     */
16587    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16588        if (predicate.apply(this)) {
16589            return this;
16590        }
16591        return null;
16592    }
16593
16594    /**
16595     * Look for a child view with the given id.  If this view has the given
16596     * id, return this view.
16597     *
16598     * @param id The id to search for.
16599     * @return The view that has the given id in the hierarchy or null
16600     */
16601    public final View findViewById(int id) {
16602        if (id < 0) {
16603            return null;
16604        }
16605        return findViewTraversal(id);
16606    }
16607
16608    /**
16609     * Finds a view by its unuque and stable accessibility id.
16610     *
16611     * @param accessibilityId The searched accessibility id.
16612     * @return The found view.
16613     */
16614    final View findViewByAccessibilityId(int accessibilityId) {
16615        if (accessibilityId < 0) {
16616            return null;
16617        }
16618        return findViewByAccessibilityIdTraversal(accessibilityId);
16619    }
16620
16621    /**
16622     * Performs the traversal to find a view by its unuque and stable accessibility id.
16623     *
16624     * <strong>Note:</strong>This method does not stop at the root namespace
16625     * boundary since the user can touch the screen at an arbitrary location
16626     * potentially crossing the root namespace bounday which will send an
16627     * accessibility event to accessibility services and they should be able
16628     * to obtain the event source. Also accessibility ids are guaranteed to be
16629     * unique in the window.
16630     *
16631     * @param accessibilityId The accessibility id.
16632     * @return The found view.
16633     *
16634     * @hide
16635     */
16636    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16637        if (getAccessibilityViewId() == accessibilityId) {
16638            return this;
16639        }
16640        return null;
16641    }
16642
16643    /**
16644     * Look for a child view with the given tag.  If this view has the given
16645     * tag, return this view.
16646     *
16647     * @param tag The tag to search for, using "tag.equals(getTag())".
16648     * @return The View that has the given tag in the hierarchy or null
16649     */
16650    public final View findViewWithTag(Object tag) {
16651        if (tag == null) {
16652            return null;
16653        }
16654        return findViewWithTagTraversal(tag);
16655    }
16656
16657    /**
16658     * {@hide}
16659     * Look for a child view that matches the specified predicate.
16660     * If this view matches the predicate, return this view.
16661     *
16662     * @param predicate The predicate to evaluate.
16663     * @return The first view that matches the predicate or null.
16664     */
16665    public final View findViewByPredicate(Predicate<View> predicate) {
16666        return findViewByPredicateTraversal(predicate, null);
16667    }
16668
16669    /**
16670     * {@hide}
16671     * Look for a child view that matches the specified predicate,
16672     * starting with the specified view and its descendents and then
16673     * recusively searching the ancestors and siblings of that view
16674     * until this view is reached.
16675     *
16676     * This method is useful in cases where the predicate does not match
16677     * a single unique view (perhaps multiple views use the same id)
16678     * and we are trying to find the view that is "closest" in scope to the
16679     * starting view.
16680     *
16681     * @param start The view to start from.
16682     * @param predicate The predicate to evaluate.
16683     * @return The first view that matches the predicate or null.
16684     */
16685    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16686        View childToSkip = null;
16687        for (;;) {
16688            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16689            if (view != null || start == this) {
16690                return view;
16691            }
16692
16693            ViewParent parent = start.getParent();
16694            if (parent == null || !(parent instanceof View)) {
16695                return null;
16696            }
16697
16698            childToSkip = start;
16699            start = (View) parent;
16700        }
16701    }
16702
16703    /**
16704     * Sets the identifier for this view. The identifier does not have to be
16705     * unique in this view's hierarchy. The identifier should be a positive
16706     * number.
16707     *
16708     * @see #NO_ID
16709     * @see #getId()
16710     * @see #findViewById(int)
16711     *
16712     * @param id a number used to identify the view
16713     *
16714     * @attr ref android.R.styleable#View_id
16715     */
16716    public void setId(int id) {
16717        mID = id;
16718        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16719            mID = generateViewId();
16720        }
16721    }
16722
16723    /**
16724     * {@hide}
16725     *
16726     * @param isRoot true if the view belongs to the root namespace, false
16727     *        otherwise
16728     */
16729    public void setIsRootNamespace(boolean isRoot) {
16730        if (isRoot) {
16731            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16732        } else {
16733            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16734        }
16735    }
16736
16737    /**
16738     * {@hide}
16739     *
16740     * @return true if the view belongs to the root namespace, false otherwise
16741     */
16742    public boolean isRootNamespace() {
16743        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16744    }
16745
16746    /**
16747     * Returns this view's identifier.
16748     *
16749     * @return a positive integer used to identify the view or {@link #NO_ID}
16750     *         if the view has no ID
16751     *
16752     * @see #setId(int)
16753     * @see #findViewById(int)
16754     * @attr ref android.R.styleable#View_id
16755     */
16756    @ViewDebug.CapturedViewProperty
16757    public int getId() {
16758        return mID;
16759    }
16760
16761    /**
16762     * Returns this view's tag.
16763     *
16764     * @return the Object stored in this view as a tag, or {@code null} if not
16765     *         set
16766     *
16767     * @see #setTag(Object)
16768     * @see #getTag(int)
16769     */
16770    @ViewDebug.ExportedProperty
16771    public Object getTag() {
16772        return mTag;
16773    }
16774
16775    /**
16776     * Sets the tag associated with this view. A tag can be used to mark
16777     * a view in its hierarchy and does not have to be unique within the
16778     * hierarchy. Tags can also be used to store data within a view without
16779     * resorting to another data structure.
16780     *
16781     * @param tag an Object to tag the view with
16782     *
16783     * @see #getTag()
16784     * @see #setTag(int, Object)
16785     */
16786    public void setTag(final Object tag) {
16787        mTag = tag;
16788    }
16789
16790    /**
16791     * Returns the tag associated with this view and the specified key.
16792     *
16793     * @param key The key identifying the tag
16794     *
16795     * @return the Object stored in this view as a tag, or {@code null} if not
16796     *         set
16797     *
16798     * @see #setTag(int, Object)
16799     * @see #getTag()
16800     */
16801    public Object getTag(int key) {
16802        if (mKeyedTags != null) return mKeyedTags.get(key);
16803        return null;
16804    }
16805
16806    /**
16807     * Sets a tag associated with this view and a key. A tag can be used
16808     * to mark a view in its hierarchy and does not have to be unique within
16809     * the hierarchy. Tags can also be used to store data within a view
16810     * without resorting to another data structure.
16811     *
16812     * The specified key should be an id declared in the resources of the
16813     * application to ensure it is unique (see the <a
16814     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16815     * Keys identified as belonging to
16816     * the Android framework or not associated with any package will cause
16817     * an {@link IllegalArgumentException} to be thrown.
16818     *
16819     * @param key The key identifying the tag
16820     * @param tag An Object to tag the view with
16821     *
16822     * @throws IllegalArgumentException If they specified key is not valid
16823     *
16824     * @see #setTag(Object)
16825     * @see #getTag(int)
16826     */
16827    public void setTag(int key, final Object tag) {
16828        // If the package id is 0x00 or 0x01, it's either an undefined package
16829        // or a framework id
16830        if ((key >>> 24) < 2) {
16831            throw new IllegalArgumentException("The key must be an application-specific "
16832                    + "resource id.");
16833        }
16834
16835        setKeyedTag(key, tag);
16836    }
16837
16838    /**
16839     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16840     * framework id.
16841     *
16842     * @hide
16843     */
16844    public void setTagInternal(int key, Object tag) {
16845        if ((key >>> 24) != 0x1) {
16846            throw new IllegalArgumentException("The key must be a framework-specific "
16847                    + "resource id.");
16848        }
16849
16850        setKeyedTag(key, tag);
16851    }
16852
16853    private void setKeyedTag(int key, Object tag) {
16854        if (mKeyedTags == null) {
16855            mKeyedTags = new SparseArray<Object>(2);
16856        }
16857
16858        mKeyedTags.put(key, tag);
16859    }
16860
16861    /**
16862     * Prints information about this view in the log output, with the tag
16863     * {@link #VIEW_LOG_TAG}.
16864     *
16865     * @hide
16866     */
16867    public void debug() {
16868        debug(0);
16869    }
16870
16871    /**
16872     * Prints information about this view in the log output, with the tag
16873     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16874     * indentation defined by the <code>depth</code>.
16875     *
16876     * @param depth the indentation level
16877     *
16878     * @hide
16879     */
16880    protected void debug(int depth) {
16881        String output = debugIndent(depth - 1);
16882
16883        output += "+ " + this;
16884        int id = getId();
16885        if (id != -1) {
16886            output += " (id=" + id + ")";
16887        }
16888        Object tag = getTag();
16889        if (tag != null) {
16890            output += " (tag=" + tag + ")";
16891        }
16892        Log.d(VIEW_LOG_TAG, output);
16893
16894        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16895            output = debugIndent(depth) + " FOCUSED";
16896            Log.d(VIEW_LOG_TAG, output);
16897        }
16898
16899        output = debugIndent(depth);
16900        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16901                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16902                + "} ";
16903        Log.d(VIEW_LOG_TAG, output);
16904
16905        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16906                || mPaddingBottom != 0) {
16907            output = debugIndent(depth);
16908            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16909                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16910            Log.d(VIEW_LOG_TAG, output);
16911        }
16912
16913        output = debugIndent(depth);
16914        output += "mMeasureWidth=" + mMeasuredWidth +
16915                " mMeasureHeight=" + mMeasuredHeight;
16916        Log.d(VIEW_LOG_TAG, output);
16917
16918        output = debugIndent(depth);
16919        if (mLayoutParams == null) {
16920            output += "BAD! no layout params";
16921        } else {
16922            output = mLayoutParams.debug(output);
16923        }
16924        Log.d(VIEW_LOG_TAG, output);
16925
16926        output = debugIndent(depth);
16927        output += "flags={";
16928        output += View.printFlags(mViewFlags);
16929        output += "}";
16930        Log.d(VIEW_LOG_TAG, output);
16931
16932        output = debugIndent(depth);
16933        output += "privateFlags={";
16934        output += View.printPrivateFlags(mPrivateFlags);
16935        output += "}";
16936        Log.d(VIEW_LOG_TAG, output);
16937    }
16938
16939    /**
16940     * Creates a string of whitespaces used for indentation.
16941     *
16942     * @param depth the indentation level
16943     * @return a String containing (depth * 2 + 3) * 2 white spaces
16944     *
16945     * @hide
16946     */
16947    protected static String debugIndent(int depth) {
16948        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16949        for (int i = 0; i < (depth * 2) + 3; i++) {
16950            spaces.append(' ').append(' ');
16951        }
16952        return spaces.toString();
16953    }
16954
16955    /**
16956     * <p>Return the offset of the widget's text baseline from the widget's top
16957     * boundary. If this widget does not support baseline alignment, this
16958     * method returns -1. </p>
16959     *
16960     * @return the offset of the baseline within the widget's bounds or -1
16961     *         if baseline alignment is not supported
16962     */
16963    @ViewDebug.ExportedProperty(category = "layout")
16964    public int getBaseline() {
16965        return -1;
16966    }
16967
16968    /**
16969     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16970     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16971     * a layout pass.
16972     *
16973     * @return whether the view hierarchy is currently undergoing a layout pass
16974     */
16975    public boolean isInLayout() {
16976        ViewRootImpl viewRoot = getViewRootImpl();
16977        return (viewRoot != null && viewRoot.isInLayout());
16978    }
16979
16980    /**
16981     * Call this when something has changed which has invalidated the
16982     * layout of this view. This will schedule a layout pass of the view
16983     * tree. This should not be called while the view hierarchy is currently in a layout
16984     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16985     * end of the current layout pass (and then layout will run again) or after the current
16986     * frame is drawn and the next layout occurs.
16987     *
16988     * <p>Subclasses which override this method should call the superclass method to
16989     * handle possible request-during-layout errors correctly.</p>
16990     */
16991    public void requestLayout() {
16992        if (mMeasureCache != null) mMeasureCache.clear();
16993
16994        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16995            // Only trigger request-during-layout logic if this is the view requesting it,
16996            // not the views in its parent hierarchy
16997            ViewRootImpl viewRoot = getViewRootImpl();
16998            if (viewRoot != null && viewRoot.isInLayout()) {
16999                if (!viewRoot.requestLayoutDuringLayout(this)) {
17000                    return;
17001                }
17002            }
17003            mAttachInfo.mViewRequestingLayout = this;
17004        }
17005
17006        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17007        mPrivateFlags |= PFLAG_INVALIDATED;
17008
17009        if (mParent != null && !mParent.isLayoutRequested()) {
17010            mParent.requestLayout();
17011        }
17012        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17013            mAttachInfo.mViewRequestingLayout = null;
17014        }
17015    }
17016
17017    /**
17018     * Forces this view to be laid out during the next layout pass.
17019     * This method does not call requestLayout() or forceLayout()
17020     * on the parent.
17021     */
17022    public void forceLayout() {
17023        if (mMeasureCache != null) mMeasureCache.clear();
17024
17025        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17026        mPrivateFlags |= PFLAG_INVALIDATED;
17027    }
17028
17029    /**
17030     * <p>
17031     * This is called to find out how big a view should be. The parent
17032     * supplies constraint information in the width and height parameters.
17033     * </p>
17034     *
17035     * <p>
17036     * The actual measurement work of a view is performed in
17037     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17038     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17039     * </p>
17040     *
17041     *
17042     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17043     *        parent
17044     * @param heightMeasureSpec Vertical space requirements as imposed by the
17045     *        parent
17046     *
17047     * @see #onMeasure(int, int)
17048     */
17049    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17050        boolean optical = isLayoutModeOptical(this);
17051        if (optical != isLayoutModeOptical(mParent)) {
17052            Insets insets = getOpticalInsets();
17053            int oWidth  = insets.left + insets.right;
17054            int oHeight = insets.top  + insets.bottom;
17055            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17056            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17057        }
17058
17059        // Suppress sign extension for the low bytes
17060        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17061        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17062
17063        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17064                widthMeasureSpec != mOldWidthMeasureSpec ||
17065                heightMeasureSpec != mOldHeightMeasureSpec) {
17066
17067            // first clears the measured dimension flag
17068            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17069
17070            resolveRtlPropertiesIfNeeded();
17071
17072            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17073                    mMeasureCache.indexOfKey(key);
17074            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17075                // measure ourselves, this should set the measured dimension flag back
17076                onMeasure(widthMeasureSpec, heightMeasureSpec);
17077                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17078            } else {
17079                long value = mMeasureCache.valueAt(cacheIndex);
17080                // Casting a long to int drops the high 32 bits, no mask needed
17081                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17082                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17083            }
17084
17085            // flag not set, setMeasuredDimension() was not invoked, we raise
17086            // an exception to warn the developer
17087            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17088                throw new IllegalStateException("onMeasure() did not set the"
17089                        + " measured dimension by calling"
17090                        + " setMeasuredDimension()");
17091            }
17092
17093            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17094        }
17095
17096        mOldWidthMeasureSpec = widthMeasureSpec;
17097        mOldHeightMeasureSpec = heightMeasureSpec;
17098
17099        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17100                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17101    }
17102
17103    /**
17104     * <p>
17105     * Measure the view and its content to determine the measured width and the
17106     * measured height. This method is invoked by {@link #measure(int, int)} and
17107     * should be overriden by subclasses to provide accurate and efficient
17108     * measurement of their contents.
17109     * </p>
17110     *
17111     * <p>
17112     * <strong>CONTRACT:</strong> When overriding this method, you
17113     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17114     * measured width and height of this view. Failure to do so will trigger an
17115     * <code>IllegalStateException</code>, thrown by
17116     * {@link #measure(int, int)}. Calling the superclass'
17117     * {@link #onMeasure(int, int)} is a valid use.
17118     * </p>
17119     *
17120     * <p>
17121     * The base class implementation of measure defaults to the background size,
17122     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17123     * override {@link #onMeasure(int, int)} to provide better measurements of
17124     * their content.
17125     * </p>
17126     *
17127     * <p>
17128     * If this method is overridden, it is the subclass's responsibility to make
17129     * sure the measured height and width are at least the view's minimum height
17130     * and width ({@link #getSuggestedMinimumHeight()} and
17131     * {@link #getSuggestedMinimumWidth()}).
17132     * </p>
17133     *
17134     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17135     *                         The requirements are encoded with
17136     *                         {@link android.view.View.MeasureSpec}.
17137     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17138     *                         The requirements are encoded with
17139     *                         {@link android.view.View.MeasureSpec}.
17140     *
17141     * @see #getMeasuredWidth()
17142     * @see #getMeasuredHeight()
17143     * @see #setMeasuredDimension(int, int)
17144     * @see #getSuggestedMinimumHeight()
17145     * @see #getSuggestedMinimumWidth()
17146     * @see android.view.View.MeasureSpec#getMode(int)
17147     * @see android.view.View.MeasureSpec#getSize(int)
17148     */
17149    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17150        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17151                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17152    }
17153
17154    /**
17155     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17156     * measured width and measured height. Failing to do so will trigger an
17157     * exception at measurement time.</p>
17158     *
17159     * @param measuredWidth The measured width of this view.  May be a complex
17160     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17161     * {@link #MEASURED_STATE_TOO_SMALL}.
17162     * @param measuredHeight The measured height of this view.  May be a complex
17163     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17164     * {@link #MEASURED_STATE_TOO_SMALL}.
17165     */
17166    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17167        boolean optical = isLayoutModeOptical(this);
17168        if (optical != isLayoutModeOptical(mParent)) {
17169            Insets insets = getOpticalInsets();
17170            int opticalWidth  = insets.left + insets.right;
17171            int opticalHeight = insets.top  + insets.bottom;
17172
17173            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17174            measuredHeight += optical ? opticalHeight : -opticalHeight;
17175        }
17176        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17177    }
17178
17179    /**
17180     * Sets the measured dimension without extra processing for things like optical bounds.
17181     * Useful for reapplying consistent values that have already been cooked with adjustments
17182     * for optical bounds, etc. such as those from the measurement cache.
17183     *
17184     * @param measuredWidth The measured width of this view.  May be a complex
17185     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17186     * {@link #MEASURED_STATE_TOO_SMALL}.
17187     * @param measuredHeight The measured height of this view.  May be a complex
17188     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17189     * {@link #MEASURED_STATE_TOO_SMALL}.
17190     */
17191    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17192        mMeasuredWidth = measuredWidth;
17193        mMeasuredHeight = measuredHeight;
17194
17195        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17196    }
17197
17198    /**
17199     * Merge two states as returned by {@link #getMeasuredState()}.
17200     * @param curState The current state as returned from a view or the result
17201     * of combining multiple views.
17202     * @param newState The new view state to combine.
17203     * @return Returns a new integer reflecting the combination of the two
17204     * states.
17205     */
17206    public static int combineMeasuredStates(int curState, int newState) {
17207        return curState | newState;
17208    }
17209
17210    /**
17211     * Version of {@link #resolveSizeAndState(int, int, int)}
17212     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17213     */
17214    public static int resolveSize(int size, int measureSpec) {
17215        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17216    }
17217
17218    /**
17219     * Utility to reconcile a desired size and state, with constraints imposed
17220     * by a MeasureSpec.  Will take the desired size, unless a different size
17221     * is imposed by the constraints.  The returned value is a compound integer,
17222     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17223     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17224     * size is smaller than the size the view wants to be.
17225     *
17226     * @param size How big the view wants to be
17227     * @param measureSpec Constraints imposed by the parent
17228     * @return Size information bit mask as defined by
17229     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17230     */
17231    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17232        int result = size;
17233        int specMode = MeasureSpec.getMode(measureSpec);
17234        int specSize =  MeasureSpec.getSize(measureSpec);
17235        switch (specMode) {
17236        case MeasureSpec.UNSPECIFIED:
17237            result = size;
17238            break;
17239        case MeasureSpec.AT_MOST:
17240            if (specSize < size) {
17241                result = specSize | MEASURED_STATE_TOO_SMALL;
17242            } else {
17243                result = size;
17244            }
17245            break;
17246        case MeasureSpec.EXACTLY:
17247            result = specSize;
17248            break;
17249        }
17250        return result | (childMeasuredState&MEASURED_STATE_MASK);
17251    }
17252
17253    /**
17254     * Utility to return a default size. Uses the supplied size if the
17255     * MeasureSpec imposed no constraints. Will get larger if allowed
17256     * by the MeasureSpec.
17257     *
17258     * @param size Default size for this view
17259     * @param measureSpec Constraints imposed by the parent
17260     * @return The size this view should be.
17261     */
17262    public static int getDefaultSize(int size, int measureSpec) {
17263        int result = size;
17264        int specMode = MeasureSpec.getMode(measureSpec);
17265        int specSize = MeasureSpec.getSize(measureSpec);
17266
17267        switch (specMode) {
17268        case MeasureSpec.UNSPECIFIED:
17269            result = size;
17270            break;
17271        case MeasureSpec.AT_MOST:
17272        case MeasureSpec.EXACTLY:
17273            result = specSize;
17274            break;
17275        }
17276        return result;
17277    }
17278
17279    /**
17280     * Returns the suggested minimum height that the view should use. This
17281     * returns the maximum of the view's minimum height
17282     * and the background's minimum height
17283     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17284     * <p>
17285     * When being used in {@link #onMeasure(int, int)}, the caller should still
17286     * ensure the returned height is within the requirements of the parent.
17287     *
17288     * @return The suggested minimum height of the view.
17289     */
17290    protected int getSuggestedMinimumHeight() {
17291        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17292
17293    }
17294
17295    /**
17296     * Returns the suggested minimum width that the view should use. This
17297     * returns the maximum of the view's minimum width)
17298     * and the background's minimum width
17299     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17300     * <p>
17301     * When being used in {@link #onMeasure(int, int)}, the caller should still
17302     * ensure the returned width is within the requirements of the parent.
17303     *
17304     * @return The suggested minimum width of the view.
17305     */
17306    protected int getSuggestedMinimumWidth() {
17307        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17308    }
17309
17310    /**
17311     * Returns the minimum height of the view.
17312     *
17313     * @return the minimum height the view will try to be.
17314     *
17315     * @see #setMinimumHeight(int)
17316     *
17317     * @attr ref android.R.styleable#View_minHeight
17318     */
17319    public int getMinimumHeight() {
17320        return mMinHeight;
17321    }
17322
17323    /**
17324     * Sets the minimum height of the view. It is not guaranteed the view will
17325     * be able to achieve this minimum height (for example, if its parent layout
17326     * constrains it with less available height).
17327     *
17328     * @param minHeight The minimum height the view will try to be.
17329     *
17330     * @see #getMinimumHeight()
17331     *
17332     * @attr ref android.R.styleable#View_minHeight
17333     */
17334    public void setMinimumHeight(int minHeight) {
17335        mMinHeight = minHeight;
17336        requestLayout();
17337    }
17338
17339    /**
17340     * Returns the minimum width of the view.
17341     *
17342     * @return the minimum width the view will try to be.
17343     *
17344     * @see #setMinimumWidth(int)
17345     *
17346     * @attr ref android.R.styleable#View_minWidth
17347     */
17348    public int getMinimumWidth() {
17349        return mMinWidth;
17350    }
17351
17352    /**
17353     * Sets the minimum width of the view. It is not guaranteed the view will
17354     * be able to achieve this minimum width (for example, if its parent layout
17355     * constrains it with less available width).
17356     *
17357     * @param minWidth The minimum width the view will try to be.
17358     *
17359     * @see #getMinimumWidth()
17360     *
17361     * @attr ref android.R.styleable#View_minWidth
17362     */
17363    public void setMinimumWidth(int minWidth) {
17364        mMinWidth = minWidth;
17365        requestLayout();
17366
17367    }
17368
17369    /**
17370     * Get the animation currently associated with this view.
17371     *
17372     * @return The animation that is currently playing or
17373     *         scheduled to play for this view.
17374     */
17375    public Animation getAnimation() {
17376        return mCurrentAnimation;
17377    }
17378
17379    /**
17380     * Start the specified animation now.
17381     *
17382     * @param animation the animation to start now
17383     */
17384    public void startAnimation(Animation animation) {
17385        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17386        setAnimation(animation);
17387        invalidateParentCaches();
17388        invalidate(true);
17389    }
17390
17391    /**
17392     * Cancels any animations for this view.
17393     */
17394    public void clearAnimation() {
17395        if (mCurrentAnimation != null) {
17396            mCurrentAnimation.detach();
17397        }
17398        mCurrentAnimation = null;
17399        invalidateParentIfNeeded();
17400    }
17401
17402    /**
17403     * Sets the next animation to play for this view.
17404     * If you want the animation to play immediately, use
17405     * {@link #startAnimation(android.view.animation.Animation)} instead.
17406     * This method provides allows fine-grained
17407     * control over the start time and invalidation, but you
17408     * must make sure that 1) the animation has a start time set, and
17409     * 2) the view's parent (which controls animations on its children)
17410     * will be invalidated when the animation is supposed to
17411     * start.
17412     *
17413     * @param animation The next animation, or null.
17414     */
17415    public void setAnimation(Animation animation) {
17416        mCurrentAnimation = animation;
17417
17418        if (animation != null) {
17419            // If the screen is off assume the animation start time is now instead of
17420            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17421            // would cause the animation to start when the screen turns back on
17422            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17423                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17424                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17425            }
17426            animation.reset();
17427        }
17428    }
17429
17430    /**
17431     * Invoked by a parent ViewGroup to notify the start of the animation
17432     * currently associated with this view. If you override this method,
17433     * always call super.onAnimationStart();
17434     *
17435     * @see #setAnimation(android.view.animation.Animation)
17436     * @see #getAnimation()
17437     */
17438    protected void onAnimationStart() {
17439        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17440    }
17441
17442    /**
17443     * Invoked by a parent ViewGroup to notify the end of the animation
17444     * currently associated with this view. If you override this method,
17445     * always call super.onAnimationEnd();
17446     *
17447     * @see #setAnimation(android.view.animation.Animation)
17448     * @see #getAnimation()
17449     */
17450    protected void onAnimationEnd() {
17451        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17452    }
17453
17454    /**
17455     * Invoked if there is a Transform that involves alpha. Subclass that can
17456     * draw themselves with the specified alpha should return true, and then
17457     * respect that alpha when their onDraw() is called. If this returns false
17458     * then the view may be redirected to draw into an offscreen buffer to
17459     * fulfill the request, which will look fine, but may be slower than if the
17460     * subclass handles it internally. The default implementation returns false.
17461     *
17462     * @param alpha The alpha (0..255) to apply to the view's drawing
17463     * @return true if the view can draw with the specified alpha.
17464     */
17465    protected boolean onSetAlpha(int alpha) {
17466        return false;
17467    }
17468
17469    /**
17470     * This is used by the RootView to perform an optimization when
17471     * the view hierarchy contains one or several SurfaceView.
17472     * SurfaceView is always considered transparent, but its children are not,
17473     * therefore all View objects remove themselves from the global transparent
17474     * region (passed as a parameter to this function).
17475     *
17476     * @param region The transparent region for this ViewAncestor (window).
17477     *
17478     * @return Returns true if the effective visibility of the view at this
17479     * point is opaque, regardless of the transparent region; returns false
17480     * if it is possible for underlying windows to be seen behind the view.
17481     *
17482     * {@hide}
17483     */
17484    public boolean gatherTransparentRegion(Region region) {
17485        final AttachInfo attachInfo = mAttachInfo;
17486        if (region != null && attachInfo != null) {
17487            final int pflags = mPrivateFlags;
17488            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17489                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17490                // remove it from the transparent region.
17491                final int[] location = attachInfo.mTransparentLocation;
17492                getLocationInWindow(location);
17493                region.op(location[0], location[1], location[0] + mRight - mLeft,
17494                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17495            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17496                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17497                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17498                // exists, so we remove the background drawable's non-transparent
17499                // parts from this transparent region.
17500                applyDrawableToTransparentRegion(mBackground, region);
17501            }
17502        }
17503        return true;
17504    }
17505
17506    /**
17507     * Play a sound effect for this view.
17508     *
17509     * <p>The framework will play sound effects for some built in actions, such as
17510     * clicking, but you may wish to play these effects in your widget,
17511     * for instance, for internal navigation.
17512     *
17513     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17514     * {@link #isSoundEffectsEnabled()} is true.
17515     *
17516     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17517     */
17518    public void playSoundEffect(int soundConstant) {
17519        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17520            return;
17521        }
17522        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17523    }
17524
17525    /**
17526     * BZZZTT!!1!
17527     *
17528     * <p>Provide haptic feedback to the user for this view.
17529     *
17530     * <p>The framework will provide haptic feedback for some built in actions,
17531     * such as long presses, but you may wish to provide feedback for your
17532     * own widget.
17533     *
17534     * <p>The feedback will only be performed if
17535     * {@link #isHapticFeedbackEnabled()} is true.
17536     *
17537     * @param feedbackConstant One of the constants defined in
17538     * {@link HapticFeedbackConstants}
17539     */
17540    public boolean performHapticFeedback(int feedbackConstant) {
17541        return performHapticFeedback(feedbackConstant, 0);
17542    }
17543
17544    /**
17545     * BZZZTT!!1!
17546     *
17547     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17548     *
17549     * @param feedbackConstant One of the constants defined in
17550     * {@link HapticFeedbackConstants}
17551     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17552     */
17553    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17554        if (mAttachInfo == null) {
17555            return false;
17556        }
17557        //noinspection SimplifiableIfStatement
17558        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17559                && !isHapticFeedbackEnabled()) {
17560            return false;
17561        }
17562        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17563                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17564    }
17565
17566    /**
17567     * Request that the visibility of the status bar or other screen/window
17568     * decorations be changed.
17569     *
17570     * <p>This method is used to put the over device UI into temporary modes
17571     * where the user's attention is focused more on the application content,
17572     * by dimming or hiding surrounding system affordances.  This is typically
17573     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17574     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17575     * to be placed behind the action bar (and with these flags other system
17576     * affordances) so that smooth transitions between hiding and showing them
17577     * can be done.
17578     *
17579     * <p>Two representative examples of the use of system UI visibility is
17580     * implementing a content browsing application (like a magazine reader)
17581     * and a video playing application.
17582     *
17583     * <p>The first code shows a typical implementation of a View in a content
17584     * browsing application.  In this implementation, the application goes
17585     * into a content-oriented mode by hiding the status bar and action bar,
17586     * and putting the navigation elements into lights out mode.  The user can
17587     * then interact with content while in this mode.  Such an application should
17588     * provide an easy way for the user to toggle out of the mode (such as to
17589     * check information in the status bar or access notifications).  In the
17590     * implementation here, this is done simply by tapping on the content.
17591     *
17592     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17593     *      content}
17594     *
17595     * <p>This second code sample shows a typical implementation of a View
17596     * in a video playing application.  In this situation, while the video is
17597     * playing the application would like to go into a complete full-screen mode,
17598     * to use as much of the display as possible for the video.  When in this state
17599     * the user can not interact with the application; the system intercepts
17600     * touching on the screen to pop the UI out of full screen mode.  See
17601     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17602     *
17603     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17604     *      content}
17605     *
17606     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17607     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17608     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17609     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17610     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17611     */
17612    public void setSystemUiVisibility(int visibility) {
17613        if (visibility != mSystemUiVisibility) {
17614            mSystemUiVisibility = visibility;
17615            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17616                mParent.recomputeViewAttributes(this);
17617            }
17618        }
17619    }
17620
17621    /**
17622     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17623     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17624     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17625     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17626     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17627     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17628     */
17629    public int getSystemUiVisibility() {
17630        return mSystemUiVisibility;
17631    }
17632
17633    /**
17634     * Returns the current system UI visibility that is currently set for
17635     * the entire window.  This is the combination of the
17636     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17637     * views in the window.
17638     */
17639    public int getWindowSystemUiVisibility() {
17640        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17641    }
17642
17643    /**
17644     * Override to find out when the window's requested system UI visibility
17645     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17646     * This is different from the callbacks received through
17647     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17648     * in that this is only telling you about the local request of the window,
17649     * not the actual values applied by the system.
17650     */
17651    public void onWindowSystemUiVisibilityChanged(int visible) {
17652    }
17653
17654    /**
17655     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17656     * the view hierarchy.
17657     */
17658    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17659        onWindowSystemUiVisibilityChanged(visible);
17660    }
17661
17662    /**
17663     * Set a listener to receive callbacks when the visibility of the system bar changes.
17664     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17665     */
17666    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17667        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17668        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17669            mParent.recomputeViewAttributes(this);
17670        }
17671    }
17672
17673    /**
17674     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17675     * the view hierarchy.
17676     */
17677    public void dispatchSystemUiVisibilityChanged(int visibility) {
17678        ListenerInfo li = mListenerInfo;
17679        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17680            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17681                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17682        }
17683    }
17684
17685    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17686        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17687        if (val != mSystemUiVisibility) {
17688            setSystemUiVisibility(val);
17689            return true;
17690        }
17691        return false;
17692    }
17693
17694    /** @hide */
17695    public void setDisabledSystemUiVisibility(int flags) {
17696        if (mAttachInfo != null) {
17697            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17698                mAttachInfo.mDisabledSystemUiVisibility = flags;
17699                if (mParent != null) {
17700                    mParent.recomputeViewAttributes(this);
17701                }
17702            }
17703        }
17704    }
17705
17706    /**
17707     * Creates an image that the system displays during the drag and drop
17708     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17709     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17710     * appearance as the given View. The default also positions the center of the drag shadow
17711     * directly under the touch point. If no View is provided (the constructor with no parameters
17712     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17713     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17714     * default is an invisible drag shadow.
17715     * <p>
17716     * You are not required to use the View you provide to the constructor as the basis of the
17717     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17718     * anything you want as the drag shadow.
17719     * </p>
17720     * <p>
17721     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17722     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17723     *  size and position of the drag shadow. It uses this data to construct a
17724     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17725     *  so that your application can draw the shadow image in the Canvas.
17726     * </p>
17727     *
17728     * <div class="special reference">
17729     * <h3>Developer Guides</h3>
17730     * <p>For a guide to implementing drag and drop features, read the
17731     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17732     * </div>
17733     */
17734    public static class DragShadowBuilder {
17735        private final WeakReference<View> mView;
17736
17737        /**
17738         * Constructs a shadow image builder based on a View. By default, the resulting drag
17739         * shadow will have the same appearance and dimensions as the View, with the touch point
17740         * over the center of the View.
17741         * @param view A View. Any View in scope can be used.
17742         */
17743        public DragShadowBuilder(View view) {
17744            mView = new WeakReference<View>(view);
17745        }
17746
17747        /**
17748         * Construct a shadow builder object with no associated View.  This
17749         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17750         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17751         * to supply the drag shadow's dimensions and appearance without
17752         * reference to any View object. If they are not overridden, then the result is an
17753         * invisible drag shadow.
17754         */
17755        public DragShadowBuilder() {
17756            mView = new WeakReference<View>(null);
17757        }
17758
17759        /**
17760         * Returns the View object that had been passed to the
17761         * {@link #View.DragShadowBuilder(View)}
17762         * constructor.  If that View parameter was {@code null} or if the
17763         * {@link #View.DragShadowBuilder()}
17764         * constructor was used to instantiate the builder object, this method will return
17765         * null.
17766         *
17767         * @return The View object associate with this builder object.
17768         */
17769        @SuppressWarnings({"JavadocReference"})
17770        final public View getView() {
17771            return mView.get();
17772        }
17773
17774        /**
17775         * Provides the metrics for the shadow image. These include the dimensions of
17776         * the shadow image, and the point within that shadow that should
17777         * be centered under the touch location while dragging.
17778         * <p>
17779         * The default implementation sets the dimensions of the shadow to be the
17780         * same as the dimensions of the View itself and centers the shadow under
17781         * the touch point.
17782         * </p>
17783         *
17784         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17785         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17786         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17787         * image.
17788         *
17789         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17790         * shadow image that should be underneath the touch point during the drag and drop
17791         * operation. Your application must set {@link android.graphics.Point#x} to the
17792         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17793         */
17794        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17795            final View view = mView.get();
17796            if (view != null) {
17797                shadowSize.set(view.getWidth(), view.getHeight());
17798                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17799            } else {
17800                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17801            }
17802        }
17803
17804        /**
17805         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17806         * based on the dimensions it received from the
17807         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17808         *
17809         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17810         */
17811        public void onDrawShadow(Canvas canvas) {
17812            final View view = mView.get();
17813            if (view != null) {
17814                view.draw(canvas);
17815            } else {
17816                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17817            }
17818        }
17819    }
17820
17821    /**
17822     * Starts a drag and drop operation. When your application calls this method, it passes a
17823     * {@link android.view.View.DragShadowBuilder} object to the system. The
17824     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17825     * to get metrics for the drag shadow, and then calls the object's
17826     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17827     * <p>
17828     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17829     *  drag events to all the View objects in your application that are currently visible. It does
17830     *  this either by calling the View object's drag listener (an implementation of
17831     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17832     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17833     *  Both are passed a {@link android.view.DragEvent} object that has a
17834     *  {@link android.view.DragEvent#getAction()} value of
17835     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17836     * </p>
17837     * <p>
17838     * Your application can invoke startDrag() on any attached View object. The View object does not
17839     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17840     * be related to the View the user selected for dragging.
17841     * </p>
17842     * @param data A {@link android.content.ClipData} object pointing to the data to be
17843     * transferred by the drag and drop operation.
17844     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17845     * drag shadow.
17846     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17847     * drop operation. This Object is put into every DragEvent object sent by the system during the
17848     * current drag.
17849     * <p>
17850     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17851     * to the target Views. For example, it can contain flags that differentiate between a
17852     * a copy operation and a move operation.
17853     * </p>
17854     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17855     * so the parameter should be set to 0.
17856     * @return {@code true} if the method completes successfully, or
17857     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17858     * do a drag, and so no drag operation is in progress.
17859     */
17860    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17861            Object myLocalState, int flags) {
17862        if (ViewDebug.DEBUG_DRAG) {
17863            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17864        }
17865        boolean okay = false;
17866
17867        Point shadowSize = new Point();
17868        Point shadowTouchPoint = new Point();
17869        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17870
17871        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17872                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17873            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17874        }
17875
17876        if (ViewDebug.DEBUG_DRAG) {
17877            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17878                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17879        }
17880        Surface surface = new Surface();
17881        try {
17882            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17883                    flags, shadowSize.x, shadowSize.y, surface);
17884            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17885                    + " surface=" + surface);
17886            if (token != null) {
17887                Canvas canvas = surface.lockCanvas(null);
17888                try {
17889                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17890                    shadowBuilder.onDrawShadow(canvas);
17891                } finally {
17892                    surface.unlockCanvasAndPost(canvas);
17893                }
17894
17895                final ViewRootImpl root = getViewRootImpl();
17896
17897                // Cache the local state object for delivery with DragEvents
17898                root.setLocalDragState(myLocalState);
17899
17900                // repurpose 'shadowSize' for the last touch point
17901                root.getLastTouchPoint(shadowSize);
17902
17903                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17904                        shadowSize.x, shadowSize.y,
17905                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17906                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17907
17908                // Off and running!  Release our local surface instance; the drag
17909                // shadow surface is now managed by the system process.
17910                surface.release();
17911            }
17912        } catch (Exception e) {
17913            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17914            surface.destroy();
17915        }
17916
17917        return okay;
17918    }
17919
17920    /**
17921     * Handles drag events sent by the system following a call to
17922     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17923     *<p>
17924     * When the system calls this method, it passes a
17925     * {@link android.view.DragEvent} object. A call to
17926     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17927     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17928     * operation.
17929     * @param event The {@link android.view.DragEvent} sent by the system.
17930     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17931     * in DragEvent, indicating the type of drag event represented by this object.
17932     * @return {@code true} if the method was successful, otherwise {@code false}.
17933     * <p>
17934     *  The method should return {@code true} in response to an action type of
17935     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17936     *  operation.
17937     * </p>
17938     * <p>
17939     *  The method should also return {@code true} in response to an action type of
17940     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17941     *  {@code false} if it didn't.
17942     * </p>
17943     */
17944    public boolean onDragEvent(DragEvent event) {
17945        return false;
17946    }
17947
17948    /**
17949     * Detects if this View is enabled and has a drag event listener.
17950     * If both are true, then it calls the drag event listener with the
17951     * {@link android.view.DragEvent} it received. If the drag event listener returns
17952     * {@code true}, then dispatchDragEvent() returns {@code true}.
17953     * <p>
17954     * For all other cases, the method calls the
17955     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17956     * method and returns its result.
17957     * </p>
17958     * <p>
17959     * This ensures that a drag event is always consumed, even if the View does not have a drag
17960     * event listener. However, if the View has a listener and the listener returns true, then
17961     * onDragEvent() is not called.
17962     * </p>
17963     */
17964    public boolean dispatchDragEvent(DragEvent event) {
17965        ListenerInfo li = mListenerInfo;
17966        //noinspection SimplifiableIfStatement
17967        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17968                && li.mOnDragListener.onDrag(this, event)) {
17969            return true;
17970        }
17971        return onDragEvent(event);
17972    }
17973
17974    boolean canAcceptDrag() {
17975        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17976    }
17977
17978    /**
17979     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17980     * it is ever exposed at all.
17981     * @hide
17982     */
17983    public void onCloseSystemDialogs(String reason) {
17984    }
17985
17986    /**
17987     * Given a Drawable whose bounds have been set to draw into this view,
17988     * update a Region being computed for
17989     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17990     * that any non-transparent parts of the Drawable are removed from the
17991     * given transparent region.
17992     *
17993     * @param dr The Drawable whose transparency is to be applied to the region.
17994     * @param region A Region holding the current transparency information,
17995     * where any parts of the region that are set are considered to be
17996     * transparent.  On return, this region will be modified to have the
17997     * transparency information reduced by the corresponding parts of the
17998     * Drawable that are not transparent.
17999     * {@hide}
18000     */
18001    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18002        if (DBG) {
18003            Log.i("View", "Getting transparent region for: " + this);
18004        }
18005        final Region r = dr.getTransparentRegion();
18006        final Rect db = dr.getBounds();
18007        final AttachInfo attachInfo = mAttachInfo;
18008        if (r != null && attachInfo != null) {
18009            final int w = getRight()-getLeft();
18010            final int h = getBottom()-getTop();
18011            if (db.left > 0) {
18012                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18013                r.op(0, 0, db.left, h, Region.Op.UNION);
18014            }
18015            if (db.right < w) {
18016                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18017                r.op(db.right, 0, w, h, Region.Op.UNION);
18018            }
18019            if (db.top > 0) {
18020                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18021                r.op(0, 0, w, db.top, Region.Op.UNION);
18022            }
18023            if (db.bottom < h) {
18024                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18025                r.op(0, db.bottom, w, h, Region.Op.UNION);
18026            }
18027            final int[] location = attachInfo.mTransparentLocation;
18028            getLocationInWindow(location);
18029            r.translate(location[0], location[1]);
18030            region.op(r, Region.Op.INTERSECT);
18031        } else {
18032            region.op(db, Region.Op.DIFFERENCE);
18033        }
18034    }
18035
18036    private void checkForLongClick(int delayOffset) {
18037        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18038            mHasPerformedLongPress = false;
18039
18040            if (mPendingCheckForLongPress == null) {
18041                mPendingCheckForLongPress = new CheckForLongPress();
18042            }
18043            mPendingCheckForLongPress.rememberWindowAttachCount();
18044            postDelayed(mPendingCheckForLongPress,
18045                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18046        }
18047    }
18048
18049    /**
18050     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18051     * LayoutInflater} class, which provides a full range of options for view inflation.
18052     *
18053     * @param context The Context object for your activity or application.
18054     * @param resource The resource ID to inflate
18055     * @param root A view group that will be the parent.  Used to properly inflate the
18056     * layout_* parameters.
18057     * @see LayoutInflater
18058     */
18059    public static View inflate(Context context, int resource, ViewGroup root) {
18060        LayoutInflater factory = LayoutInflater.from(context);
18061        return factory.inflate(resource, root);
18062    }
18063
18064    /**
18065     * Scroll the view with standard behavior for scrolling beyond the normal
18066     * content boundaries. Views that call this method should override
18067     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18068     * results of an over-scroll operation.
18069     *
18070     * Views can use this method to handle any touch or fling-based scrolling.
18071     *
18072     * @param deltaX Change in X in pixels
18073     * @param deltaY Change in Y in pixels
18074     * @param scrollX Current X scroll value in pixels before applying deltaX
18075     * @param scrollY Current Y scroll value in pixels before applying deltaY
18076     * @param scrollRangeX Maximum content scroll range along the X axis
18077     * @param scrollRangeY Maximum content scroll range along the Y axis
18078     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18079     *          along the X axis.
18080     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18081     *          along the Y axis.
18082     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18083     * @return true if scrolling was clamped to an over-scroll boundary along either
18084     *          axis, false otherwise.
18085     */
18086    @SuppressWarnings({"UnusedParameters"})
18087    protected boolean overScrollBy(int deltaX, int deltaY,
18088            int scrollX, int scrollY,
18089            int scrollRangeX, int scrollRangeY,
18090            int maxOverScrollX, int maxOverScrollY,
18091            boolean isTouchEvent) {
18092        final int overScrollMode = mOverScrollMode;
18093        final boolean canScrollHorizontal =
18094                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18095        final boolean canScrollVertical =
18096                computeVerticalScrollRange() > computeVerticalScrollExtent();
18097        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18098                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18099        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18100                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18101
18102        int newScrollX = scrollX + deltaX;
18103        if (!overScrollHorizontal) {
18104            maxOverScrollX = 0;
18105        }
18106
18107        int newScrollY = scrollY + deltaY;
18108        if (!overScrollVertical) {
18109            maxOverScrollY = 0;
18110        }
18111
18112        // Clamp values if at the limits and record
18113        final int left = -maxOverScrollX;
18114        final int right = maxOverScrollX + scrollRangeX;
18115        final int top = -maxOverScrollY;
18116        final int bottom = maxOverScrollY + scrollRangeY;
18117
18118        boolean clampedX = false;
18119        if (newScrollX > right) {
18120            newScrollX = right;
18121            clampedX = true;
18122        } else if (newScrollX < left) {
18123            newScrollX = left;
18124            clampedX = true;
18125        }
18126
18127        boolean clampedY = false;
18128        if (newScrollY > bottom) {
18129            newScrollY = bottom;
18130            clampedY = true;
18131        } else if (newScrollY < top) {
18132            newScrollY = top;
18133            clampedY = true;
18134        }
18135
18136        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18137
18138        return clampedX || clampedY;
18139    }
18140
18141    /**
18142     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18143     * respond to the results of an over-scroll operation.
18144     *
18145     * @param scrollX New X scroll value in pixels
18146     * @param scrollY New Y scroll value in pixels
18147     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18148     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18149     */
18150    protected void onOverScrolled(int scrollX, int scrollY,
18151            boolean clampedX, boolean clampedY) {
18152        // Intentionally empty.
18153    }
18154
18155    /**
18156     * Returns the over-scroll mode for this view. The result will be
18157     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18158     * (allow over-scrolling only if the view content is larger than the container),
18159     * or {@link #OVER_SCROLL_NEVER}.
18160     *
18161     * @return This view's over-scroll mode.
18162     */
18163    public int getOverScrollMode() {
18164        return mOverScrollMode;
18165    }
18166
18167    /**
18168     * Set the over-scroll mode for this view. Valid over-scroll modes are
18169     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18170     * (allow over-scrolling only if the view content is larger than the container),
18171     * or {@link #OVER_SCROLL_NEVER}.
18172     *
18173     * Setting the over-scroll mode of a view will have an effect only if the
18174     * view is capable of scrolling.
18175     *
18176     * @param overScrollMode The new over-scroll mode for this view.
18177     */
18178    public void setOverScrollMode(int overScrollMode) {
18179        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18180                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18181                overScrollMode != OVER_SCROLL_NEVER) {
18182            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18183        }
18184        mOverScrollMode = overScrollMode;
18185    }
18186
18187    /**
18188     * Enable or disable nested scrolling for this view.
18189     *
18190     * <p>If this property is set to true the view will be permitted to initiate nested
18191     * scrolling operations with a compatible parent view in the current hierarchy. If this
18192     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18193     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18194     * the nested scroll.</p>
18195     *
18196     * @param enabled true to enable nested scrolling, false to disable
18197     *
18198     * @see #isNestedScrollingEnabled()
18199     */
18200    public void setNestedScrollingEnabled(boolean enabled) {
18201        if (enabled) {
18202            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18203        } else {
18204            stopNestedScroll();
18205            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18206        }
18207    }
18208
18209    /**
18210     * Returns true if nested scrolling is enabled for this view.
18211     *
18212     * <p>If nested scrolling is enabled and this View class implementation supports it,
18213     * this view will act as a nested scrolling child view when applicable, forwarding data
18214     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18215     * parent.</p>
18216     *
18217     * @return true if nested scrolling is enabled
18218     *
18219     * @see #setNestedScrollingEnabled(boolean)
18220     */
18221    public boolean isNestedScrollingEnabled() {
18222        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18223                PFLAG3_NESTED_SCROLLING_ENABLED;
18224    }
18225
18226    /**
18227     * Begin a nestable scroll operation along the given axes.
18228     *
18229     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18230     *
18231     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18232     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18233     * In the case of touch scrolling the nested scroll will be terminated automatically in
18234     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18235     * In the event of programmatic scrolling the caller must explicitly call
18236     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18237     *
18238     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18239     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18240     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18241     *
18242     * <p>At each incremental step of the scroll the caller should invoke
18243     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18244     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18245     * parent at least partially consumed the scroll and the caller should adjust the amount it
18246     * scrolls by.</p>
18247     *
18248     * <p>After applying the remainder of the scroll delta the caller should invoke
18249     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18250     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18251     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18252     * </p>
18253     *
18254     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18255     *             {@link #SCROLL_AXIS_VERTICAL}.
18256     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18257     *         the current gesture.
18258     *
18259     * @see #stopNestedScroll()
18260     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18261     * @see #dispatchNestedScroll(int, int, int, int, int[])
18262     */
18263    public boolean startNestedScroll(int axes) {
18264        if (hasNestedScrollingParent()) {
18265            // Already in progress
18266            return true;
18267        }
18268        if (isNestedScrollingEnabled()) {
18269            ViewParent p = getParent();
18270            View child = this;
18271            while (p != null) {
18272                try {
18273                    if (p.onStartNestedScroll(child, this, axes)) {
18274                        mNestedScrollingParent = p;
18275                        p.onNestedScrollAccepted(child, this, axes);
18276                        return true;
18277                    }
18278                } catch (AbstractMethodError e) {
18279                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18280                            "method onStartNestedScroll", e);
18281                    // Allow the search upward to continue
18282                }
18283                if (p instanceof View) {
18284                    child = (View) p;
18285                }
18286                p = p.getParent();
18287            }
18288        }
18289        return false;
18290    }
18291
18292    /**
18293     * Stop a nested scroll in progress.
18294     *
18295     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18296     *
18297     * @see #startNestedScroll(int)
18298     */
18299    public void stopNestedScroll() {
18300        if (mNestedScrollingParent != null) {
18301            mNestedScrollingParent.onStopNestedScroll(this);
18302            mNestedScrollingParent = null;
18303        }
18304    }
18305
18306    /**
18307     * Returns true if this view has a nested scrolling parent.
18308     *
18309     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18310     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18311     *
18312     * @return whether this view has a nested scrolling parent
18313     */
18314    public boolean hasNestedScrollingParent() {
18315        return mNestedScrollingParent != null;
18316    }
18317
18318    /**
18319     * Dispatch one step of a nested scroll in progress.
18320     *
18321     * <p>Implementations of views that support nested scrolling should call this to report
18322     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18323     * is not currently in progress or nested scrolling is not
18324     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18325     *
18326     * <p>Compatible View implementations should also call
18327     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18328     * consuming a component of the scroll event themselves.</p>
18329     *
18330     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18331     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18332     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18333     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18334     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18335     *                       in local view coordinates of this view from before this operation
18336     *                       to after it completes. View implementations may use this to adjust
18337     *                       expected input coordinate tracking.
18338     * @return true if the event was dispatched, false if it could not be dispatched.
18339     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18340     */
18341    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18342            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18343        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18344            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18345                int startX = 0;
18346                int startY = 0;
18347                if (offsetInWindow != null) {
18348                    getLocationInWindow(offsetInWindow);
18349                    startX = offsetInWindow[0];
18350                    startY = offsetInWindow[1];
18351                }
18352
18353                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18354                        dxUnconsumed, dyUnconsumed);
18355
18356                if (offsetInWindow != null) {
18357                    getLocationInWindow(offsetInWindow);
18358                    offsetInWindow[0] -= startX;
18359                    offsetInWindow[1] -= startY;
18360                }
18361                return true;
18362            } else if (offsetInWindow != null) {
18363                // No motion, no dispatch. Keep offsetInWindow up to date.
18364                offsetInWindow[0] = 0;
18365                offsetInWindow[1] = 0;
18366            }
18367        }
18368        return false;
18369    }
18370
18371    /**
18372     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18373     *
18374     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18375     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18376     * scrolling operation to consume some or all of the scroll operation before the child view
18377     * consumes it.</p>
18378     *
18379     * @param dx Horizontal scroll distance in pixels
18380     * @param dy Vertical scroll distance in pixels
18381     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18382     *                 and consumed[1] the consumed dy.
18383     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18384     *                       in local view coordinates of this view from before this operation
18385     *                       to after it completes. View implementations may use this to adjust
18386     *                       expected input coordinate tracking.
18387     * @return true if the parent consumed some or all of the scroll delta
18388     * @see #dispatchNestedScroll(int, int, int, int, int[])
18389     */
18390    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18391        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18392            if (dx != 0 || dy != 0) {
18393                int startX = 0;
18394                int startY = 0;
18395                if (offsetInWindow != null) {
18396                    getLocationInWindow(offsetInWindow);
18397                    startX = offsetInWindow[0];
18398                    startY = offsetInWindow[1];
18399                }
18400
18401                if (consumed == null) {
18402                    if (mTempNestedScrollConsumed == null) {
18403                        mTempNestedScrollConsumed = new int[2];
18404                    }
18405                    consumed = mTempNestedScrollConsumed;
18406                }
18407                consumed[0] = 0;
18408                consumed[1] = 0;
18409                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18410
18411                if (offsetInWindow != null) {
18412                    getLocationInWindow(offsetInWindow);
18413                    offsetInWindow[0] -= startX;
18414                    offsetInWindow[1] -= startY;
18415                }
18416                return consumed[0] != 0 || consumed[1] != 0;
18417            } else if (offsetInWindow != null) {
18418                offsetInWindow[0] = 0;
18419                offsetInWindow[1] = 0;
18420            }
18421        }
18422        return false;
18423    }
18424
18425    /**
18426     * Dispatch a fling to a nested scrolling parent.
18427     *
18428     * <p>This method should be used to indicate that a nested scrolling child has detected
18429     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18430     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18431     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18432     * along a scrollable axis.</p>
18433     *
18434     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18435     * its own content, it can use this method to delegate the fling to its nested scrolling
18436     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18437     *
18438     * @param velocityX Horizontal fling velocity in pixels per second
18439     * @param velocityY Vertical fling velocity in pixels per second
18440     * @param consumed true if the child consumed the fling, false otherwise
18441     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18442     */
18443    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18444        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18445            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18446        }
18447        return false;
18448    }
18449
18450    /**
18451     * Gets a scale factor that determines the distance the view should scroll
18452     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18453     * @return The vertical scroll scale factor.
18454     * @hide
18455     */
18456    protected float getVerticalScrollFactor() {
18457        if (mVerticalScrollFactor == 0) {
18458            TypedValue outValue = new TypedValue();
18459            if (!mContext.getTheme().resolveAttribute(
18460                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18461                throw new IllegalStateException(
18462                        "Expected theme to define listPreferredItemHeight.");
18463            }
18464            mVerticalScrollFactor = outValue.getDimension(
18465                    mContext.getResources().getDisplayMetrics());
18466        }
18467        return mVerticalScrollFactor;
18468    }
18469
18470    /**
18471     * Gets a scale factor that determines the distance the view should scroll
18472     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18473     * @return The horizontal scroll scale factor.
18474     * @hide
18475     */
18476    protected float getHorizontalScrollFactor() {
18477        // TODO: Should use something else.
18478        return getVerticalScrollFactor();
18479    }
18480
18481    /**
18482     * Return the value specifying the text direction or policy that was set with
18483     * {@link #setTextDirection(int)}.
18484     *
18485     * @return the defined text direction. It can be one of:
18486     *
18487     * {@link #TEXT_DIRECTION_INHERIT},
18488     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18489     * {@link #TEXT_DIRECTION_ANY_RTL},
18490     * {@link #TEXT_DIRECTION_LTR},
18491     * {@link #TEXT_DIRECTION_RTL},
18492     * {@link #TEXT_DIRECTION_LOCALE}
18493     *
18494     * @attr ref android.R.styleable#View_textDirection
18495     *
18496     * @hide
18497     */
18498    @ViewDebug.ExportedProperty(category = "text", mapping = {
18499            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18500            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18501            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18502            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18503            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18504            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18505    })
18506    public int getRawTextDirection() {
18507        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18508    }
18509
18510    /**
18511     * Set the text direction.
18512     *
18513     * @param textDirection the direction to set. Should be one of:
18514     *
18515     * {@link #TEXT_DIRECTION_INHERIT},
18516     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18517     * {@link #TEXT_DIRECTION_ANY_RTL},
18518     * {@link #TEXT_DIRECTION_LTR},
18519     * {@link #TEXT_DIRECTION_RTL},
18520     * {@link #TEXT_DIRECTION_LOCALE}
18521     *
18522     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18523     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18524     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18525     *
18526     * @attr ref android.R.styleable#View_textDirection
18527     */
18528    public void setTextDirection(int textDirection) {
18529        if (getRawTextDirection() != textDirection) {
18530            // Reset the current text direction and the resolved one
18531            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18532            resetResolvedTextDirection();
18533            // Set the new text direction
18534            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18535            // Do resolution
18536            resolveTextDirection();
18537            // Notify change
18538            onRtlPropertiesChanged(getLayoutDirection());
18539            // Refresh
18540            requestLayout();
18541            invalidate(true);
18542        }
18543    }
18544
18545    /**
18546     * Return the resolved text direction.
18547     *
18548     * @return the resolved text direction. Returns one of:
18549     *
18550     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18551     * {@link #TEXT_DIRECTION_ANY_RTL},
18552     * {@link #TEXT_DIRECTION_LTR},
18553     * {@link #TEXT_DIRECTION_RTL},
18554     * {@link #TEXT_DIRECTION_LOCALE}
18555     *
18556     * @attr ref android.R.styleable#View_textDirection
18557     */
18558    @ViewDebug.ExportedProperty(category = "text", mapping = {
18559            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18560            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18561            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18562            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18563            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18564            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18565    })
18566    public int getTextDirection() {
18567        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18568    }
18569
18570    /**
18571     * Resolve the text direction.
18572     *
18573     * @return true if resolution has been done, false otherwise.
18574     *
18575     * @hide
18576     */
18577    public boolean resolveTextDirection() {
18578        // Reset any previous text direction resolution
18579        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18580
18581        if (hasRtlSupport()) {
18582            // Set resolved text direction flag depending on text direction flag
18583            final int textDirection = getRawTextDirection();
18584            switch(textDirection) {
18585                case TEXT_DIRECTION_INHERIT:
18586                    if (!canResolveTextDirection()) {
18587                        // We cannot do the resolution if there is no parent, so use the default one
18588                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18589                        // Resolution will need to happen again later
18590                        return false;
18591                    }
18592
18593                    // Parent has not yet resolved, so we still return the default
18594                    try {
18595                        if (!mParent.isTextDirectionResolved()) {
18596                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18597                            // Resolution will need to happen again later
18598                            return false;
18599                        }
18600                    } catch (AbstractMethodError e) {
18601                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18602                                " does not fully implement ViewParent", e);
18603                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18604                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18605                        return true;
18606                    }
18607
18608                    // Set current resolved direction to the same value as the parent's one
18609                    int parentResolvedDirection;
18610                    try {
18611                        parentResolvedDirection = mParent.getTextDirection();
18612                    } catch (AbstractMethodError e) {
18613                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18614                                " does not fully implement ViewParent", e);
18615                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18616                    }
18617                    switch (parentResolvedDirection) {
18618                        case TEXT_DIRECTION_FIRST_STRONG:
18619                        case TEXT_DIRECTION_ANY_RTL:
18620                        case TEXT_DIRECTION_LTR:
18621                        case TEXT_DIRECTION_RTL:
18622                        case TEXT_DIRECTION_LOCALE:
18623                            mPrivateFlags2 |=
18624                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18625                            break;
18626                        default:
18627                            // Default resolved direction is "first strong" heuristic
18628                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18629                    }
18630                    break;
18631                case TEXT_DIRECTION_FIRST_STRONG:
18632                case TEXT_DIRECTION_ANY_RTL:
18633                case TEXT_DIRECTION_LTR:
18634                case TEXT_DIRECTION_RTL:
18635                case TEXT_DIRECTION_LOCALE:
18636                    // Resolved direction is the same as text direction
18637                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18638                    break;
18639                default:
18640                    // Default resolved direction is "first strong" heuristic
18641                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18642            }
18643        } else {
18644            // Default resolved direction is "first strong" heuristic
18645            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18646        }
18647
18648        // Set to resolved
18649        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18650        return true;
18651    }
18652
18653    /**
18654     * Check if text direction resolution can be done.
18655     *
18656     * @return true if text direction resolution can be done otherwise return false.
18657     */
18658    public boolean canResolveTextDirection() {
18659        switch (getRawTextDirection()) {
18660            case TEXT_DIRECTION_INHERIT:
18661                if (mParent != null) {
18662                    try {
18663                        return mParent.canResolveTextDirection();
18664                    } catch (AbstractMethodError e) {
18665                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18666                                " does not fully implement ViewParent", e);
18667                    }
18668                }
18669                return false;
18670
18671            default:
18672                return true;
18673        }
18674    }
18675
18676    /**
18677     * Reset resolved text direction. Text direction will be resolved during a call to
18678     * {@link #onMeasure(int, int)}.
18679     *
18680     * @hide
18681     */
18682    public void resetResolvedTextDirection() {
18683        // Reset any previous text direction resolution
18684        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18685        // Set to default value
18686        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18687    }
18688
18689    /**
18690     * @return true if text direction is inherited.
18691     *
18692     * @hide
18693     */
18694    public boolean isTextDirectionInherited() {
18695        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18696    }
18697
18698    /**
18699     * @return true if text direction is resolved.
18700     */
18701    public boolean isTextDirectionResolved() {
18702        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18703    }
18704
18705    /**
18706     * Return the value specifying the text alignment or policy that was set with
18707     * {@link #setTextAlignment(int)}.
18708     *
18709     * @return the defined text alignment. It can be one of:
18710     *
18711     * {@link #TEXT_ALIGNMENT_INHERIT},
18712     * {@link #TEXT_ALIGNMENT_GRAVITY},
18713     * {@link #TEXT_ALIGNMENT_CENTER},
18714     * {@link #TEXT_ALIGNMENT_TEXT_START},
18715     * {@link #TEXT_ALIGNMENT_TEXT_END},
18716     * {@link #TEXT_ALIGNMENT_VIEW_START},
18717     * {@link #TEXT_ALIGNMENT_VIEW_END}
18718     *
18719     * @attr ref android.R.styleable#View_textAlignment
18720     *
18721     * @hide
18722     */
18723    @ViewDebug.ExportedProperty(category = "text", mapping = {
18724            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18725            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18726            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18727            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18728            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18729            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18730            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18731    })
18732    @TextAlignment
18733    public int getRawTextAlignment() {
18734        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18735    }
18736
18737    /**
18738     * Set the text alignment.
18739     *
18740     * @param textAlignment The text alignment to set. Should be one of
18741     *
18742     * {@link #TEXT_ALIGNMENT_INHERIT},
18743     * {@link #TEXT_ALIGNMENT_GRAVITY},
18744     * {@link #TEXT_ALIGNMENT_CENTER},
18745     * {@link #TEXT_ALIGNMENT_TEXT_START},
18746     * {@link #TEXT_ALIGNMENT_TEXT_END},
18747     * {@link #TEXT_ALIGNMENT_VIEW_START},
18748     * {@link #TEXT_ALIGNMENT_VIEW_END}
18749     *
18750     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18751     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18752     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18753     *
18754     * @attr ref android.R.styleable#View_textAlignment
18755     */
18756    public void setTextAlignment(@TextAlignment int textAlignment) {
18757        if (textAlignment != getRawTextAlignment()) {
18758            // Reset the current and resolved text alignment
18759            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18760            resetResolvedTextAlignment();
18761            // Set the new text alignment
18762            mPrivateFlags2 |=
18763                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18764            // Do resolution
18765            resolveTextAlignment();
18766            // Notify change
18767            onRtlPropertiesChanged(getLayoutDirection());
18768            // Refresh
18769            requestLayout();
18770            invalidate(true);
18771        }
18772    }
18773
18774    /**
18775     * Return the resolved text alignment.
18776     *
18777     * @return the resolved text alignment. Returns one of:
18778     *
18779     * {@link #TEXT_ALIGNMENT_GRAVITY},
18780     * {@link #TEXT_ALIGNMENT_CENTER},
18781     * {@link #TEXT_ALIGNMENT_TEXT_START},
18782     * {@link #TEXT_ALIGNMENT_TEXT_END},
18783     * {@link #TEXT_ALIGNMENT_VIEW_START},
18784     * {@link #TEXT_ALIGNMENT_VIEW_END}
18785     *
18786     * @attr ref android.R.styleable#View_textAlignment
18787     */
18788    @ViewDebug.ExportedProperty(category = "text", mapping = {
18789            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18790            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18791            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18792            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18793            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18794            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18795            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18796    })
18797    @TextAlignment
18798    public int getTextAlignment() {
18799        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18800                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18801    }
18802
18803    /**
18804     * Resolve the text alignment.
18805     *
18806     * @return true if resolution has been done, false otherwise.
18807     *
18808     * @hide
18809     */
18810    public boolean resolveTextAlignment() {
18811        // Reset any previous text alignment resolution
18812        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18813
18814        if (hasRtlSupport()) {
18815            // Set resolved text alignment flag depending on text alignment flag
18816            final int textAlignment = getRawTextAlignment();
18817            switch (textAlignment) {
18818                case TEXT_ALIGNMENT_INHERIT:
18819                    // Check if we can resolve the text alignment
18820                    if (!canResolveTextAlignment()) {
18821                        // We cannot do the resolution if there is no parent so use the default
18822                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18823                        // Resolution will need to happen again later
18824                        return false;
18825                    }
18826
18827                    // Parent has not yet resolved, so we still return the default
18828                    try {
18829                        if (!mParent.isTextAlignmentResolved()) {
18830                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18831                            // Resolution will need to happen again later
18832                            return false;
18833                        }
18834                    } catch (AbstractMethodError e) {
18835                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18836                                " does not fully implement ViewParent", e);
18837                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18838                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18839                        return true;
18840                    }
18841
18842                    int parentResolvedTextAlignment;
18843                    try {
18844                        parentResolvedTextAlignment = mParent.getTextAlignment();
18845                    } catch (AbstractMethodError e) {
18846                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18847                                " does not fully implement ViewParent", e);
18848                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18849                    }
18850                    switch (parentResolvedTextAlignment) {
18851                        case TEXT_ALIGNMENT_GRAVITY:
18852                        case TEXT_ALIGNMENT_TEXT_START:
18853                        case TEXT_ALIGNMENT_TEXT_END:
18854                        case TEXT_ALIGNMENT_CENTER:
18855                        case TEXT_ALIGNMENT_VIEW_START:
18856                        case TEXT_ALIGNMENT_VIEW_END:
18857                            // Resolved text alignment is the same as the parent resolved
18858                            // text alignment
18859                            mPrivateFlags2 |=
18860                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18861                            break;
18862                        default:
18863                            // Use default resolved text alignment
18864                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18865                    }
18866                    break;
18867                case TEXT_ALIGNMENT_GRAVITY:
18868                case TEXT_ALIGNMENT_TEXT_START:
18869                case TEXT_ALIGNMENT_TEXT_END:
18870                case TEXT_ALIGNMENT_CENTER:
18871                case TEXT_ALIGNMENT_VIEW_START:
18872                case TEXT_ALIGNMENT_VIEW_END:
18873                    // Resolved text alignment is the same as text alignment
18874                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18875                    break;
18876                default:
18877                    // Use default resolved text alignment
18878                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18879            }
18880        } else {
18881            // Use default resolved text alignment
18882            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18883        }
18884
18885        // Set the resolved
18886        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18887        return true;
18888    }
18889
18890    /**
18891     * Check if text alignment resolution can be done.
18892     *
18893     * @return true if text alignment resolution can be done otherwise return false.
18894     */
18895    public boolean canResolveTextAlignment() {
18896        switch (getRawTextAlignment()) {
18897            case TEXT_DIRECTION_INHERIT:
18898                if (mParent != null) {
18899                    try {
18900                        return mParent.canResolveTextAlignment();
18901                    } catch (AbstractMethodError e) {
18902                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18903                                " does not fully implement ViewParent", e);
18904                    }
18905                }
18906                return false;
18907
18908            default:
18909                return true;
18910        }
18911    }
18912
18913    /**
18914     * Reset resolved text alignment. Text alignment will be resolved during a call to
18915     * {@link #onMeasure(int, int)}.
18916     *
18917     * @hide
18918     */
18919    public void resetResolvedTextAlignment() {
18920        // Reset any previous text alignment resolution
18921        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18922        // Set to default
18923        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18924    }
18925
18926    /**
18927     * @return true if text alignment is inherited.
18928     *
18929     * @hide
18930     */
18931    public boolean isTextAlignmentInherited() {
18932        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18933    }
18934
18935    /**
18936     * @return true if text alignment is resolved.
18937     */
18938    public boolean isTextAlignmentResolved() {
18939        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18940    }
18941
18942    /**
18943     * Generate a value suitable for use in {@link #setId(int)}.
18944     * This value will not collide with ID values generated at build time by aapt for R.id.
18945     *
18946     * @return a generated ID value
18947     */
18948    public static int generateViewId() {
18949        for (;;) {
18950            final int result = sNextGeneratedId.get();
18951            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18952            int newValue = result + 1;
18953            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18954            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18955                return result;
18956            }
18957        }
18958    }
18959
18960    /**
18961     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18962     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18963     *                           a normal View or a ViewGroup with
18964     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18965     * @hide
18966     */
18967    public void captureTransitioningViews(List<View> transitioningViews) {
18968        if (getVisibility() == View.VISIBLE) {
18969            transitioningViews.add(this);
18970        }
18971    }
18972
18973    /**
18974     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
18975     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
18976     * @hide
18977     */
18978    public void findNamedViews(Map<String, View> namedElements) {
18979        if (getVisibility() == VISIBLE) {
18980            String transitionName = getTransitionName();
18981            if (transitionName != null) {
18982                namedElements.put(transitionName, this);
18983            }
18984        }
18985    }
18986
18987    //
18988    // Properties
18989    //
18990    /**
18991     * A Property wrapper around the <code>alpha</code> functionality handled by the
18992     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18993     */
18994    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18995        @Override
18996        public void setValue(View object, float value) {
18997            object.setAlpha(value);
18998        }
18999
19000        @Override
19001        public Float get(View object) {
19002            return object.getAlpha();
19003        }
19004    };
19005
19006    /**
19007     * A Property wrapper around the <code>translationX</code> functionality handled by the
19008     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19009     */
19010    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19011        @Override
19012        public void setValue(View object, float value) {
19013            object.setTranslationX(value);
19014        }
19015
19016                @Override
19017        public Float get(View object) {
19018            return object.getTranslationX();
19019        }
19020    };
19021
19022    /**
19023     * A Property wrapper around the <code>translationY</code> functionality handled by the
19024     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19025     */
19026    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19027        @Override
19028        public void setValue(View object, float value) {
19029            object.setTranslationY(value);
19030        }
19031
19032        @Override
19033        public Float get(View object) {
19034            return object.getTranslationY();
19035        }
19036    };
19037
19038    /**
19039     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19040     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19041     */
19042    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19043        @Override
19044        public void setValue(View object, float value) {
19045            object.setTranslationZ(value);
19046        }
19047
19048        @Override
19049        public Float get(View object) {
19050            return object.getTranslationZ();
19051        }
19052    };
19053
19054    /**
19055     * A Property wrapper around the <code>x</code> functionality handled by the
19056     * {@link View#setX(float)} and {@link View#getX()} methods.
19057     */
19058    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19059        @Override
19060        public void setValue(View object, float value) {
19061            object.setX(value);
19062        }
19063
19064        @Override
19065        public Float get(View object) {
19066            return object.getX();
19067        }
19068    };
19069
19070    /**
19071     * A Property wrapper around the <code>y</code> functionality handled by the
19072     * {@link View#setY(float)} and {@link View#getY()} methods.
19073     */
19074    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19075        @Override
19076        public void setValue(View object, float value) {
19077            object.setY(value);
19078        }
19079
19080        @Override
19081        public Float get(View object) {
19082            return object.getY();
19083        }
19084    };
19085
19086    /**
19087     * A Property wrapper around the <code>z</code> functionality handled by the
19088     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19089     */
19090    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19091        @Override
19092        public void setValue(View object, float value) {
19093            object.setZ(value);
19094        }
19095
19096        @Override
19097        public Float get(View object) {
19098            return object.getZ();
19099        }
19100    };
19101
19102    /**
19103     * A Property wrapper around the <code>rotation</code> functionality handled by the
19104     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19105     */
19106    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19107        @Override
19108        public void setValue(View object, float value) {
19109            object.setRotation(value);
19110        }
19111
19112        @Override
19113        public Float get(View object) {
19114            return object.getRotation();
19115        }
19116    };
19117
19118    /**
19119     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19120     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19121     */
19122    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19123        @Override
19124        public void setValue(View object, float value) {
19125            object.setRotationX(value);
19126        }
19127
19128        @Override
19129        public Float get(View object) {
19130            return object.getRotationX();
19131        }
19132    };
19133
19134    /**
19135     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19136     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19137     */
19138    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19139        @Override
19140        public void setValue(View object, float value) {
19141            object.setRotationY(value);
19142        }
19143
19144        @Override
19145        public Float get(View object) {
19146            return object.getRotationY();
19147        }
19148    };
19149
19150    /**
19151     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19152     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19153     */
19154    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19155        @Override
19156        public void setValue(View object, float value) {
19157            object.setScaleX(value);
19158        }
19159
19160        @Override
19161        public Float get(View object) {
19162            return object.getScaleX();
19163        }
19164    };
19165
19166    /**
19167     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19168     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19169     */
19170    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19171        @Override
19172        public void setValue(View object, float value) {
19173            object.setScaleY(value);
19174        }
19175
19176        @Override
19177        public Float get(View object) {
19178            return object.getScaleY();
19179        }
19180    };
19181
19182    /**
19183     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19184     * Each MeasureSpec represents a requirement for either the width or the height.
19185     * A MeasureSpec is comprised of a size and a mode. There are three possible
19186     * modes:
19187     * <dl>
19188     * <dt>UNSPECIFIED</dt>
19189     * <dd>
19190     * The parent has not imposed any constraint on the child. It can be whatever size
19191     * it wants.
19192     * </dd>
19193     *
19194     * <dt>EXACTLY</dt>
19195     * <dd>
19196     * The parent has determined an exact size for the child. The child is going to be
19197     * given those bounds regardless of how big it wants to be.
19198     * </dd>
19199     *
19200     * <dt>AT_MOST</dt>
19201     * <dd>
19202     * The child can be as large as it wants up to the specified size.
19203     * </dd>
19204     * </dl>
19205     *
19206     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19207     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19208     */
19209    public static class MeasureSpec {
19210        private static final int MODE_SHIFT = 30;
19211        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19212
19213        /**
19214         * Measure specification mode: The parent has not imposed any constraint
19215         * on the child. It can be whatever size it wants.
19216         */
19217        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19218
19219        /**
19220         * Measure specification mode: The parent has determined an exact size
19221         * for the child. The child is going to be given those bounds regardless
19222         * of how big it wants to be.
19223         */
19224        public static final int EXACTLY     = 1 << MODE_SHIFT;
19225
19226        /**
19227         * Measure specification mode: The child can be as large as it wants up
19228         * to the specified size.
19229         */
19230        public static final int AT_MOST     = 2 << MODE_SHIFT;
19231
19232        /**
19233         * Creates a measure specification based on the supplied size and mode.
19234         *
19235         * The mode must always be one of the following:
19236         * <ul>
19237         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19238         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19239         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19240         * </ul>
19241         *
19242         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19243         * implementation was such that the order of arguments did not matter
19244         * and overflow in either value could impact the resulting MeasureSpec.
19245         * {@link android.widget.RelativeLayout} was affected by this bug.
19246         * Apps targeting API levels greater than 17 will get the fixed, more strict
19247         * behavior.</p>
19248         *
19249         * @param size the size of the measure specification
19250         * @param mode the mode of the measure specification
19251         * @return the measure specification based on size and mode
19252         */
19253        public static int makeMeasureSpec(int size, int mode) {
19254            if (sUseBrokenMakeMeasureSpec) {
19255                return size + mode;
19256            } else {
19257                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19258            }
19259        }
19260
19261        /**
19262         * Extracts the mode from the supplied measure specification.
19263         *
19264         * @param measureSpec the measure specification to extract the mode from
19265         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19266         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19267         *         {@link android.view.View.MeasureSpec#EXACTLY}
19268         */
19269        public static int getMode(int measureSpec) {
19270            return (measureSpec & MODE_MASK);
19271        }
19272
19273        /**
19274         * Extracts the size from the supplied measure specification.
19275         *
19276         * @param measureSpec the measure specification to extract the size from
19277         * @return the size in pixels defined in the supplied measure specification
19278         */
19279        public static int getSize(int measureSpec) {
19280            return (measureSpec & ~MODE_MASK);
19281        }
19282
19283        static int adjust(int measureSpec, int delta) {
19284            final int mode = getMode(measureSpec);
19285            if (mode == UNSPECIFIED) {
19286                // No need to adjust size for UNSPECIFIED mode.
19287                return makeMeasureSpec(0, UNSPECIFIED);
19288            }
19289            int size = getSize(measureSpec) + delta;
19290            if (size < 0) {
19291                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19292                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19293                size = 0;
19294            }
19295            return makeMeasureSpec(size, mode);
19296        }
19297
19298        /**
19299         * Returns a String representation of the specified measure
19300         * specification.
19301         *
19302         * @param measureSpec the measure specification to convert to a String
19303         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19304         */
19305        public static String toString(int measureSpec) {
19306            int mode = getMode(measureSpec);
19307            int size = getSize(measureSpec);
19308
19309            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19310
19311            if (mode == UNSPECIFIED)
19312                sb.append("UNSPECIFIED ");
19313            else if (mode == EXACTLY)
19314                sb.append("EXACTLY ");
19315            else if (mode == AT_MOST)
19316                sb.append("AT_MOST ");
19317            else
19318                sb.append(mode).append(" ");
19319
19320            sb.append(size);
19321            return sb.toString();
19322        }
19323    }
19324
19325    private final class CheckForLongPress implements Runnable {
19326        private int mOriginalWindowAttachCount;
19327
19328        @Override
19329        public void run() {
19330            if (isPressed() && (mParent != null)
19331                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19332                if (performLongClick()) {
19333                    mHasPerformedLongPress = true;
19334                }
19335            }
19336        }
19337
19338        public void rememberWindowAttachCount() {
19339            mOriginalWindowAttachCount = mWindowAttachCount;
19340        }
19341    }
19342
19343    private final class CheckForTap implements Runnable {
19344        public float x;
19345        public float y;
19346
19347        @Override
19348        public void run() {
19349            mPrivateFlags &= ~PFLAG_PREPRESSED;
19350            setPressed(true, x, y);
19351            checkForLongClick(ViewConfiguration.getTapTimeout());
19352        }
19353    }
19354
19355    private final class PerformClick implements Runnable {
19356        @Override
19357        public void run() {
19358            performClick();
19359        }
19360    }
19361
19362    /** @hide */
19363    public void hackTurnOffWindowResizeAnim(boolean off) {
19364        mAttachInfo.mTurnOffWindowResizeAnim = off;
19365    }
19366
19367    /**
19368     * This method returns a ViewPropertyAnimator object, which can be used to animate
19369     * specific properties on this View.
19370     *
19371     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19372     */
19373    public ViewPropertyAnimator animate() {
19374        if (mAnimator == null) {
19375            mAnimator = new ViewPropertyAnimator(this);
19376        }
19377        return mAnimator;
19378    }
19379
19380    /**
19381     * Sets the name of the View to be used to identify Views in Transitions.
19382     * Names should be unique in the View hierarchy.
19383     *
19384     * @param transitionName The name of the View to uniquely identify it for Transitions.
19385     */
19386    public final void setTransitionName(String transitionName) {
19387        mTransitionName = transitionName;
19388    }
19389
19390    /**
19391     * To be removed before L release.
19392     * @hide
19393     */
19394    public final void setViewName(String transitionName) {
19395        setTransitionName(transitionName);
19396    }
19397
19398    /**
19399     * Returns the name of the View to be used to identify Views in Transitions.
19400     * Names should be unique in the View hierarchy.
19401     *
19402     * <p>This returns null if the View has not been given a name.</p>
19403     *
19404     * @return The name used of the View to be used to identify Views in Transitions or null
19405     * if no name has been given.
19406     */
19407    public String getTransitionName() {
19408        return mTransitionName;
19409    }
19410
19411    /**
19412     * To be removed before L release.
19413     * @hide
19414     */
19415    public String getViewName() { return getTransitionName(); }
19416
19417    /**
19418     * Interface definition for a callback to be invoked when a hardware key event is
19419     * dispatched to this view. The callback will be invoked before the key event is
19420     * given to the view. This is only useful for hardware keyboards; a software input
19421     * method has no obligation to trigger this listener.
19422     */
19423    public interface OnKeyListener {
19424        /**
19425         * Called when a hardware key is dispatched to a view. This allows listeners to
19426         * get a chance to respond before the target view.
19427         * <p>Key presses in software keyboards will generally NOT trigger this method,
19428         * although some may elect to do so in some situations. Do not assume a
19429         * software input method has to be key-based; even if it is, it may use key presses
19430         * in a different way than you expect, so there is no way to reliably catch soft
19431         * input key presses.
19432         *
19433         * @param v The view the key has been dispatched to.
19434         * @param keyCode The code for the physical key that was pressed
19435         * @param event The KeyEvent object containing full information about
19436         *        the event.
19437         * @return True if the listener has consumed the event, false otherwise.
19438         */
19439        boolean onKey(View v, int keyCode, KeyEvent event);
19440    }
19441
19442    /**
19443     * Interface definition for a callback to be invoked when a touch event is
19444     * dispatched to this view. The callback will be invoked before the touch
19445     * event is given to the view.
19446     */
19447    public interface OnTouchListener {
19448        /**
19449         * Called when a touch event is dispatched to a view. This allows listeners to
19450         * get a chance to respond before the target view.
19451         *
19452         * @param v The view the touch event has been dispatched to.
19453         * @param event The MotionEvent object containing full information about
19454         *        the event.
19455         * @return True if the listener has consumed the event, false otherwise.
19456         */
19457        boolean onTouch(View v, MotionEvent event);
19458    }
19459
19460    /**
19461     * Interface definition for a callback to be invoked when a hover event is
19462     * dispatched to this view. The callback will be invoked before the hover
19463     * event is given to the view.
19464     */
19465    public interface OnHoverListener {
19466        /**
19467         * Called when a hover event is dispatched to a view. This allows listeners to
19468         * get a chance to respond before the target view.
19469         *
19470         * @param v The view the hover event has been dispatched to.
19471         * @param event The MotionEvent object containing full information about
19472         *        the event.
19473         * @return True if the listener has consumed the event, false otherwise.
19474         */
19475        boolean onHover(View v, MotionEvent event);
19476    }
19477
19478    /**
19479     * Interface definition for a callback to be invoked when a generic motion event is
19480     * dispatched to this view. The callback will be invoked before the generic motion
19481     * event is given to the view.
19482     */
19483    public interface OnGenericMotionListener {
19484        /**
19485         * Called when a generic motion event is dispatched to a view. This allows listeners to
19486         * get a chance to respond before the target view.
19487         *
19488         * @param v The view the generic motion event has been dispatched to.
19489         * @param event The MotionEvent object containing full information about
19490         *        the event.
19491         * @return True if the listener has consumed the event, false otherwise.
19492         */
19493        boolean onGenericMotion(View v, MotionEvent event);
19494    }
19495
19496    /**
19497     * Interface definition for a callback to be invoked when a view has been clicked and held.
19498     */
19499    public interface OnLongClickListener {
19500        /**
19501         * Called when a view has been clicked and held.
19502         *
19503         * @param v The view that was clicked and held.
19504         *
19505         * @return true if the callback consumed the long click, false otherwise.
19506         */
19507        boolean onLongClick(View v);
19508    }
19509
19510    /**
19511     * Interface definition for a callback to be invoked when a drag is being dispatched
19512     * to this view.  The callback will be invoked before the hosting view's own
19513     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19514     * onDrag(event) behavior, it should return 'false' from this callback.
19515     *
19516     * <div class="special reference">
19517     * <h3>Developer Guides</h3>
19518     * <p>For a guide to implementing drag and drop features, read the
19519     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19520     * </div>
19521     */
19522    public interface OnDragListener {
19523        /**
19524         * Called when a drag event is dispatched to a view. This allows listeners
19525         * to get a chance to override base View behavior.
19526         *
19527         * @param v The View that received the drag event.
19528         * @param event The {@link android.view.DragEvent} object for the drag event.
19529         * @return {@code true} if the drag event was handled successfully, or {@code false}
19530         * if the drag event was not handled. Note that {@code false} will trigger the View
19531         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19532         */
19533        boolean onDrag(View v, DragEvent event);
19534    }
19535
19536    /**
19537     * Interface definition for a callback to be invoked when the focus state of
19538     * a view changed.
19539     */
19540    public interface OnFocusChangeListener {
19541        /**
19542         * Called when the focus state of a view has changed.
19543         *
19544         * @param v The view whose state has changed.
19545         * @param hasFocus The new focus state of v.
19546         */
19547        void onFocusChange(View v, boolean hasFocus);
19548    }
19549
19550    /**
19551     * Interface definition for a callback to be invoked when a view is clicked.
19552     */
19553    public interface OnClickListener {
19554        /**
19555         * Called when a view has been clicked.
19556         *
19557         * @param v The view that was clicked.
19558         */
19559        void onClick(View v);
19560    }
19561
19562    /**
19563     * Interface definition for a callback to be invoked when the context menu
19564     * for this view is being built.
19565     */
19566    public interface OnCreateContextMenuListener {
19567        /**
19568         * Called when the context menu for this view is being built. It is not
19569         * safe to hold onto the menu after this method returns.
19570         *
19571         * @param menu The context menu that is being built
19572         * @param v The view for which the context menu is being built
19573         * @param menuInfo Extra information about the item for which the
19574         *            context menu should be shown. This information will vary
19575         *            depending on the class of v.
19576         */
19577        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19578    }
19579
19580    /**
19581     * Interface definition for a callback to be invoked when the status bar changes
19582     * visibility.  This reports <strong>global</strong> changes to the system UI
19583     * state, not what the application is requesting.
19584     *
19585     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19586     */
19587    public interface OnSystemUiVisibilityChangeListener {
19588        /**
19589         * Called when the status bar changes visibility because of a call to
19590         * {@link View#setSystemUiVisibility(int)}.
19591         *
19592         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19593         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19594         * This tells you the <strong>global</strong> state of these UI visibility
19595         * flags, not what your app is currently applying.
19596         */
19597        public void onSystemUiVisibilityChange(int visibility);
19598    }
19599
19600    /**
19601     * Interface definition for a callback to be invoked when this view is attached
19602     * or detached from its window.
19603     */
19604    public interface OnAttachStateChangeListener {
19605        /**
19606         * Called when the view is attached to a window.
19607         * @param v The view that was attached
19608         */
19609        public void onViewAttachedToWindow(View v);
19610        /**
19611         * Called when the view is detached from a window.
19612         * @param v The view that was detached
19613         */
19614        public void onViewDetachedFromWindow(View v);
19615    }
19616
19617    /**
19618     * Listener for applying window insets on a view in a custom way.
19619     *
19620     * <p>Apps may choose to implement this interface if they want to apply custom policy
19621     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19622     * is set, its
19623     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19624     * method will be called instead of the View's own
19625     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19626     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19627     * the View's normal behavior as part of its own.</p>
19628     */
19629    public interface OnApplyWindowInsetsListener {
19630        /**
19631         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19632         * on a View, this listener method will be called instead of the view's own
19633         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19634         *
19635         * @param v The view applying window insets
19636         * @param insets The insets to apply
19637         * @return The insets supplied, minus any insets that were consumed
19638         */
19639        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19640    }
19641
19642    private final class UnsetPressedState implements Runnable {
19643        @Override
19644        public void run() {
19645            setPressed(false);
19646        }
19647    }
19648
19649    /**
19650     * Base class for derived classes that want to save and restore their own
19651     * state in {@link android.view.View#onSaveInstanceState()}.
19652     */
19653    public static class BaseSavedState extends AbsSavedState {
19654        /**
19655         * Constructor used when reading from a parcel. Reads the state of the superclass.
19656         *
19657         * @param source
19658         */
19659        public BaseSavedState(Parcel source) {
19660            super(source);
19661        }
19662
19663        /**
19664         * Constructor called by derived classes when creating their SavedState objects
19665         *
19666         * @param superState The state of the superclass of this view
19667         */
19668        public BaseSavedState(Parcelable superState) {
19669            super(superState);
19670        }
19671
19672        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19673                new Parcelable.Creator<BaseSavedState>() {
19674            public BaseSavedState createFromParcel(Parcel in) {
19675                return new BaseSavedState(in);
19676            }
19677
19678            public BaseSavedState[] newArray(int size) {
19679                return new BaseSavedState[size];
19680            }
19681        };
19682    }
19683
19684    /**
19685     * A set of information given to a view when it is attached to its parent
19686     * window.
19687     */
19688    final static class AttachInfo {
19689        interface Callbacks {
19690            void playSoundEffect(int effectId);
19691            boolean performHapticFeedback(int effectId, boolean always);
19692        }
19693
19694        /**
19695         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19696         * to a Handler. This class contains the target (View) to invalidate and
19697         * the coordinates of the dirty rectangle.
19698         *
19699         * For performance purposes, this class also implements a pool of up to
19700         * POOL_LIMIT objects that get reused. This reduces memory allocations
19701         * whenever possible.
19702         */
19703        static class InvalidateInfo {
19704            private static final int POOL_LIMIT = 10;
19705
19706            private static final SynchronizedPool<InvalidateInfo> sPool =
19707                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19708
19709            View target;
19710
19711            int left;
19712            int top;
19713            int right;
19714            int bottom;
19715
19716            public static InvalidateInfo obtain() {
19717                InvalidateInfo instance = sPool.acquire();
19718                return (instance != null) ? instance : new InvalidateInfo();
19719            }
19720
19721            public void recycle() {
19722                target = null;
19723                sPool.release(this);
19724            }
19725        }
19726
19727        final IWindowSession mSession;
19728
19729        final IWindow mWindow;
19730
19731        final IBinder mWindowToken;
19732
19733        final Display mDisplay;
19734
19735        final Callbacks mRootCallbacks;
19736
19737        IWindowId mIWindowId;
19738        WindowId mWindowId;
19739
19740        /**
19741         * The top view of the hierarchy.
19742         */
19743        View mRootView;
19744
19745        IBinder mPanelParentWindowToken;
19746
19747        boolean mHardwareAccelerated;
19748        boolean mHardwareAccelerationRequested;
19749        HardwareRenderer mHardwareRenderer;
19750
19751        /**
19752         * The state of the display to which the window is attached, as reported
19753         * by {@link Display#getState()}.  Note that the display state constants
19754         * declared by {@link Display} do not exactly line up with the screen state
19755         * constants declared by {@link View} (there are more display states than
19756         * screen states).
19757         */
19758        int mDisplayState = Display.STATE_UNKNOWN;
19759
19760        /**
19761         * Scale factor used by the compatibility mode
19762         */
19763        float mApplicationScale;
19764
19765        /**
19766         * Indicates whether the application is in compatibility mode
19767         */
19768        boolean mScalingRequired;
19769
19770        /**
19771         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19772         */
19773        boolean mTurnOffWindowResizeAnim;
19774
19775        /**
19776         * Left position of this view's window
19777         */
19778        int mWindowLeft;
19779
19780        /**
19781         * Top position of this view's window
19782         */
19783        int mWindowTop;
19784
19785        /**
19786         * Indicates whether views need to use 32-bit drawing caches
19787         */
19788        boolean mUse32BitDrawingCache;
19789
19790        /**
19791         * For windows that are full-screen but using insets to layout inside
19792         * of the screen areas, these are the current insets to appear inside
19793         * the overscan area of the display.
19794         */
19795        final Rect mOverscanInsets = new Rect();
19796
19797        /**
19798         * For windows that are full-screen but using insets to layout inside
19799         * of the screen decorations, these are the current insets for the
19800         * content of the window.
19801         */
19802        final Rect mContentInsets = new Rect();
19803
19804        /**
19805         * For windows that are full-screen but using insets to layout inside
19806         * of the screen decorations, these are the current insets for the
19807         * actual visible parts of the window.
19808         */
19809        final Rect mVisibleInsets = new Rect();
19810
19811        /**
19812         * For windows that are full-screen but using insets to layout inside
19813         * of the screen decorations, these are the current insets for the
19814         * stable system windows.
19815         */
19816        final Rect mStableInsets = new Rect();
19817
19818        /**
19819         * The internal insets given by this window.  This value is
19820         * supplied by the client (through
19821         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19822         * be given to the window manager when changed to be used in laying
19823         * out windows behind it.
19824         */
19825        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19826                = new ViewTreeObserver.InternalInsetsInfo();
19827
19828        /**
19829         * Set to true when mGivenInternalInsets is non-empty.
19830         */
19831        boolean mHasNonEmptyGivenInternalInsets;
19832
19833        /**
19834         * All views in the window's hierarchy that serve as scroll containers,
19835         * used to determine if the window can be resized or must be panned
19836         * to adjust for a soft input area.
19837         */
19838        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19839
19840        final KeyEvent.DispatcherState mKeyDispatchState
19841                = new KeyEvent.DispatcherState();
19842
19843        /**
19844         * Indicates whether the view's window currently has the focus.
19845         */
19846        boolean mHasWindowFocus;
19847
19848        /**
19849         * The current visibility of the window.
19850         */
19851        int mWindowVisibility;
19852
19853        /**
19854         * Indicates the time at which drawing started to occur.
19855         */
19856        long mDrawingTime;
19857
19858        /**
19859         * Indicates whether or not ignoring the DIRTY_MASK flags.
19860         */
19861        boolean mIgnoreDirtyState;
19862
19863        /**
19864         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19865         * to avoid clearing that flag prematurely.
19866         */
19867        boolean mSetIgnoreDirtyState = false;
19868
19869        /**
19870         * Indicates whether the view's window is currently in touch mode.
19871         */
19872        boolean mInTouchMode;
19873
19874        /**
19875         * Indicates whether the view has requested unbuffered input dispatching for the current
19876         * event stream.
19877         */
19878        boolean mUnbufferedDispatchRequested;
19879
19880        /**
19881         * Indicates that ViewAncestor should trigger a global layout change
19882         * the next time it performs a traversal
19883         */
19884        boolean mRecomputeGlobalAttributes;
19885
19886        /**
19887         * Always report new attributes at next traversal.
19888         */
19889        boolean mForceReportNewAttributes;
19890
19891        /**
19892         * Set during a traveral if any views want to keep the screen on.
19893         */
19894        boolean mKeepScreenOn;
19895
19896        /**
19897         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19898         */
19899        int mSystemUiVisibility;
19900
19901        /**
19902         * Hack to force certain system UI visibility flags to be cleared.
19903         */
19904        int mDisabledSystemUiVisibility;
19905
19906        /**
19907         * Last global system UI visibility reported by the window manager.
19908         */
19909        int mGlobalSystemUiVisibility;
19910
19911        /**
19912         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19913         * attached.
19914         */
19915        boolean mHasSystemUiListeners;
19916
19917        /**
19918         * Set if the window has requested to extend into the overscan region
19919         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19920         */
19921        boolean mOverscanRequested;
19922
19923        /**
19924         * Set if the visibility of any views has changed.
19925         */
19926        boolean mViewVisibilityChanged;
19927
19928        /**
19929         * Set to true if a view has been scrolled.
19930         */
19931        boolean mViewScrollChanged;
19932
19933        /**
19934         * Global to the view hierarchy used as a temporary for dealing with
19935         * x/y points in the transparent region computations.
19936         */
19937        final int[] mTransparentLocation = new int[2];
19938
19939        /**
19940         * Global to the view hierarchy used as a temporary for dealing with
19941         * x/y points in the ViewGroup.invalidateChild implementation.
19942         */
19943        final int[] mInvalidateChildLocation = new int[2];
19944
19945        /**
19946         * Global to the view hierarchy used as a temporary for dealng with
19947         * computing absolute on-screen location.
19948         */
19949        final int[] mTmpLocation = new int[2];
19950
19951        /**
19952         * Global to the view hierarchy used as a temporary for dealing with
19953         * x/y location when view is transformed.
19954         */
19955        final float[] mTmpTransformLocation = new float[2];
19956
19957        /**
19958         * The view tree observer used to dispatch global events like
19959         * layout, pre-draw, touch mode change, etc.
19960         */
19961        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19962
19963        /**
19964         * A Canvas used by the view hierarchy to perform bitmap caching.
19965         */
19966        Canvas mCanvas;
19967
19968        /**
19969         * The view root impl.
19970         */
19971        final ViewRootImpl mViewRootImpl;
19972
19973        /**
19974         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19975         * handler can be used to pump events in the UI events queue.
19976         */
19977        final Handler mHandler;
19978
19979        /**
19980         * Temporary for use in computing invalidate rectangles while
19981         * calling up the hierarchy.
19982         */
19983        final Rect mTmpInvalRect = new Rect();
19984
19985        /**
19986         * Temporary for use in computing hit areas with transformed views
19987         */
19988        final RectF mTmpTransformRect = new RectF();
19989
19990        /**
19991         * Temporary for use in transforming invalidation rect
19992         */
19993        final Matrix mTmpMatrix = new Matrix();
19994
19995        /**
19996         * Temporary for use in transforming invalidation rect
19997         */
19998        final Transformation mTmpTransformation = new Transformation();
19999
20000        /**
20001         * Temporary for use in querying outlines from OutlineProviders
20002         */
20003        final Outline mTmpOutline = new Outline();
20004
20005        /**
20006         * Temporary list for use in collecting focusable descendents of a view.
20007         */
20008        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20009
20010        /**
20011         * The id of the window for accessibility purposes.
20012         */
20013        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20014
20015        /**
20016         * Flags related to accessibility processing.
20017         *
20018         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20019         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20020         */
20021        int mAccessibilityFetchFlags;
20022
20023        /**
20024         * The drawable for highlighting accessibility focus.
20025         */
20026        Drawable mAccessibilityFocusDrawable;
20027
20028        /**
20029         * Show where the margins, bounds and layout bounds are for each view.
20030         */
20031        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20032
20033        /**
20034         * Point used to compute visible regions.
20035         */
20036        final Point mPoint = new Point();
20037
20038        /**
20039         * Used to track which View originated a requestLayout() call, used when
20040         * requestLayout() is called during layout.
20041         */
20042        View mViewRequestingLayout;
20043
20044        /**
20045         * Creates a new set of attachment information with the specified
20046         * events handler and thread.
20047         *
20048         * @param handler the events handler the view must use
20049         */
20050        AttachInfo(IWindowSession session, IWindow window, Display display,
20051                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20052            mSession = session;
20053            mWindow = window;
20054            mWindowToken = window.asBinder();
20055            mDisplay = display;
20056            mViewRootImpl = viewRootImpl;
20057            mHandler = handler;
20058            mRootCallbacks = effectPlayer;
20059        }
20060    }
20061
20062    /**
20063     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20064     * is supported. This avoids keeping too many unused fields in most
20065     * instances of View.</p>
20066     */
20067    private static class ScrollabilityCache implements Runnable {
20068
20069        /**
20070         * Scrollbars are not visible
20071         */
20072        public static final int OFF = 0;
20073
20074        /**
20075         * Scrollbars are visible
20076         */
20077        public static final int ON = 1;
20078
20079        /**
20080         * Scrollbars are fading away
20081         */
20082        public static final int FADING = 2;
20083
20084        public boolean fadeScrollBars;
20085
20086        public int fadingEdgeLength;
20087        public int scrollBarDefaultDelayBeforeFade;
20088        public int scrollBarFadeDuration;
20089
20090        public int scrollBarSize;
20091        public ScrollBarDrawable scrollBar;
20092        public float[] interpolatorValues;
20093        public View host;
20094
20095        public final Paint paint;
20096        public final Matrix matrix;
20097        public Shader shader;
20098
20099        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20100
20101        private static final float[] OPAQUE = { 255 };
20102        private static final float[] TRANSPARENT = { 0.0f };
20103
20104        /**
20105         * When fading should start. This time moves into the future every time
20106         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20107         */
20108        public long fadeStartTime;
20109
20110
20111        /**
20112         * The current state of the scrollbars: ON, OFF, or FADING
20113         */
20114        public int state = OFF;
20115
20116        private int mLastColor;
20117
20118        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20119            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20120            scrollBarSize = configuration.getScaledScrollBarSize();
20121            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20122            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20123
20124            paint = new Paint();
20125            matrix = new Matrix();
20126            // use use a height of 1, and then wack the matrix each time we
20127            // actually use it.
20128            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20129            paint.setShader(shader);
20130            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20131
20132            this.host = host;
20133        }
20134
20135        public void setFadeColor(int color) {
20136            if (color != mLastColor) {
20137                mLastColor = color;
20138
20139                if (color != 0) {
20140                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20141                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20142                    paint.setShader(shader);
20143                    // Restore the default transfer mode (src_over)
20144                    paint.setXfermode(null);
20145                } else {
20146                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20147                    paint.setShader(shader);
20148                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20149                }
20150            }
20151        }
20152
20153        public void run() {
20154            long now = AnimationUtils.currentAnimationTimeMillis();
20155            if (now >= fadeStartTime) {
20156
20157                // the animation fades the scrollbars out by changing
20158                // the opacity (alpha) from fully opaque to fully
20159                // transparent
20160                int nextFrame = (int) now;
20161                int framesCount = 0;
20162
20163                Interpolator interpolator = scrollBarInterpolator;
20164
20165                // Start opaque
20166                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20167
20168                // End transparent
20169                nextFrame += scrollBarFadeDuration;
20170                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20171
20172                state = FADING;
20173
20174                // Kick off the fade animation
20175                host.invalidate(true);
20176            }
20177        }
20178    }
20179
20180    /**
20181     * Resuable callback for sending
20182     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20183     */
20184    private class SendViewScrolledAccessibilityEvent implements Runnable {
20185        public volatile boolean mIsPending;
20186
20187        public void run() {
20188            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20189            mIsPending = false;
20190        }
20191    }
20192
20193    /**
20194     * <p>
20195     * This class represents a delegate that can be registered in a {@link View}
20196     * to enhance accessibility support via composition rather via inheritance.
20197     * It is specifically targeted to widget developers that extend basic View
20198     * classes i.e. classes in package android.view, that would like their
20199     * applications to be backwards compatible.
20200     * </p>
20201     * <div class="special reference">
20202     * <h3>Developer Guides</h3>
20203     * <p>For more information about making applications accessible, read the
20204     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20205     * developer guide.</p>
20206     * </div>
20207     * <p>
20208     * A scenario in which a developer would like to use an accessibility delegate
20209     * is overriding a method introduced in a later API version then the minimal API
20210     * version supported by the application. For example, the method
20211     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20212     * in API version 4 when the accessibility APIs were first introduced. If a
20213     * developer would like his application to run on API version 4 devices (assuming
20214     * all other APIs used by the application are version 4 or lower) and take advantage
20215     * of this method, instead of overriding the method which would break the application's
20216     * backwards compatibility, he can override the corresponding method in this
20217     * delegate and register the delegate in the target View if the API version of
20218     * the system is high enough i.e. the API version is same or higher to the API
20219     * version that introduced
20220     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20221     * </p>
20222     * <p>
20223     * Here is an example implementation:
20224     * </p>
20225     * <code><pre><p>
20226     * if (Build.VERSION.SDK_INT >= 14) {
20227     *     // If the API version is equal of higher than the version in
20228     *     // which onInitializeAccessibilityNodeInfo was introduced we
20229     *     // register a delegate with a customized implementation.
20230     *     View view = findViewById(R.id.view_id);
20231     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20232     *         public void onInitializeAccessibilityNodeInfo(View host,
20233     *                 AccessibilityNodeInfo info) {
20234     *             // Let the default implementation populate the info.
20235     *             super.onInitializeAccessibilityNodeInfo(host, info);
20236     *             // Set some other information.
20237     *             info.setEnabled(host.isEnabled());
20238     *         }
20239     *     });
20240     * }
20241     * </code></pre></p>
20242     * <p>
20243     * This delegate contains methods that correspond to the accessibility methods
20244     * in View. If a delegate has been specified the implementation in View hands
20245     * off handling to the corresponding method in this delegate. The default
20246     * implementation the delegate methods behaves exactly as the corresponding
20247     * method in View for the case of no accessibility delegate been set. Hence,
20248     * to customize the behavior of a View method, clients can override only the
20249     * corresponding delegate method without altering the behavior of the rest
20250     * accessibility related methods of the host view.
20251     * </p>
20252     */
20253    public static class AccessibilityDelegate {
20254
20255        /**
20256         * Sends an accessibility event of the given type. If accessibility is not
20257         * enabled this method has no effect.
20258         * <p>
20259         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20260         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20261         * been set.
20262         * </p>
20263         *
20264         * @param host The View hosting the delegate.
20265         * @param eventType The type of the event to send.
20266         *
20267         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20268         */
20269        public void sendAccessibilityEvent(View host, int eventType) {
20270            host.sendAccessibilityEventInternal(eventType);
20271        }
20272
20273        /**
20274         * Performs the specified accessibility action on the view. For
20275         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20276         * <p>
20277         * The default implementation behaves as
20278         * {@link View#performAccessibilityAction(int, Bundle)
20279         *  View#performAccessibilityAction(int, Bundle)} for the case of
20280         *  no accessibility delegate been set.
20281         * </p>
20282         *
20283         * @param action The action to perform.
20284         * @return Whether the action was performed.
20285         *
20286         * @see View#performAccessibilityAction(int, Bundle)
20287         *      View#performAccessibilityAction(int, Bundle)
20288         */
20289        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20290            return host.performAccessibilityActionInternal(action, args);
20291        }
20292
20293        /**
20294         * Sends an accessibility event. This method behaves exactly as
20295         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20296         * empty {@link AccessibilityEvent} and does not perform a check whether
20297         * accessibility is enabled.
20298         * <p>
20299         * The default implementation behaves as
20300         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20301         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20302         * the case of no accessibility delegate been set.
20303         * </p>
20304         *
20305         * @param host The View hosting the delegate.
20306         * @param event The event to send.
20307         *
20308         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20309         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20310         */
20311        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20312            host.sendAccessibilityEventUncheckedInternal(event);
20313        }
20314
20315        /**
20316         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20317         * to its children for adding their text content to the event.
20318         * <p>
20319         * The default implementation behaves as
20320         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20321         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20322         * the case of no accessibility delegate been set.
20323         * </p>
20324         *
20325         * @param host The View hosting the delegate.
20326         * @param event The event.
20327         * @return True if the event population was completed.
20328         *
20329         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20330         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20331         */
20332        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20333            return host.dispatchPopulateAccessibilityEventInternal(event);
20334        }
20335
20336        /**
20337         * Gives a chance to the host View to populate the accessibility event with its
20338         * text content.
20339         * <p>
20340         * The default implementation behaves as
20341         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20342         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20343         * the case of no accessibility delegate been set.
20344         * </p>
20345         *
20346         * @param host The View hosting the delegate.
20347         * @param event The accessibility event which to populate.
20348         *
20349         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20350         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20351         */
20352        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20353            host.onPopulateAccessibilityEventInternal(event);
20354        }
20355
20356        /**
20357         * Initializes an {@link AccessibilityEvent} with information about the
20358         * the host View which is the event source.
20359         * <p>
20360         * The default implementation behaves as
20361         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20362         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20363         * the case of no accessibility delegate been set.
20364         * </p>
20365         *
20366         * @param host The View hosting the delegate.
20367         * @param event The event to initialize.
20368         *
20369         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20370         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20371         */
20372        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20373            host.onInitializeAccessibilityEventInternal(event);
20374        }
20375
20376        /**
20377         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20378         * <p>
20379         * The default implementation behaves as
20380         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20381         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20382         * the case of no accessibility delegate been set.
20383         * </p>
20384         *
20385         * @param host The View hosting the delegate.
20386         * @param info The instance to initialize.
20387         *
20388         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20389         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20390         */
20391        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20392            host.onInitializeAccessibilityNodeInfoInternal(info);
20393        }
20394
20395        /**
20396         * Called when a child of the host View has requested sending an
20397         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20398         * to augment the event.
20399         * <p>
20400         * The default implementation behaves as
20401         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20402         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20403         * the case of no accessibility delegate been set.
20404         * </p>
20405         *
20406         * @param host The View hosting the delegate.
20407         * @param child The child which requests sending the event.
20408         * @param event The event to be sent.
20409         * @return True if the event should be sent
20410         *
20411         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20412         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20413         */
20414        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20415                AccessibilityEvent event) {
20416            return host.onRequestSendAccessibilityEventInternal(child, event);
20417        }
20418
20419        /**
20420         * Gets the provider for managing a virtual view hierarchy rooted at this View
20421         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20422         * that explore the window content.
20423         * <p>
20424         * The default implementation behaves as
20425         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20426         * the case of no accessibility delegate been set.
20427         * </p>
20428         *
20429         * @return The provider.
20430         *
20431         * @see AccessibilityNodeProvider
20432         */
20433        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20434            return null;
20435        }
20436
20437        /**
20438         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20439         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20440         * This method is responsible for obtaining an accessibility node info from a
20441         * pool of reusable instances and calling
20442         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20443         * view to initialize the former.
20444         * <p>
20445         * <strong>Note:</strong> The client is responsible for recycling the obtained
20446         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20447         * creation.
20448         * </p>
20449         * <p>
20450         * The default implementation behaves as
20451         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20452         * the case of no accessibility delegate been set.
20453         * </p>
20454         * @return A populated {@link AccessibilityNodeInfo}.
20455         *
20456         * @see AccessibilityNodeInfo
20457         *
20458         * @hide
20459         */
20460        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20461            return host.createAccessibilityNodeInfoInternal();
20462        }
20463    }
20464
20465    private class MatchIdPredicate implements Predicate<View> {
20466        public int mId;
20467
20468        @Override
20469        public boolean apply(View view) {
20470            return (view.mID == mId);
20471        }
20472    }
20473
20474    private class MatchLabelForPredicate implements Predicate<View> {
20475        private int mLabeledId;
20476
20477        @Override
20478        public boolean apply(View view) {
20479            return (view.mLabelForId == mLabeledId);
20480        }
20481    }
20482
20483    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20484        private int mChangeTypes = 0;
20485        private boolean mPosted;
20486        private boolean mPostedWithDelay;
20487        private long mLastEventTimeMillis;
20488
20489        @Override
20490        public void run() {
20491            mPosted = false;
20492            mPostedWithDelay = false;
20493            mLastEventTimeMillis = SystemClock.uptimeMillis();
20494            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20495                final AccessibilityEvent event = AccessibilityEvent.obtain();
20496                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20497                event.setContentChangeTypes(mChangeTypes);
20498                sendAccessibilityEventUnchecked(event);
20499            }
20500            mChangeTypes = 0;
20501        }
20502
20503        public void runOrPost(int changeType) {
20504            mChangeTypes |= changeType;
20505
20506            // If this is a live region or the child of a live region, collect
20507            // all events from this frame and send them on the next frame.
20508            if (inLiveRegion()) {
20509                // If we're already posted with a delay, remove that.
20510                if (mPostedWithDelay) {
20511                    removeCallbacks(this);
20512                    mPostedWithDelay = false;
20513                }
20514                // Only post if we're not already posted.
20515                if (!mPosted) {
20516                    post(this);
20517                    mPosted = true;
20518                }
20519                return;
20520            }
20521
20522            if (mPosted) {
20523                return;
20524            }
20525            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20526            final long minEventIntevalMillis =
20527                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20528            if (timeSinceLastMillis >= minEventIntevalMillis) {
20529                removeCallbacks(this);
20530                run();
20531            } else {
20532                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20533                mPosted = true;
20534                mPostedWithDelay = true;
20535            }
20536        }
20537    }
20538
20539    private boolean inLiveRegion() {
20540        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20541            return true;
20542        }
20543
20544        ViewParent parent = getParent();
20545        while (parent instanceof View) {
20546            if (((View) parent).getAccessibilityLiveRegion()
20547                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20548                return true;
20549            }
20550            parent = parent.getParent();
20551        }
20552
20553        return false;
20554    }
20555
20556    /**
20557     * Dump all private flags in readable format, useful for documentation and
20558     * sanity checking.
20559     */
20560    private static void dumpFlags() {
20561        final HashMap<String, String> found = Maps.newHashMap();
20562        try {
20563            for (Field field : View.class.getDeclaredFields()) {
20564                final int modifiers = field.getModifiers();
20565                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20566                    if (field.getType().equals(int.class)) {
20567                        final int value = field.getInt(null);
20568                        dumpFlag(found, field.getName(), value);
20569                    } else if (field.getType().equals(int[].class)) {
20570                        final int[] values = (int[]) field.get(null);
20571                        for (int i = 0; i < values.length; i++) {
20572                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20573                        }
20574                    }
20575                }
20576            }
20577        } catch (IllegalAccessException e) {
20578            throw new RuntimeException(e);
20579        }
20580
20581        final ArrayList<String> keys = Lists.newArrayList();
20582        keys.addAll(found.keySet());
20583        Collections.sort(keys);
20584        for (String key : keys) {
20585            Log.d(VIEW_LOG_TAG, found.get(key));
20586        }
20587    }
20588
20589    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20590        // Sort flags by prefix, then by bits, always keeping unique keys
20591        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20592        final int prefix = name.indexOf('_');
20593        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20594        final String output = bits + " " + name;
20595        found.put(key, output);
20596    }
20597}
20598