View.java revision e4cf152cb766784b514f99caf82da5648e5de358
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.PixelFormat;
39import android.graphics.Point;
40import android.graphics.PorterDuff;
41import android.graphics.PorterDuffXfermode;
42import android.graphics.Rect;
43import android.graphics.RectF;
44import android.graphics.Region;
45import android.graphics.Shader;
46import android.graphics.drawable.ColorDrawable;
47import android.graphics.drawable.Drawable;
48import android.hardware.display.DisplayManagerGlobal;
49import android.os.Bundle;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.Parcel;
53import android.os.Parcelable;
54import android.os.RemoteException;
55import android.os.SystemClock;
56import android.os.SystemProperties;
57import android.text.TextUtils;
58import android.util.AttributeSet;
59import android.util.FloatProperty;
60import android.util.LayoutDirection;
61import android.util.Log;
62import android.util.LongSparseLongArray;
63import android.util.Pools.SynchronizedPool;
64import android.util.Property;
65import android.util.SparseArray;
66import android.util.SuperNotCalledException;
67import android.util.TypedValue;
68import android.view.ContextMenu.ContextMenuInfo;
69import android.view.AccessibilityIterators.TextSegmentIterator;
70import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
71import android.view.AccessibilityIterators.WordTextSegmentIterator;
72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
73import android.view.accessibility.AccessibilityEvent;
74import android.view.accessibility.AccessibilityEventSource;
75import android.view.accessibility.AccessibilityManager;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeProvider;
78import android.view.animation.Animation;
79import android.view.animation.AnimationUtils;
80import android.view.animation.Transformation;
81import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.ScrollBarDrawable;
85
86import static android.os.Build.VERSION_CODES.*;
87import static java.lang.Math.max;
88
89import com.android.internal.R;
90import com.android.internal.util.Predicate;
91import com.android.internal.view.menu.MenuBuilder;
92
93import com.google.android.collect.Lists;
94import com.google.android.collect.Maps;
95
96import java.lang.annotation.Retention;
97import java.lang.annotation.RetentionPolicy;
98import java.lang.ref.WeakReference;
99import java.lang.reflect.Field;
100import java.lang.reflect.InvocationTargetException;
101import java.lang.reflect.Method;
102import java.lang.reflect.Modifier;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.HashMap;
107import java.util.List;
108import java.util.Locale;
109import java.util.Map;
110import java.util.concurrent.CopyOnWriteArrayList;
111import java.util.concurrent.atomic.AtomicInteger;
112
113/**
114 * <p>
115 * This class represents the basic building block for user interface components. A View
116 * occupies a rectangular area on the screen and is responsible for drawing and
117 * event handling. View is the base class for <em>widgets</em>, which are
118 * used to create interactive UI components (buttons, text fields, etc.). The
119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
120 * are invisible containers that hold other Views (or other ViewGroups) and define
121 * their layout properties.
122 * </p>
123 *
124 * <div class="special reference">
125 * <h3>Developer Guides</h3>
126 * <p>For information about using this class to develop your application's user interface,
127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
128 * </div>
129 *
130 * <a name="Using"></a>
131 * <h3>Using Views</h3>
132 * <p>
133 * All of the views in a window are arranged in a single tree. You can add views
134 * either from code or by specifying a tree of views in one or more XML layout
135 * files. There are many specialized subclasses of views that act as controls or
136 * are capable of displaying text, images, or other content.
137 * </p>
138 * <p>
139 * Once you have created a tree of views, there are typically a few types of
140 * common operations you may wish to perform:
141 * <ul>
142 * <li><strong>Set properties:</strong> for example setting the text of a
143 * {@link android.widget.TextView}. The available properties and the methods
144 * that set them will vary among the different subclasses of views. Note that
145 * properties that are known at build time can be set in the XML layout
146 * files.</li>
147 * <li><strong>Set focus:</strong> The framework will handled moving focus in
148 * response to user input. To force focus to a specific view, call
149 * {@link #requestFocus}.</li>
150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
151 * that will be notified when something interesting happens to the view. For
152 * example, all views will let you set a listener to be notified when the view
153 * gains or loses focus. You can register such a listener using
154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
155 * Other view subclasses offer more specialized listeners. For example, a Button
156 * exposes a listener to notify clients when the button is clicked.</li>
157 * <li><strong>Set visibility:</strong> You can hide or show views using
158 * {@link #setVisibility(int)}.</li>
159 * </ul>
160 * </p>
161 * <p><em>
162 * Note: The Android framework is responsible for measuring, laying out and
163 * drawing views. You should not call methods that perform these actions on
164 * views yourself unless you are actually implementing a
165 * {@link android.view.ViewGroup}.
166 * </em></p>
167 *
168 * <a name="Lifecycle"></a>
169 * <h3>Implementing a Custom View</h3>
170 *
171 * <p>
172 * To implement a custom view, you will usually begin by providing overrides for
173 * some of the standard methods that the framework calls on all views. You do
174 * not need to override all of these methods. In fact, you can start by just
175 * overriding {@link #onDraw(android.graphics.Canvas)}.
176 * <table border="2" width="85%" align="center" cellpadding="5">
177 *     <thead>
178 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
179 *     </thead>
180 *
181 *     <tbody>
182 *     <tr>
183 *         <td rowspan="2">Creation</td>
184 *         <td>Constructors</td>
185 *         <td>There is a form of the constructor that are called when the view
186 *         is created from code and a form that is called when the view is
187 *         inflated from a layout file. The second form should parse and apply
188 *         any attributes defined in the layout file.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onFinishInflate()}</code></td>
193 *         <td>Called after a view and all of its children has been inflated
194 *         from XML.</td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="3">Layout</td>
199 *         <td><code>{@link #onMeasure(int, int)}</code></td>
200 *         <td>Called to determine the size requirements for this view and all
201 *         of its children.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
206 *         <td>Called when this view should assign a size and position to all
207 *         of its children.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
212 *         <td>Called when the size of this view has changed.
213 *         </td>
214 *     </tr>
215 *
216 *     <tr>
217 *         <td>Drawing</td>
218 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
219 *         <td>Called when the view should render its content.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="4">Event processing</td>
225 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
226 *         <td>Called when a new hardware key event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
231 *         <td>Called when a hardware key up event occurs.
232 *         </td>
233 *     </tr>
234 *     <tr>
235 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
236 *         <td>Called when a trackball motion event occurs.
237 *         </td>
238 *     </tr>
239 *     <tr>
240 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
241 *         <td>Called when a touch screen motion event occurs.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="2">Focus</td>
247 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
248 *         <td>Called when the view gains or loses focus.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
254 *         <td>Called when the window containing the view gains or loses focus.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="3">Attaching</td>
260 *         <td><code>{@link #onAttachedToWindow()}</code></td>
261 *         <td>Called when the view is attached to a window.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onDetachedFromWindow}</code></td>
267 *         <td>Called when the view is detached from its window.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
273 *         <td>Called when the visibility of the window containing the view
274 *         has changed.
275 *         </td>
276 *     </tr>
277 *     </tbody>
278 *
279 * </table>
280 * </p>
281 *
282 * <a name="IDs"></a>
283 * <h3>IDs</h3>
284 * Views may have an integer id associated with them. These ids are typically
285 * assigned in the layout XML files, and are used to find specific views within
286 * the view tree. A common pattern is to:
287 * <ul>
288 * <li>Define a Button in the layout file and assign it a unique ID.
289 * <pre>
290 * &lt;Button
291 *     android:id="@+id/my_button"
292 *     android:layout_width="wrap_content"
293 *     android:layout_height="wrap_content"
294 *     android:text="@string/my_button_text"/&gt;
295 * </pre></li>
296 * <li>From the onCreate method of an Activity, find the Button
297 * <pre class="prettyprint">
298 *      Button myButton = (Button) findViewById(R.id.my_button);
299 * </pre></li>
300 * </ul>
301 * <p>
302 * View IDs need not be unique throughout the tree, but it is good practice to
303 * ensure that they are at least unique within the part of the tree you are
304 * searching.
305 * </p>
306 *
307 * <a name="Position"></a>
308 * <h3>Position</h3>
309 * <p>
310 * The geometry of a view is that of a rectangle. A view has a location,
311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
312 * two dimensions, expressed as a width and a height. The unit for location
313 * and dimensions is the pixel.
314 * </p>
315 *
316 * <p>
317 * It is possible to retrieve the location of a view by invoking the methods
318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
319 * coordinate of the rectangle representing the view. The latter returns the
320 * top, or Y, coordinate of the rectangle representing the view. These methods
321 * both return the location of the view relative to its parent. For instance,
322 * when getLeft() returns 20, that means the view is located 20 pixels to the
323 * right of the left edge of its direct parent.
324 * </p>
325 *
326 * <p>
327 * In addition, several convenience methods are offered to avoid unnecessary
328 * computations, namely {@link #getRight()} and {@link #getBottom()}.
329 * These methods return the coordinates of the right and bottom edges of the
330 * rectangle representing the view. For instance, calling {@link #getRight()}
331 * is similar to the following computation: <code>getLeft() + getWidth()</code>
332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
333 * </p>
334 *
335 * <a name="SizePaddingMargins"></a>
336 * <h3>Size, padding and margins</h3>
337 * <p>
338 * The size of a view is expressed with a width and a height. A view actually
339 * possess two pairs of width and height values.
340 * </p>
341 *
342 * <p>
343 * The first pair is known as <em>measured width</em> and
344 * <em>measured height</em>. These dimensions define how big a view wants to be
345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
347 * and {@link #getMeasuredHeight()}.
348 * </p>
349 *
350 * <p>
351 * The second pair is simply known as <em>width</em> and <em>height</em>, or
352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
353 * dimensions define the actual size of the view on screen, at drawing time and
354 * after layout. These values may, but do not have to, be different from the
355 * measured width and height. The width and height can be obtained by calling
356 * {@link #getWidth()} and {@link #getHeight()}.
357 * </p>
358 *
359 * <p>
360 * To measure its dimensions, a view takes into account its padding. The padding
361 * is expressed in pixels for the left, top, right and bottom parts of the view.
362 * Padding can be used to offset the content of the view by a specific amount of
363 * pixels. For instance, a left padding of 2 will push the view's content by
364 * 2 pixels to the right of the left edge. Padding can be set using the
365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
368 * {@link #getPaddingEnd()}.
369 * </p>
370 *
371 * <p>
372 * Even though a view can define a padding, it does not provide any support for
373 * margins. However, view groups provide such a support. Refer to
374 * {@link android.view.ViewGroup} and
375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
376 * </p>
377 *
378 * <a name="Layout"></a>
379 * <h3>Layout</h3>
380 * <p>
381 * Layout is a two pass process: a measure pass and a layout pass. The measuring
382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
383 * of the view tree. Each view pushes dimension specifications down the tree
384 * during the recursion. At the end of the measure pass, every view has stored
385 * its measurements. The second pass happens in
386 * {@link #layout(int,int,int,int)} and is also top-down. During
387 * this pass each parent is responsible for positioning all of its children
388 * using the sizes computed in the measure pass.
389 * </p>
390 *
391 * <p>
392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
393 * {@link #getMeasuredHeight()} values must be set, along with those for all of
394 * that view's descendants. A view's measured width and measured height values
395 * must respect the constraints imposed by the view's parents. This guarantees
396 * that at the end of the measure pass, all parents accept all of their
397 * children's measurements. A parent view may call measure() more than once on
398 * its children. For example, the parent may measure each child once with
399 * unspecified dimensions to find out how big they want to be, then call
400 * measure() on them again with actual numbers if the sum of all the children's
401 * unconstrained sizes is too big or too small.
402 * </p>
403 *
404 * <p>
405 * The measure pass uses two classes to communicate dimensions. The
406 * {@link MeasureSpec} class is used by views to tell their parents how they
407 * want to be measured and positioned. The base LayoutParams class just
408 * describes how big the view wants to be for both width and height. For each
409 * dimension, it can specify one of:
410 * <ul>
411 * <li> an exact number
412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
413 * (minus padding)
414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
415 * enclose its content (plus padding).
416 * </ul>
417 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
419 * an X and Y value.
420 * </p>
421 *
422 * <p>
423 * MeasureSpecs are used to push requirements down the tree from parent to
424 * child. A MeasureSpec can be in one of three modes:
425 * <ul>
426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
427 * of a child view. For example, a LinearLayout may call measure() on its child
428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
429 * tall the child view wants to be given a width of 240 pixels.
430 * <li>EXACTLY: This is used by the parent to impose an exact size on the
431 * child. The child must use this size, and guarantee that all of its
432 * descendants will fit within this size.
433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
434 * child. The child must guarantee that it and all of its descendants will fit
435 * within this size.
436 * </ul>
437 * </p>
438 *
439 * <p>
440 * To intiate a layout, call {@link #requestLayout}. This method is typically
441 * called by a view on itself when it believes that is can no longer fit within
442 * its current bounds.
443 * </p>
444 *
445 * <a name="Drawing"></a>
446 * <h3>Drawing</h3>
447 * <p>
448 * Drawing is handled by walking the tree and rendering each view that
449 * intersects the invalid region. Because the tree is traversed in-order,
450 * this means that parents will draw before (i.e., behind) their children, with
451 * siblings drawn in the order they appear in the tree.
452 * If you set a background drawable for a View, then the View will draw it for you
453 * before calling back to its <code>onDraw()</code> method.
454 * </p>
455 *
456 * <p>
457 * Note that the framework will not draw views that are not in the invalid region.
458 * </p>
459 *
460 * <p>
461 * To force a view to draw, call {@link #invalidate()}.
462 * </p>
463 *
464 * <a name="EventHandlingThreading"></a>
465 * <h3>Event Handling and Threading</h3>
466 * <p>
467 * The basic cycle of a view is as follows:
468 * <ol>
469 * <li>An event comes in and is dispatched to the appropriate view. The view
470 * handles the event and notifies any listeners.</li>
471 * <li>If in the course of processing the event, the view's bounds may need
472 * to be changed, the view will call {@link #requestLayout()}.</li>
473 * <li>Similarly, if in the course of processing the event the view's appearance
474 * may need to be changed, the view will call {@link #invalidate()}.</li>
475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
476 * the framework will take care of measuring, laying out, and drawing the tree
477 * as appropriate.</li>
478 * </ol>
479 * </p>
480 *
481 * <p><em>Note: The entire view tree is single threaded. You must always be on
482 * the UI thread when calling any method on any view.</em>
483 * If you are doing work on other threads and want to update the state of a view
484 * from that thread, you should use a {@link Handler}.
485 * </p>
486 *
487 * <a name="FocusHandling"></a>
488 * <h3>Focus Handling</h3>
489 * <p>
490 * The framework will handle routine focus movement in response to user input.
491 * This includes changing the focus as views are removed or hidden, or as new
492 * views become available. Views indicate their willingness to take focus
493 * through the {@link #isFocusable} method. To change whether a view can take
494 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
496 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
497 * </p>
498 * <p>
499 * Focus movement is based on an algorithm which finds the nearest neighbor in a
500 * given direction. In rare cases, the default algorithm may not match the
501 * intended behavior of the developer. In these situations, you can provide
502 * explicit overrides by using these XML attributes in the layout file:
503 * <pre>
504 * nextFocusDown
505 * nextFocusLeft
506 * nextFocusRight
507 * nextFocusUp
508 * </pre>
509 * </p>
510 *
511 *
512 * <p>
513 * To get a particular view to take focus, call {@link #requestFocus()}.
514 * </p>
515 *
516 * <a name="TouchMode"></a>
517 * <h3>Touch Mode</h3>
518 * <p>
519 * When a user is navigating a user interface via directional keys such as a D-pad, it is
520 * necessary to give focus to actionable items such as buttons so the user can see
521 * what will take input.  If the device has touch capabilities, however, and the user
522 * begins interacting with the interface by touching it, it is no longer necessary to
523 * always highlight, or give focus to, a particular view.  This motivates a mode
524 * for interaction named 'touch mode'.
525 * </p>
526 * <p>
527 * For a touch capable device, once the user touches the screen, the device
528 * will enter touch mode.  From this point onward, only views for which
529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
530 * Other views that are touchable, like buttons, will not take focus when touched; they will
531 * only fire the on click listeners.
532 * </p>
533 * <p>
534 * Any time a user hits a directional key, such as a D-pad direction, the view device will
535 * exit touch mode, and find a view to take focus, so that the user may resume interacting
536 * with the user interface without touching the screen again.
537 * </p>
538 * <p>
539 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
540 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
541 * </p>
542 *
543 * <a name="Scrolling"></a>
544 * <h3>Scrolling</h3>
545 * <p>
546 * The framework provides basic support for views that wish to internally
547 * scroll their content. This includes keeping track of the X and Y scroll
548 * offset as well as mechanisms for drawing scrollbars. See
549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
550 * {@link #awakenScrollBars()} for more details.
551 * </p>
552 *
553 * <a name="Tags"></a>
554 * <h3>Tags</h3>
555 * <p>
556 * Unlike IDs, tags are not used to identify views. Tags are essentially an
557 * extra piece of information that can be associated with a view. They are most
558 * often used as a convenience to store data related to views in the views
559 * themselves rather than by putting them in a separate structure.
560 * </p>
561 *
562 * <a name="Properties"></a>
563 * <h3>Properties</h3>
564 * <p>
565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
567 * available both in the {@link Property} form as well as in similarly-named setter/getter
568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
569 * be used to set persistent state associated with these rendering-related properties on the view.
570 * The properties and methods can also be used in conjunction with
571 * {@link android.animation.Animator Animator}-based animations, described more in the
572 * <a href="#Animation">Animation</a> section.
573 * </p>
574 *
575 * <a name="Animation"></a>
576 * <h3>Animation</h3>
577 * <p>
578 * Starting with Android 3.0, the preferred way of animating views is to use the
579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
584 * makes animating these View properties particularly easy and efficient.
585 * </p>
586 * <p>
587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
588 * You can attach an {@link Animation} object to a view using
589 * {@link #setAnimation(Animation)} or
590 * {@link #startAnimation(Animation)}. The animation can alter the scale,
591 * rotation, translation and alpha of a view over time. If the animation is
592 * attached to a view that has children, the animation will affect the entire
593 * subtree rooted by that node. When an animation is started, the framework will
594 * take care of redrawing the appropriate views until the animation completes.
595 * </p>
596 *
597 * <a name="Security"></a>
598 * <h3>Security</h3>
599 * <p>
600 * Sometimes it is essential that an application be able to verify that an action
601 * is being performed with the full knowledge and consent of the user, such as
602 * granting a permission request, making a purchase or clicking on an advertisement.
603 * Unfortunately, a malicious application could try to spoof the user into
604 * performing these actions, unaware, by concealing the intended purpose of the view.
605 * As a remedy, the framework offers a touch filtering mechanism that can be used to
606 * improve the security of views that provide access to sensitive functionality.
607 * </p><p>
608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
609 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
610 * will discard touches that are received whenever the view's window is obscured by
611 * another visible window.  As a result, the view will not receive touches whenever a
612 * toast, dialog or other window appears above the view's window.
613 * </p><p>
614 * For more fine-grained control over security, consider overriding the
615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
617 * </p>
618 *
619 * @attr ref android.R.styleable#View_alpha
620 * @attr ref android.R.styleable#View_background
621 * @attr ref android.R.styleable#View_clickable
622 * @attr ref android.R.styleable#View_contentDescription
623 * @attr ref android.R.styleable#View_drawingCacheQuality
624 * @attr ref android.R.styleable#View_duplicateParentState
625 * @attr ref android.R.styleable#View_id
626 * @attr ref android.R.styleable#View_requiresFadingEdge
627 * @attr ref android.R.styleable#View_fadeScrollbars
628 * @attr ref android.R.styleable#View_fadingEdgeLength
629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
630 * @attr ref android.R.styleable#View_fitsSystemWindows
631 * @attr ref android.R.styleable#View_isScrollContainer
632 * @attr ref android.R.styleable#View_focusable
633 * @attr ref android.R.styleable#View_focusableInTouchMode
634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
635 * @attr ref android.R.styleable#View_keepScreenOn
636 * @attr ref android.R.styleable#View_layerType
637 * @attr ref android.R.styleable#View_layoutDirection
638 * @attr ref android.R.styleable#View_longClickable
639 * @attr ref android.R.styleable#View_minHeight
640 * @attr ref android.R.styleable#View_minWidth
641 * @attr ref android.R.styleable#View_nextFocusDown
642 * @attr ref android.R.styleable#View_nextFocusLeft
643 * @attr ref android.R.styleable#View_nextFocusRight
644 * @attr ref android.R.styleable#View_nextFocusUp
645 * @attr ref android.R.styleable#View_onClick
646 * @attr ref android.R.styleable#View_padding
647 * @attr ref android.R.styleable#View_paddingBottom
648 * @attr ref android.R.styleable#View_paddingLeft
649 * @attr ref android.R.styleable#View_paddingRight
650 * @attr ref android.R.styleable#View_paddingTop
651 * @attr ref android.R.styleable#View_paddingStart
652 * @attr ref android.R.styleable#View_paddingEnd
653 * @attr ref android.R.styleable#View_saveEnabled
654 * @attr ref android.R.styleable#View_rotation
655 * @attr ref android.R.styleable#View_rotationX
656 * @attr ref android.R.styleable#View_rotationY
657 * @attr ref android.R.styleable#View_scaleX
658 * @attr ref android.R.styleable#View_scaleY
659 * @attr ref android.R.styleable#View_scrollX
660 * @attr ref android.R.styleable#View_scrollY
661 * @attr ref android.R.styleable#View_scrollbarSize
662 * @attr ref android.R.styleable#View_scrollbarStyle
663 * @attr ref android.R.styleable#View_scrollbars
664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
665 * @attr ref android.R.styleable#View_scrollbarFadeDuration
666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
668 * @attr ref android.R.styleable#View_scrollbarThumbVertical
669 * @attr ref android.R.styleable#View_scrollbarTrackVertical
670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
672 * @attr ref android.R.styleable#View_stateListAnimator
673 * @attr ref android.R.styleable#View_transitionName
674 * @attr ref android.R.styleable#View_soundEffectsEnabled
675 * @attr ref android.R.styleable#View_tag
676 * @attr ref android.R.styleable#View_textAlignment
677 * @attr ref android.R.styleable#View_textDirection
678 * @attr ref android.R.styleable#View_transformPivotX
679 * @attr ref android.R.styleable#View_transformPivotY
680 * @attr ref android.R.styleable#View_translationX
681 * @attr ref android.R.styleable#View_translationY
682 * @attr ref android.R.styleable#View_translationZ
683 * @attr ref android.R.styleable#View_visibility
684 *
685 * @see android.view.ViewGroup
686 */
687public class View implements Drawable.Callback, KeyEvent.Callback,
688        AccessibilityEventSource {
689    private static final boolean DBG = false;
690
691    /**
692     * The logging tag used by this class with android.util.Log.
693     */
694    protected static final String VIEW_LOG_TAG = "View";
695
696    /**
697     * When set to true, apps will draw debugging information about their layouts.
698     *
699     * @hide
700     */
701    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
702
703    /**
704     * Used to mark a View that has no ID.
705     */
706    public static final int NO_ID = -1;
707
708    /**
709     * Signals that compatibility booleans have been initialized according to
710     * target SDK versions.
711     */
712    private static boolean sCompatibilityDone = false;
713
714    /**
715     * Use the old (broken) way of building MeasureSpecs.
716     */
717    private static boolean sUseBrokenMakeMeasureSpec = false;
718
719    /**
720     * Ignore any optimizations using the measure cache.
721     */
722    private static boolean sIgnoreMeasureCache = false;
723
724    /**
725     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
726     * calling setFlags.
727     */
728    private static final int NOT_FOCUSABLE = 0x00000000;
729
730    /**
731     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
732     * setFlags.
733     */
734    private static final int FOCUSABLE = 0x00000001;
735
736    /**
737     * Mask for use with setFlags indicating bits used for focus.
738     */
739    private static final int FOCUSABLE_MASK = 0x00000001;
740
741    /**
742     * This view will adjust its padding to fit sytem windows (e.g. status bar)
743     */
744    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
745
746    /** @hide */
747    @IntDef({VISIBLE, INVISIBLE, GONE})
748    @Retention(RetentionPolicy.SOURCE)
749    public @interface Visibility {}
750
751    /**
752     * This view is visible.
753     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
754     * android:visibility}.
755     */
756    public static final int VISIBLE = 0x00000000;
757
758    /**
759     * This view is invisible, but it still takes up space for layout purposes.
760     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
761     * android:visibility}.
762     */
763    public static final int INVISIBLE = 0x00000004;
764
765    /**
766     * This view is invisible, and it doesn't take any space for layout
767     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
768     * android:visibility}.
769     */
770    public static final int GONE = 0x00000008;
771
772    /**
773     * Mask for use with setFlags indicating bits used for visibility.
774     * {@hide}
775     */
776    static final int VISIBILITY_MASK = 0x0000000C;
777
778    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
779
780    /**
781     * This view is enabled. Interpretation varies by subclass.
782     * Use with ENABLED_MASK when calling setFlags.
783     * {@hide}
784     */
785    static final int ENABLED = 0x00000000;
786
787    /**
788     * This view is disabled. Interpretation varies by subclass.
789     * Use with ENABLED_MASK when calling setFlags.
790     * {@hide}
791     */
792    static final int DISABLED = 0x00000020;
793
794   /**
795    * Mask for use with setFlags indicating bits used for indicating whether
796    * this view is enabled
797    * {@hide}
798    */
799    static final int ENABLED_MASK = 0x00000020;
800
801    /**
802     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
803     * called and further optimizations will be performed. It is okay to have
804     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
805     * {@hide}
806     */
807    static final int WILL_NOT_DRAW = 0x00000080;
808
809    /**
810     * Mask for use with setFlags indicating bits used for indicating whether
811     * this view is will draw
812     * {@hide}
813     */
814    static final int DRAW_MASK = 0x00000080;
815
816    /**
817     * <p>This view doesn't show scrollbars.</p>
818     * {@hide}
819     */
820    static final int SCROLLBARS_NONE = 0x00000000;
821
822    /**
823     * <p>This view shows horizontal scrollbars.</p>
824     * {@hide}
825     */
826    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
827
828    /**
829     * <p>This view shows vertical scrollbars.</p>
830     * {@hide}
831     */
832    static final int SCROLLBARS_VERTICAL = 0x00000200;
833
834    /**
835     * <p>Mask for use with setFlags indicating bits used for indicating which
836     * scrollbars are enabled.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_MASK = 0x00000300;
840
841    /**
842     * Indicates that the view should filter touches when its window is obscured.
843     * Refer to the class comments for more information about this security feature.
844     * {@hide}
845     */
846    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
847
848    /**
849     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
850     * that they are optional and should be skipped if the window has
851     * requested system UI flags that ignore those insets for layout.
852     */
853    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
854
855    /**
856     * <p>This view doesn't show fading edges.</p>
857     * {@hide}
858     */
859    static final int FADING_EDGE_NONE = 0x00000000;
860
861    /**
862     * <p>This view shows horizontal fading edges.</p>
863     * {@hide}
864     */
865    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
866
867    /**
868     * <p>This view shows vertical fading edges.</p>
869     * {@hide}
870     */
871    static final int FADING_EDGE_VERTICAL = 0x00002000;
872
873    /**
874     * <p>Mask for use with setFlags indicating bits used for indicating which
875     * fading edges are enabled.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_MASK = 0x00003000;
879
880    /**
881     * <p>Indicates this view can be clicked. When clickable, a View reacts
882     * to clicks by notifying the OnClickListener.<p>
883     * {@hide}
884     */
885    static final int CLICKABLE = 0x00004000;
886
887    /**
888     * <p>Indicates this view is caching its drawing into a bitmap.</p>
889     * {@hide}
890     */
891    static final int DRAWING_CACHE_ENABLED = 0x00008000;
892
893    /**
894     * <p>Indicates that no icicle should be saved for this view.<p>
895     * {@hide}
896     */
897    static final int SAVE_DISABLED = 0x000010000;
898
899    /**
900     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
901     * property.</p>
902     * {@hide}
903     */
904    static final int SAVE_DISABLED_MASK = 0x000010000;
905
906    /**
907     * <p>Indicates that no drawing cache should ever be created for this view.<p>
908     * {@hide}
909     */
910    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
911
912    /**
913     * <p>Indicates this view can take / keep focus when int touch mode.</p>
914     * {@hide}
915     */
916    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
917
918    /** @hide */
919    @Retention(RetentionPolicy.SOURCE)
920    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
921    public @interface DrawingCacheQuality {}
922
923    /**
924     * <p>Enables low quality mode for the drawing cache.</p>
925     */
926    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
927
928    /**
929     * <p>Enables high quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
932
933    /**
934     * <p>Enables automatic quality mode for the drawing cache.</p>
935     */
936    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
937
938    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
939            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
940    };
941
942    /**
943     * <p>Mask for use with setFlags indicating bits used for the cache
944     * quality property.</p>
945     * {@hide}
946     */
947    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
948
949    /**
950     * <p>
951     * Indicates this view can be long clicked. When long clickable, a View
952     * reacts to long clicks by notifying the OnLongClickListener or showing a
953     * context menu.
954     * </p>
955     * {@hide}
956     */
957    static final int LONG_CLICKABLE = 0x00200000;
958
959    /**
960     * <p>Indicates that this view gets its drawable states from its direct parent
961     * and ignores its original internal states.</p>
962     *
963     * @hide
964     */
965    static final int DUPLICATE_PARENT_STATE = 0x00400000;
966
967    /** @hide */
968    @IntDef({
969        SCROLLBARS_INSIDE_OVERLAY,
970        SCROLLBARS_INSIDE_INSET,
971        SCROLLBARS_OUTSIDE_OVERLAY,
972        SCROLLBARS_OUTSIDE_INSET
973    })
974    @Retention(RetentionPolicy.SOURCE)
975    public @interface ScrollBarStyle {}
976
977    /**
978     * The scrollbar style to display the scrollbars inside the content area,
979     * without increasing the padding. The scrollbars will be overlaid with
980     * translucency on the view's content.
981     */
982    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
983
984    /**
985     * The scrollbar style to display the scrollbars inside the padded area,
986     * increasing the padding of the view. The scrollbars will not overlap the
987     * content area of the view.
988     */
989    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
990
991    /**
992     * The scrollbar style to display the scrollbars at the edge of the view,
993     * without increasing the padding. The scrollbars will be overlaid with
994     * translucency.
995     */
996    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
997
998    /**
999     * The scrollbar style to display the scrollbars at the edge of the view,
1000     * increasing the padding of the view. The scrollbars will only overlap the
1001     * background, if any.
1002     */
1003    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1004
1005    /**
1006     * Mask to check if the scrollbar style is overlay or inset.
1007     * {@hide}
1008     */
1009    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1010
1011    /**
1012     * Mask to check if the scrollbar style is inside or outside.
1013     * {@hide}
1014     */
1015    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1016
1017    /**
1018     * Mask for scrollbar style.
1019     * {@hide}
1020     */
1021    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1022
1023    /**
1024     * View flag indicating that the screen should remain on while the
1025     * window containing this view is visible to the user.  This effectively
1026     * takes care of automatically setting the WindowManager's
1027     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1028     */
1029    public static final int KEEP_SCREEN_ON = 0x04000000;
1030
1031    /**
1032     * View flag indicating whether this view should have sound effects enabled
1033     * for events such as clicking and touching.
1034     */
1035    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1036
1037    /**
1038     * View flag indicating whether this view should have haptic feedback
1039     * enabled for events such as long presses.
1040     */
1041    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1042
1043    /**
1044     * <p>Indicates that the view hierarchy should stop saving state when
1045     * it reaches this view.  If state saving is initiated immediately at
1046     * the view, it will be allowed.
1047     * {@hide}
1048     */
1049    static final int PARENT_SAVE_DISABLED = 0x20000000;
1050
1051    /**
1052     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1053     * {@hide}
1054     */
1055    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1056
1057    /** @hide */
1058    @IntDef(flag = true,
1059            value = {
1060                FOCUSABLES_ALL,
1061                FOCUSABLES_TOUCH_MODE
1062            })
1063    @Retention(RetentionPolicy.SOURCE)
1064    public @interface FocusableMode {}
1065
1066    /**
1067     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1068     * should add all focusable Views regardless if they are focusable in touch mode.
1069     */
1070    public static final int FOCUSABLES_ALL = 0x00000000;
1071
1072    /**
1073     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1074     * should add only Views focusable in touch mode.
1075     */
1076    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1077
1078    /** @hide */
1079    @IntDef({
1080            FOCUS_BACKWARD,
1081            FOCUS_FORWARD,
1082            FOCUS_LEFT,
1083            FOCUS_UP,
1084            FOCUS_RIGHT,
1085            FOCUS_DOWN
1086    })
1087    @Retention(RetentionPolicy.SOURCE)
1088    public @interface FocusDirection {}
1089
1090    /** @hide */
1091    @IntDef({
1092            FOCUS_LEFT,
1093            FOCUS_UP,
1094            FOCUS_RIGHT,
1095            FOCUS_DOWN
1096    })
1097    @Retention(RetentionPolicy.SOURCE)
1098    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1099
1100    /**
1101     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1102     * item.
1103     */
1104    public static final int FOCUS_BACKWARD = 0x00000001;
1105
1106    /**
1107     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1108     * item.
1109     */
1110    public static final int FOCUS_FORWARD = 0x00000002;
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus to the left.
1114     */
1115    public static final int FOCUS_LEFT = 0x00000011;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus up.
1119     */
1120    public static final int FOCUS_UP = 0x00000021;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus to the right.
1124     */
1125    public static final int FOCUS_RIGHT = 0x00000042;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus down.
1129     */
1130    public static final int FOCUS_DOWN = 0x00000082;
1131
1132    /**
1133     * Bits of {@link #getMeasuredWidthAndState()} and
1134     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1135     */
1136    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1137
1138    /**
1139     * Bits of {@link #getMeasuredWidthAndState()} and
1140     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1141     */
1142    public static final int MEASURED_STATE_MASK = 0xff000000;
1143
1144    /**
1145     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1146     * for functions that combine both width and height into a single int,
1147     * such as {@link #getMeasuredState()} and the childState argument of
1148     * {@link #resolveSizeAndState(int, int, int)}.
1149     */
1150    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1151
1152    /**
1153     * Bit of {@link #getMeasuredWidthAndState()} and
1154     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1155     * is smaller that the space the view would like to have.
1156     */
1157    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1158
1159    /**
1160     * Base View state sets
1161     */
1162    // Singles
1163    /**
1164     * Indicates the view has no states set. States are used with
1165     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1166     * view depending on its state.
1167     *
1168     * @see android.graphics.drawable.Drawable
1169     * @see #getDrawableState()
1170     */
1171    protected static final int[] EMPTY_STATE_SET;
1172    /**
1173     * Indicates the view is enabled. States are used with
1174     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1175     * view depending on its state.
1176     *
1177     * @see android.graphics.drawable.Drawable
1178     * @see #getDrawableState()
1179     */
1180    protected static final int[] ENABLED_STATE_SET;
1181    /**
1182     * Indicates the view is focused. States are used with
1183     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1184     * view depending on its state.
1185     *
1186     * @see android.graphics.drawable.Drawable
1187     * @see #getDrawableState()
1188     */
1189    protected static final int[] FOCUSED_STATE_SET;
1190    /**
1191     * Indicates the view is selected. States are used with
1192     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1193     * view depending on its state.
1194     *
1195     * @see android.graphics.drawable.Drawable
1196     * @see #getDrawableState()
1197     */
1198    protected static final int[] SELECTED_STATE_SET;
1199    /**
1200     * Indicates the view is pressed. States are used with
1201     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1202     * view depending on its state.
1203     *
1204     * @see android.graphics.drawable.Drawable
1205     * @see #getDrawableState()
1206     */
1207    protected static final int[] PRESSED_STATE_SET;
1208    /**
1209     * Indicates the view's window has focus. States are used with
1210     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1211     * view depending on its state.
1212     *
1213     * @see android.graphics.drawable.Drawable
1214     * @see #getDrawableState()
1215     */
1216    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1217    // Doubles
1218    /**
1219     * Indicates the view is enabled and has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled and selected.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #SELECTED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_SELECTED_STATE_SET;
1232    /**
1233     * Indicates the view is enabled and that its window has focus.
1234     *
1235     * @see #ENABLED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is focused and selected.
1241     *
1242     * @see #FOCUSED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     */
1245    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1246    /**
1247     * Indicates the view has the focus and that its window has the focus.
1248     *
1249     * @see #FOCUSED_STATE_SET
1250     * @see #WINDOW_FOCUSED_STATE_SET
1251     */
1252    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is selected and that its window has the focus.
1255     *
1256     * @see #SELECTED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1260    // Triples
1261    /**
1262     * Indicates the view is enabled, focused and selected.
1263     *
1264     * @see #ENABLED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is enabled, focused and its window has the focus.
1271     *
1272     * @see #ENABLED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is enabled, selected and its window has the focus.
1279     *
1280     * @see #ENABLED_STATE_SET
1281     * @see #SELECTED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is focused, selected and its window has the focus.
1287     *
1288     * @see #FOCUSED_STATE_SET
1289     * @see #SELECTED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is enabled, focused, selected and its window
1295     * has the focus.
1296     *
1297     * @see #ENABLED_STATE_SET
1298     * @see #FOCUSED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    /**
1304     * Indicates the view is pressed and its window has the focus.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and selected.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #SELECTED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_SELECTED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed, selected and its window has the focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed and focused.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, focused and its window has the focus.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     * @see #WINDOW_FOCUSED_STATE_SET
1338     */
1339    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1340    /**
1341     * Indicates the view is pressed, focused and selected.
1342     *
1343     * @see #PRESSED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1348    /**
1349     * Indicates the view is pressed, focused, selected and its window has the focus.
1350     *
1351     * @see #PRESSED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     * @see #SELECTED_STATE_SET
1354     * @see #WINDOW_FOCUSED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed and enabled.
1359     *
1360     * @see #PRESSED_STATE_SET
1361     * @see #ENABLED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled and its window has the focus.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #WINDOW_FOCUSED_STATE_SET
1370     */
1371    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1372    /**
1373     * Indicates the view is pressed, enabled and selected.
1374     *
1375     * @see #PRESSED_STATE_SET
1376     * @see #ENABLED_STATE_SET
1377     * @see #SELECTED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1380    /**
1381     * Indicates the view is pressed, enabled, selected and its window has the
1382     * focus.
1383     *
1384     * @see #PRESSED_STATE_SET
1385     * @see #ENABLED_STATE_SET
1386     * @see #SELECTED_STATE_SET
1387     * @see #WINDOW_FOCUSED_STATE_SET
1388     */
1389    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1390    /**
1391     * Indicates the view is pressed, enabled and focused.
1392     *
1393     * @see #PRESSED_STATE_SET
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     */
1397    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is pressed, enabled, focused and its window has the
1400     * focus.
1401     *
1402     * @see #PRESSED_STATE_SET
1403     * @see #ENABLED_STATE_SET
1404     * @see #FOCUSED_STATE_SET
1405     * @see #WINDOW_FOCUSED_STATE_SET
1406     */
1407    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1408    /**
1409     * Indicates the view is pressed, enabled, focused and selected.
1410     *
1411     * @see #PRESSED_STATE_SET
1412     * @see #ENABLED_STATE_SET
1413     * @see #SELECTED_STATE_SET
1414     * @see #FOCUSED_STATE_SET
1415     */
1416    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1417    /**
1418     * Indicates the view is pressed, enabled, focused, selected and its window
1419     * has the focus.
1420     *
1421     * @see #PRESSED_STATE_SET
1422     * @see #ENABLED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     * @see #FOCUSED_STATE_SET
1425     * @see #WINDOW_FOCUSED_STATE_SET
1426     */
1427    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1428
1429    /**
1430     * The order here is very important to {@link #getDrawableState()}
1431     */
1432    private static final int[][] VIEW_STATE_SETS;
1433
1434    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1435    static final int VIEW_STATE_SELECTED = 1 << 1;
1436    static final int VIEW_STATE_FOCUSED = 1 << 2;
1437    static final int VIEW_STATE_ENABLED = 1 << 3;
1438    static final int VIEW_STATE_PRESSED = 1 << 4;
1439    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1440    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1441    static final int VIEW_STATE_HOVERED = 1 << 7;
1442    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1443    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1444
1445    static final int[] VIEW_STATE_IDS = new int[] {
1446        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1447        R.attr.state_selected,          VIEW_STATE_SELECTED,
1448        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1449        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1450        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1451        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1452        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1453        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1454        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1455        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1456    };
1457
1458    static {
1459        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1460            throw new IllegalStateException(
1461                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1462        }
1463        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1464        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1465            int viewState = R.styleable.ViewDrawableStates[i];
1466            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1467                if (VIEW_STATE_IDS[j] == viewState) {
1468                    orderedIds[i * 2] = viewState;
1469                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1470                }
1471            }
1472        }
1473        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1474        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1475        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1476            int numBits = Integer.bitCount(i);
1477            int[] set = new int[numBits];
1478            int pos = 0;
1479            for (int j = 0; j < orderedIds.length; j += 2) {
1480                if ((i & orderedIds[j+1]) != 0) {
1481                    set[pos++] = orderedIds[j];
1482                }
1483            }
1484            VIEW_STATE_SETS[i] = set;
1485        }
1486
1487        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1488        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1489        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1490        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1492        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1493        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1495        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1497        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1499                | VIEW_STATE_FOCUSED];
1500        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1501        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1503        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1505        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1507                | VIEW_STATE_ENABLED];
1508        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1510        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1515                | VIEW_STATE_ENABLED];
1516        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1519
1520        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1521        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1523        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1525        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1527                | VIEW_STATE_PRESSED];
1528        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1535                | VIEW_STATE_PRESSED];
1536        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1539        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1549                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1552                | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1555                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1558                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1559        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1560                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1561                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1562                | VIEW_STATE_PRESSED];
1563    }
1564
1565    /**
1566     * Accessibility event types that are dispatched for text population.
1567     */
1568    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1569            AccessibilityEvent.TYPE_VIEW_CLICKED
1570            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1571            | AccessibilityEvent.TYPE_VIEW_SELECTED
1572            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1573            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1574            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1575            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1576            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1577            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1578            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1579            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1580
1581    /**
1582     * Temporary Rect currently for use in setBackground().  This will probably
1583     * be extended in the future to hold our own class with more than just
1584     * a Rect. :)
1585     */
1586    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1587
1588    /**
1589     * Map used to store views' tags.
1590     */
1591    private SparseArray<Object> mKeyedTags;
1592
1593    /**
1594     * The next available accessibility id.
1595     */
1596    private static int sNextAccessibilityViewId;
1597
1598    /**
1599     * The animation currently associated with this view.
1600     * @hide
1601     */
1602    protected Animation mCurrentAnimation = null;
1603
1604    /**
1605     * Width as measured during measure pass.
1606     * {@hide}
1607     */
1608    @ViewDebug.ExportedProperty(category = "measurement")
1609    int mMeasuredWidth;
1610
1611    /**
1612     * Height as measured during measure pass.
1613     * {@hide}
1614     */
1615    @ViewDebug.ExportedProperty(category = "measurement")
1616    int mMeasuredHeight;
1617
1618    /**
1619     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1620     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1621     * its display list. This flag, used only when hw accelerated, allows us to clear the
1622     * flag while retaining this information until it's needed (at getDisplayList() time and
1623     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1624     *
1625     * {@hide}
1626     */
1627    boolean mRecreateDisplayList = false;
1628
1629    /**
1630     * The view's identifier.
1631     * {@hide}
1632     *
1633     * @see #setId(int)
1634     * @see #getId()
1635     */
1636    @ViewDebug.ExportedProperty(resolveId = true)
1637    int mID = NO_ID;
1638
1639    /**
1640     * The stable ID of this view for accessibility purposes.
1641     */
1642    int mAccessibilityViewId = NO_ID;
1643
1644    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1645
1646    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1647
1648    /**
1649     * The view's tag.
1650     * {@hide}
1651     *
1652     * @see #setTag(Object)
1653     * @see #getTag()
1654     */
1655    protected Object mTag = null;
1656
1657    // for mPrivateFlags:
1658    /** {@hide} */
1659    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1660    /** {@hide} */
1661    static final int PFLAG_FOCUSED                     = 0x00000002;
1662    /** {@hide} */
1663    static final int PFLAG_SELECTED                    = 0x00000004;
1664    /** {@hide} */
1665    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1666    /** {@hide} */
1667    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1668    /** {@hide} */
1669    static final int PFLAG_DRAWN                       = 0x00000020;
1670    /**
1671     * When this flag is set, this view is running an animation on behalf of its
1672     * children and should therefore not cancel invalidate requests, even if they
1673     * lie outside of this view's bounds.
1674     *
1675     * {@hide}
1676     */
1677    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1678    /** {@hide} */
1679    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1680    /** {@hide} */
1681    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1682    /** {@hide} */
1683    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1684    /** {@hide} */
1685    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1686    /** {@hide} */
1687    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1688    /** {@hide} */
1689    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1690    /** {@hide} */
1691    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1692
1693    private static final int PFLAG_PRESSED             = 0x00004000;
1694
1695    /** {@hide} */
1696    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1697    /**
1698     * Flag used to indicate that this view should be drawn once more (and only once
1699     * more) after its animation has completed.
1700     * {@hide}
1701     */
1702    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1703
1704    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1705
1706    /**
1707     * Indicates that the View returned true when onSetAlpha() was called and that
1708     * the alpha must be restored.
1709     * {@hide}
1710     */
1711    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1712
1713    /**
1714     * Set by {@link #setScrollContainer(boolean)}.
1715     */
1716    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1717
1718    /**
1719     * Set by {@link #setScrollContainer(boolean)}.
1720     */
1721    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1722
1723    /**
1724     * View flag indicating whether this view was invalidated (fully or partially.)
1725     *
1726     * @hide
1727     */
1728    static final int PFLAG_DIRTY                       = 0x00200000;
1729
1730    /**
1731     * View flag indicating whether this view was invalidated by an opaque
1732     * invalidate request.
1733     *
1734     * @hide
1735     */
1736    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1737
1738    /**
1739     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1740     *
1741     * @hide
1742     */
1743    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1744
1745    /**
1746     * Indicates whether the background is opaque.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1751
1752    /**
1753     * Indicates whether the scrollbars are opaque.
1754     *
1755     * @hide
1756     */
1757    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1758
1759    /**
1760     * Indicates whether the view is opaque.
1761     *
1762     * @hide
1763     */
1764    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1765
1766    /**
1767     * Indicates a prepressed state;
1768     * the short time between ACTION_DOWN and recognizing
1769     * a 'real' press. Prepressed is used to recognize quick taps
1770     * even when they are shorter than ViewConfiguration.getTapTimeout().
1771     *
1772     * @hide
1773     */
1774    private static final int PFLAG_PREPRESSED          = 0x02000000;
1775
1776    /**
1777     * Indicates whether the view is temporarily detached.
1778     *
1779     * @hide
1780     */
1781    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1782
1783    /**
1784     * Indicates that we should awaken scroll bars once attached
1785     *
1786     * @hide
1787     */
1788    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1789
1790    /**
1791     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1792     * @hide
1793     */
1794    private static final int PFLAG_HOVERED             = 0x10000000;
1795
1796    /**
1797     * no longer needed, should be reused
1798     */
1799    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1800
1801    /** {@hide} */
1802    static final int PFLAG_ACTIVATED                   = 0x40000000;
1803
1804    /**
1805     * Indicates that this view was specifically invalidated, not just dirtied because some
1806     * child view was invalidated. The flag is used to determine when we need to recreate
1807     * a view's display list (as opposed to just returning a reference to its existing
1808     * display list).
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_INVALIDATED                 = 0x80000000;
1813
1814    /**
1815     * Masks for mPrivateFlags2, as generated by dumpFlags():
1816     *
1817     * |-------|-------|-------|-------|
1818     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1819     *                                1  PFLAG2_DRAG_HOVERED
1820     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1821     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1822     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1823     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1824     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1825     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1826     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1827     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1828     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1829     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1830     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1831     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1832     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1833     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1834     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1835     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1836     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1837     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1838     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1839     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1840     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1841     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1842     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1843     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1844     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1845     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1846     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1847     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1848     *    1                              PFLAG2_PADDING_RESOLVED
1849     *   1                               PFLAG2_DRAWABLE_RESOLVED
1850     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1851     * |-------|-------|-------|-------|
1852     */
1853
1854    /**
1855     * Indicates that this view has reported that it can accept the current drag's content.
1856     * Cleared when the drag operation concludes.
1857     * @hide
1858     */
1859    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1860
1861    /**
1862     * Indicates that this view is currently directly under the drag location in a
1863     * drag-and-drop operation involving content that it can accept.  Cleared when
1864     * the drag exits the view, or when the drag operation concludes.
1865     * @hide
1866     */
1867    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1868
1869    /** @hide */
1870    @IntDef({
1871        LAYOUT_DIRECTION_LTR,
1872        LAYOUT_DIRECTION_RTL,
1873        LAYOUT_DIRECTION_INHERIT,
1874        LAYOUT_DIRECTION_LOCALE
1875    })
1876    @Retention(RetentionPolicy.SOURCE)
1877    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1878    public @interface LayoutDir {}
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL
1884    })
1885    @Retention(RetentionPolicy.SOURCE)
1886    public @interface ResolvedLayoutDir {}
1887
1888    /**
1889     * Horizontal layout direction of this view is from Left to Right.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1893
1894    /**
1895     * Horizontal layout direction of this view is from Right to Left.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1899
1900    /**
1901     * Horizontal layout direction of this view is inherited from its parent.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1905
1906    /**
1907     * Horizontal layout direction of this view is from deduced from the default language
1908     * script for the locale. Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1911
1912    /**
1913     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1917
1918    /**
1919     * Mask for use with private flags indicating bits used for horizontal layout direction.
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1923
1924    /**
1925     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1926     * right-to-left direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1942            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /*
1945     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1946     * flag value.
1947     * @hide
1948     */
1949    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1950            LAYOUT_DIRECTION_LTR,
1951            LAYOUT_DIRECTION_RTL,
1952            LAYOUT_DIRECTION_INHERIT,
1953            LAYOUT_DIRECTION_LOCALE
1954    };
1955
1956    /**
1957     * Default horizontal layout direction.
1958     */
1959    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1960
1961    /**
1962     * Default horizontal layout direction.
1963     * @hide
1964     */
1965    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1966
1967    /**
1968     * Text direction is inherited thru {@link ViewGroup}
1969     */
1970    public static final int TEXT_DIRECTION_INHERIT = 0;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is the view's resolved layout direction.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1978
1979    /**
1980     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1981     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1982     * If there are neither, the paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1985
1986    /**
1987     * Text direction is forced to LTR.
1988     */
1989    public static final int TEXT_DIRECTION_LTR = 3;
1990
1991    /**
1992     * Text direction is forced to RTL.
1993     */
1994    public static final int TEXT_DIRECTION_RTL = 4;
1995
1996    /**
1997     * Text direction is coming from the system Locale.
1998     */
1999    public static final int TEXT_DIRECTION_LOCALE = 5;
2000
2001    /**
2002     * Default text direction is inherited
2003     */
2004    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2005
2006    /**
2007     * Default resolved text direction
2008     * @hide
2009     */
2010    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2011
2012    /**
2013     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2017
2018    /**
2019     * Mask for use with private flags indicating bits used for text direction.
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2023            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2024
2025    /**
2026     * Array of text direction flags for mapping attribute "textDirection" to correct
2027     * flag value.
2028     * @hide
2029     */
2030    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2031            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2036            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2037    };
2038
2039    /**
2040     * Indicates whether the view text direction has been resolved.
2041     * @hide
2042     */
2043    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2044            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for resolved text direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2057            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2058
2059    /**
2060     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2064            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /** @hide */
2067    @IntDef({
2068        TEXT_ALIGNMENT_INHERIT,
2069        TEXT_ALIGNMENT_GRAVITY,
2070        TEXT_ALIGNMENT_CENTER,
2071        TEXT_ALIGNMENT_TEXT_START,
2072        TEXT_ALIGNMENT_TEXT_END,
2073        TEXT_ALIGNMENT_VIEW_START,
2074        TEXT_ALIGNMENT_VIEW_END
2075    })
2076    @Retention(RetentionPolicy.SOURCE)
2077    public @interface TextAlignment {}
2078
2079    /**
2080     * Default text alignment. The text alignment of this View is inherited from its parent.
2081     * Use with {@link #setTextAlignment(int)}
2082     */
2083    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2084
2085    /**
2086     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2087     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2088     *
2089     * Use with {@link #setTextAlignment(int)}
2090     */
2091    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2092
2093    /**
2094     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2099
2100    /**
2101     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2106
2107    /**
2108     * Center the paragraph, e.g. ALIGN_CENTER.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_CENTER = 4;
2113
2114    /**
2115     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2116     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2117     *
2118     * Use with {@link #setTextAlignment(int)}
2119     */
2120    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2121
2122    /**
2123     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2124     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2125     *
2126     * Use with {@link #setTextAlignment(int)}
2127     */
2128    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2129
2130    /**
2131     * Default text alignment is inherited
2132     */
2133    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2134
2135    /**
2136     * Default resolved text alignment
2137     * @hide
2138     */
2139    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2140
2141    /**
2142      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2143      * @hide
2144      */
2145    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2146
2147    /**
2148      * Mask for use with private flags indicating bits used for text alignment.
2149      * @hide
2150      */
2151    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2152
2153    /**
2154     * Array of text direction flags for mapping attribute "textAlignment" to correct
2155     * flag value.
2156     * @hide
2157     */
2158    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2159            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2166    };
2167
2168    /**
2169     * Indicates whether the view text alignment has been resolved.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2173
2174    /**
2175     * Bit shift to get the resolved text alignment.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2179
2180    /**
2181     * Mask for use with private flags indicating bits used for text alignment.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2185            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2186
2187    /**
2188     * Indicates whether if the view text alignment has been resolved to gravity
2189     */
2190    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2191            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2192
2193    // Accessiblity constants for mPrivateFlags2
2194
2195    /**
2196     * Shift for the bits in {@link #mPrivateFlags2} related to the
2197     * "importantForAccessibility" attribute.
2198     */
2199    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2200
2201    /**
2202     * Automatically determine whether a view is important for accessibility.
2203     */
2204    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2205
2206    /**
2207     * The view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2210
2211    /**
2212     * The view is not important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2215
2216    /**
2217     * The view is not important for accessibility, nor are any of its
2218     * descendant views.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2221
2222    /**
2223     * The default whether the view is important for accessibility.
2224     */
2225    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2226
2227    /**
2228     * Mask for obtainig the bits which specify how to determine
2229     * whether a view is important for accessibility.
2230     */
2231    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2232        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2233        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2234        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2235
2236    /**
2237     * Shift for the bits in {@link #mPrivateFlags2} related to the
2238     * "accessibilityLiveRegion" attribute.
2239     */
2240    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2241
2242    /**
2243     * Live region mode specifying that accessibility services should not
2244     * automatically announce changes to this view. This is the default live
2245     * region mode for most views.
2246     * <p>
2247     * Use with {@link #setAccessibilityLiveRegion(int)}.
2248     */
2249    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2250
2251    /**
2252     * Live region mode specifying that accessibility services should announce
2253     * changes to this view.
2254     * <p>
2255     * Use with {@link #setAccessibilityLiveRegion(int)}.
2256     */
2257    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2258
2259    /**
2260     * Live region mode specifying that accessibility services should interrupt
2261     * ongoing speech to immediately announce changes to this view.
2262     * <p>
2263     * Use with {@link #setAccessibilityLiveRegion(int)}.
2264     */
2265    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2266
2267    /**
2268     * The default whether the view is important for accessibility.
2269     */
2270    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2271
2272    /**
2273     * Mask for obtaining the bits which specify a view's accessibility live
2274     * region mode.
2275     */
2276    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2277            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2278            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2279
2280    /**
2281     * Flag indicating whether a view has accessibility focus.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2284
2285    /**
2286     * Flag whether the accessibility state of the subtree rooted at this view changed.
2287     */
2288    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2289
2290    /**
2291     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2292     * is used to check whether later changes to the view's transform should invalidate the
2293     * view to force the quickReject test to run again.
2294     */
2295    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2296
2297    /**
2298     * Flag indicating that start/end padding has been resolved into left/right padding
2299     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2300     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2301     * during measurement. In some special cases this is required such as when an adapter-based
2302     * view measures prospective children without attaching them to a window.
2303     */
2304    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2305
2306    /**
2307     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2308     */
2309    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2310
2311    /**
2312     * Indicates that the view is tracking some sort of transient state
2313     * that the app should not need to be aware of, but that the framework
2314     * should take special care to preserve.
2315     */
2316    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2317
2318    /**
2319     * Group of bits indicating that RTL properties resolution is done.
2320     */
2321    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2322            PFLAG2_TEXT_DIRECTION_RESOLVED |
2323            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2324            PFLAG2_PADDING_RESOLVED |
2325            PFLAG2_DRAWABLE_RESOLVED;
2326
2327    // There are a couple of flags left in mPrivateFlags2
2328
2329    /* End of masks for mPrivateFlags2 */
2330
2331    /**
2332     * Masks for mPrivateFlags3, as generated by dumpFlags():
2333     *
2334     * |-------|-------|-------|-------|
2335     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2336     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2337     *                               1   PFLAG3_IS_LAID_OUT
2338     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2339     *                             1     PFLAG3_CALLED_SUPER
2340     * |-------|-------|-------|-------|
2341     */
2342
2343    /**
2344     * Flag indicating that view has a transform animation set on it. This is used to track whether
2345     * an animation is cleared between successive frames, in order to tell the associated
2346     * DisplayList to clear its animation matrix.
2347     */
2348    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2349
2350    /**
2351     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2352     * animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to restore its alpha value.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2356
2357    /**
2358     * Flag indicating that the view has been through at least one layout since it
2359     * was last attached to a window.
2360     */
2361    static final int PFLAG3_IS_LAID_OUT = 0x4;
2362
2363    /**
2364     * Flag indicating that a call to measure() was skipped and should be done
2365     * instead when layout() is invoked.
2366     */
2367    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2368
2369    /**
2370     * Flag indicating that an overridden method correctly called down to
2371     * the superclass implementation as required by the API spec.
2372     */
2373    static final int PFLAG3_CALLED_SUPER = 0x10;
2374
2375    /**
2376     * Flag indicating that we're in the process of applying window insets.
2377     */
2378    static final int PFLAG3_APPLYING_INSETS = 0x20;
2379
2380    /**
2381     * Flag indicating that we're in the process of fitting system windows using the old method.
2382     */
2383    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2384
2385    /**
2386     * Flag indicating that nested scrolling is enabled for this view.
2387     * The view will optionally cooperate with views up its parent chain to allow for
2388     * integrated nested scrolling along the same axis.
2389     */
2390    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2391
2392    /* End of masks for mPrivateFlags3 */
2393
2394    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2395
2396    /**
2397     * Always allow a user to over-scroll this view, provided it is a
2398     * view that can scroll.
2399     *
2400     * @see #getOverScrollMode()
2401     * @see #setOverScrollMode(int)
2402     */
2403    public static final int OVER_SCROLL_ALWAYS = 0;
2404
2405    /**
2406     * Allow a user to over-scroll this view only if the content is large
2407     * enough to meaningfully scroll, provided it is a view that can scroll.
2408     *
2409     * @see #getOverScrollMode()
2410     * @see #setOverScrollMode(int)
2411     */
2412    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2413
2414    /**
2415     * Never allow a user to over-scroll this view.
2416     *
2417     * @see #getOverScrollMode()
2418     * @see #setOverScrollMode(int)
2419     */
2420    public static final int OVER_SCROLL_NEVER = 2;
2421
2422    /**
2423     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2424     * requested the system UI (status bar) to be visible (the default).
2425     *
2426     * @see #setSystemUiVisibility(int)
2427     */
2428    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2429
2430    /**
2431     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2432     * system UI to enter an unobtrusive "low profile" mode.
2433     *
2434     * <p>This is for use in games, book readers, video players, or any other
2435     * "immersive" application where the usual system chrome is deemed too distracting.
2436     *
2437     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2438     *
2439     * @see #setSystemUiVisibility(int)
2440     */
2441    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2442
2443    /**
2444     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2445     * system navigation be temporarily hidden.
2446     *
2447     * <p>This is an even less obtrusive state than that called for by
2448     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2449     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2450     * those to disappear. This is useful (in conjunction with the
2451     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2452     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2453     * window flags) for displaying content using every last pixel on the display.
2454     *
2455     * <p>There is a limitation: because navigation controls are so important, the least user
2456     * interaction will cause them to reappear immediately.  When this happens, both
2457     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2458     * so that both elements reappear at the same time.
2459     *
2460     * @see #setSystemUiVisibility(int)
2461     */
2462    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2463
2464    /**
2465     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2466     * into the normal fullscreen mode so that its content can take over the screen
2467     * while still allowing the user to interact with the application.
2468     *
2469     * <p>This has the same visual effect as
2470     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2471     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2472     * meaning that non-critical screen decorations (such as the status bar) will be
2473     * hidden while the user is in the View's window, focusing the experience on
2474     * that content.  Unlike the window flag, if you are using ActionBar in
2475     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2476     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2477     * hide the action bar.
2478     *
2479     * <p>This approach to going fullscreen is best used over the window flag when
2480     * it is a transient state -- that is, the application does this at certain
2481     * points in its user interaction where it wants to allow the user to focus
2482     * on content, but not as a continuous state.  For situations where the application
2483     * would like to simply stay full screen the entire time (such as a game that
2484     * wants to take over the screen), the
2485     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2486     * is usually a better approach.  The state set here will be removed by the system
2487     * in various situations (such as the user moving to another application) like
2488     * the other system UI states.
2489     *
2490     * <p>When using this flag, the application should provide some easy facility
2491     * for the user to go out of it.  A common example would be in an e-book
2492     * reader, where tapping on the screen brings back whatever screen and UI
2493     * decorations that had been hidden while the user was immersed in reading
2494     * the book.
2495     *
2496     * @see #setSystemUiVisibility(int)
2497     */
2498    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2499
2500    /**
2501     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2502     * flags, we would like a stable view of the content insets given to
2503     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2504     * will always represent the worst case that the application can expect
2505     * as a continuous state.  In the stock Android UI this is the space for
2506     * the system bar, nav bar, and status bar, but not more transient elements
2507     * such as an input method.
2508     *
2509     * The stable layout your UI sees is based on the system UI modes you can
2510     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2511     * then you will get a stable layout for changes of the
2512     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2513     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2514     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2515     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2516     * with a stable layout.  (Note that you should avoid using
2517     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2518     *
2519     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2520     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2521     * then a hidden status bar will be considered a "stable" state for purposes
2522     * here.  This allows your UI to continually hide the status bar, while still
2523     * using the system UI flags to hide the action bar while still retaining
2524     * a stable layout.  Note that changing the window fullscreen flag will never
2525     * provide a stable layout for a clean transition.
2526     *
2527     * <p>If you are using ActionBar in
2528     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2529     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2530     * insets it adds to those given to the application.
2531     */
2532    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2533
2534    /**
2535     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2536     * to be layed out as if it has requested
2537     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2538     * allows it to avoid artifacts when switching in and out of that mode, at
2539     * the expense that some of its user interface may be covered by screen
2540     * decorations when they are shown.  You can perform layout of your inner
2541     * UI elements to account for the navigation system UI through the
2542     * {@link #fitSystemWindows(Rect)} method.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2545
2546    /**
2547     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2548     * to be layed out as if it has requested
2549     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2550     * allows it to avoid artifacts when switching in and out of that mode, at
2551     * the expense that some of its user interface may be covered by screen
2552     * decorations when they are shown.  You can perform layout of your inner
2553     * UI elements to account for non-fullscreen system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2560     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2561     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2562     * user interaction.
2563     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2564     * has an effect when used in combination with that flag.</p>
2565     */
2566    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2571     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2572     * experience while also hiding the system bars.  If this flag is not set,
2573     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2574     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2575     * if the user swipes from the top of the screen.
2576     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2577     * system gestures, such as swiping from the top of the screen.  These transient system bars
2578     * will overlay app’s content, may have some degree of transparency, and will automatically
2579     * hide after a short timeout.
2580     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2581     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2582     * with one or both of those flags.</p>
2583     */
2584    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2585
2586    /**
2587     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2588     */
2589    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2590
2591    /**
2592     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2593     */
2594    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2595
2596    /**
2597     * @hide
2598     *
2599     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2600     * out of the public fields to keep the undefined bits out of the developer's way.
2601     *
2602     * Flag to make the status bar not expandable.  Unless you also
2603     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2604     */
2605    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2606
2607    /**
2608     * @hide
2609     *
2610     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2611     * out of the public fields to keep the undefined bits out of the developer's way.
2612     *
2613     * Flag to hide notification icons and scrolling ticker text.
2614     */
2615    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
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 disable incoming notification alerts.  This will not block
2624     * icons, but it will block sound, vibrating and other visual or aural notifications.
2625     */
2626    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2627
2628    /**
2629     * @hide
2630     *
2631     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2632     * out of the public fields to keep the undefined bits out of the developer's way.
2633     *
2634     * Flag to hide only the scrolling ticker.  Note that
2635     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2636     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2639
2640    /**
2641     * @hide
2642     *
2643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2644     * out of the public fields to keep the undefined bits out of the developer's way.
2645     *
2646     * Flag to hide the center system info area.
2647     */
2648    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
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 only the home button.  Don't use this
2657     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2658     */
2659    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2660
2661    /**
2662     * @hide
2663     *
2664     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2665     * out of the public fields to keep the undefined bits out of the developer's way.
2666     *
2667     * Flag to hide only the back button. Don't use this
2668     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2669     */
2670    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2671
2672    /**
2673     * @hide
2674     *
2675     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2676     * out of the public fields to keep the undefined bits out of the developer's way.
2677     *
2678     * Flag to hide only the clock.  You might use this if your activity has
2679     * its own clock making the status bar's clock redundant.
2680     */
2681    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to hide only the recent apps button. Don't use this
2690     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2691     */
2692    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2693
2694    /**
2695     * @hide
2696     *
2697     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2698     * out of the public fields to keep the undefined bits out of the developer's way.
2699     *
2700     * Flag to disable the global search gesture. Don't use this
2701     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2702     */
2703    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2704
2705    /**
2706     * @hide
2707     *
2708     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2709     * out of the public fields to keep the undefined bits out of the developer's way.
2710     *
2711     * Flag to specify that the status bar is displayed in transient mode.
2712     */
2713    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
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 navigation bar is displayed in transient mode.
2722     */
2723    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
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 hidden status bar would like to be shown.
2732     */
2733    public static final int STATUS_BAR_UNHIDE = 0x10000000;
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 navigation bar would like to be shown.
2742     */
2743    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
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 status bar is displayed in translucent mode.
2752     */
2753    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
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 navigation bar is displayed in translucent mode.
2762     */
2763    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * Whether Recents is visible or not.
2769     */
2770    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2771
2772    /**
2773     * @hide
2774     *
2775     * Makes system ui transparent.
2776     */
2777    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2778
2779    /**
2780     * @hide
2781     */
2782    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2783
2784    /**
2785     * These are the system UI flags that can be cleared by events outside
2786     * of an application.  Currently this is just the ability to tap on the
2787     * screen while hiding the navigation bar to have it return.
2788     * @hide
2789     */
2790    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2791            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2792            | SYSTEM_UI_FLAG_FULLSCREEN;
2793
2794    /**
2795     * Flags that can impact the layout in relation to system UI.
2796     */
2797    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2798            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2799            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2800
2801    /** @hide */
2802    @IntDef(flag = true,
2803            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2804    @Retention(RetentionPolicy.SOURCE)
2805    public @interface FindViewFlags {}
2806
2807    /**
2808     * Find views that render the specified text.
2809     *
2810     * @see #findViewsWithText(ArrayList, CharSequence, int)
2811     */
2812    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2813
2814    /**
2815     * Find find views that contain the specified content description.
2816     *
2817     * @see #findViewsWithText(ArrayList, CharSequence, int)
2818     */
2819    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2820
2821    /**
2822     * Find views that contain {@link AccessibilityNodeProvider}. Such
2823     * a View is a root of virtual view hierarchy and may contain the searched
2824     * text. If this flag is set Views with providers are automatically
2825     * added and it is a responsibility of the client to call the APIs of
2826     * the provider to determine whether the virtual tree rooted at this View
2827     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2828     * representing the virtual views with this text.
2829     *
2830     * @see #findViewsWithText(ArrayList, CharSequence, int)
2831     *
2832     * @hide
2833     */
2834    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2835
2836    /**
2837     * The undefined cursor position.
2838     *
2839     * @hide
2840     */
2841    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2842
2843    /**
2844     * Indicates that the screen has changed state and is now off.
2845     *
2846     * @see #onScreenStateChanged(int)
2847     */
2848    public static final int SCREEN_STATE_OFF = 0x0;
2849
2850    /**
2851     * Indicates that the screen has changed state and is now on.
2852     *
2853     * @see #onScreenStateChanged(int)
2854     */
2855    public static final int SCREEN_STATE_ON = 0x1;
2856
2857    /**
2858     * Indicates no axis of view scrolling.
2859     */
2860    public static final int SCROLL_AXIS_NONE = 0;
2861
2862    /**
2863     * Indicates scrolling along the horizontal axis.
2864     */
2865    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2866
2867    /**
2868     * Indicates scrolling along the vertical axis.
2869     */
2870    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2871
2872    /**
2873     * Controls the over-scroll mode for this view.
2874     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2875     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2876     * and {@link #OVER_SCROLL_NEVER}.
2877     */
2878    private int mOverScrollMode;
2879
2880    /**
2881     * The parent this view is attached to.
2882     * {@hide}
2883     *
2884     * @see #getParent()
2885     */
2886    protected ViewParent mParent;
2887
2888    /**
2889     * {@hide}
2890     */
2891    AttachInfo mAttachInfo;
2892
2893    /**
2894     * {@hide}
2895     */
2896    @ViewDebug.ExportedProperty(flagMapping = {
2897        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2898                name = "FORCE_LAYOUT"),
2899        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2900                name = "LAYOUT_REQUIRED"),
2901        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2902            name = "DRAWING_CACHE_INVALID", outputIf = false),
2903        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2904        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2905        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2906        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2907    }, formatToHexString = true)
2908    int mPrivateFlags;
2909    int mPrivateFlags2;
2910    int mPrivateFlags3;
2911
2912    /**
2913     * This view's request for the visibility of the status bar.
2914     * @hide
2915     */
2916    @ViewDebug.ExportedProperty(flagMapping = {
2917        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2918                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2919                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2920        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2921                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2922                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2923        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2924                                equals = SYSTEM_UI_FLAG_VISIBLE,
2925                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2926    }, formatToHexString = true)
2927    int mSystemUiVisibility;
2928
2929    /**
2930     * Reference count for transient state.
2931     * @see #setHasTransientState(boolean)
2932     */
2933    int mTransientStateCount = 0;
2934
2935    /**
2936     * Count of how many windows this view has been attached to.
2937     */
2938    int mWindowAttachCount;
2939
2940    /**
2941     * The layout parameters associated with this view and used by the parent
2942     * {@link android.view.ViewGroup} to determine how this view should be
2943     * laid out.
2944     * {@hide}
2945     */
2946    protected ViewGroup.LayoutParams mLayoutParams;
2947
2948    /**
2949     * The view flags hold various views states.
2950     * {@hide}
2951     */
2952    @ViewDebug.ExportedProperty(formatToHexString = true)
2953    int mViewFlags;
2954
2955    static class TransformationInfo {
2956        /**
2957         * The transform matrix for the View. This transform is calculated internally
2958         * based on the translation, rotation, and scale properties.
2959         *
2960         * Do *not* use this variable directly; instead call getMatrix(), which will
2961         * load the value from the View's RenderNode.
2962         */
2963        private final Matrix mMatrix = new Matrix();
2964
2965        /**
2966         * The inverse transform matrix for the View. This transform is calculated
2967         * internally based on the translation, rotation, and scale properties.
2968         *
2969         * Do *not* use this variable directly; instead call getInverseMatrix(),
2970         * which will load the value from the View's RenderNode.
2971         */
2972        private Matrix mInverseMatrix;
2973
2974        /**
2975         * The opacity of the View. This is a value from 0 to 1, where 0 means
2976         * completely transparent and 1 means completely opaque.
2977         */
2978        @ViewDebug.ExportedProperty
2979        float mAlpha = 1f;
2980
2981        /**
2982         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2983         * property only used by transitions, which is composited with the other alpha
2984         * values to calculate the final visual alpha value.
2985         */
2986        float mTransitionAlpha = 1f;
2987    }
2988
2989    TransformationInfo mTransformationInfo;
2990
2991    /**
2992     * Current clip bounds. to which all drawing of this view are constrained.
2993     */
2994    Rect mClipBounds = null;
2995
2996    private boolean mLastIsOpaque;
2997
2998    /**
2999     * The distance in pixels from the left edge of this view's parent
3000     * to the left edge of this view.
3001     * {@hide}
3002     */
3003    @ViewDebug.ExportedProperty(category = "layout")
3004    protected int mLeft;
3005    /**
3006     * The distance in pixels from the left edge of this view's parent
3007     * to the right edge of this view.
3008     * {@hide}
3009     */
3010    @ViewDebug.ExportedProperty(category = "layout")
3011    protected int mRight;
3012    /**
3013     * The distance in pixels from the top edge of this view's parent
3014     * to the top edge of this view.
3015     * {@hide}
3016     */
3017    @ViewDebug.ExportedProperty(category = "layout")
3018    protected int mTop;
3019    /**
3020     * The distance in pixels from the top edge of this view's parent
3021     * to the bottom edge of this view.
3022     * {@hide}
3023     */
3024    @ViewDebug.ExportedProperty(category = "layout")
3025    protected int mBottom;
3026
3027    /**
3028     * The offset, in pixels, by which the content of this view is scrolled
3029     * horizontally.
3030     * {@hide}
3031     */
3032    @ViewDebug.ExportedProperty(category = "scrolling")
3033    protected int mScrollX;
3034    /**
3035     * The offset, in pixels, by which the content of this view is scrolled
3036     * vertically.
3037     * {@hide}
3038     */
3039    @ViewDebug.ExportedProperty(category = "scrolling")
3040    protected int mScrollY;
3041
3042    /**
3043     * The left padding in pixels, that is the distance in pixels between the
3044     * left edge of this view and the left edge of its content.
3045     * {@hide}
3046     */
3047    @ViewDebug.ExportedProperty(category = "padding")
3048    protected int mPaddingLeft = 0;
3049    /**
3050     * The right padding in pixels, that is the distance in pixels between the
3051     * right edge of this view and the right edge of its content.
3052     * {@hide}
3053     */
3054    @ViewDebug.ExportedProperty(category = "padding")
3055    protected int mPaddingRight = 0;
3056    /**
3057     * The top padding in pixels, that is the distance in pixels between the
3058     * top edge of this view and the top edge of its content.
3059     * {@hide}
3060     */
3061    @ViewDebug.ExportedProperty(category = "padding")
3062    protected int mPaddingTop;
3063    /**
3064     * The bottom padding in pixels, that is the distance in pixels between the
3065     * bottom edge of this view and the bottom edge of its content.
3066     * {@hide}
3067     */
3068    @ViewDebug.ExportedProperty(category = "padding")
3069    protected int mPaddingBottom;
3070
3071    /**
3072     * The layout insets in pixels, that is the distance in pixels between the
3073     * visible edges of this view its bounds.
3074     */
3075    private Insets mLayoutInsets;
3076
3077    /**
3078     * Briefly describes the view and is primarily used for accessibility support.
3079     */
3080    private CharSequence mContentDescription;
3081
3082    /**
3083     * Specifies the id of a view for which this view serves as a label for
3084     * accessibility purposes.
3085     */
3086    private int mLabelForId = View.NO_ID;
3087
3088    /**
3089     * Predicate for matching labeled view id with its label for
3090     * accessibility purposes.
3091     */
3092    private MatchLabelForPredicate mMatchLabelForPredicate;
3093
3094    /**
3095     * Predicate for matching a view by its id.
3096     */
3097    private MatchIdPredicate mMatchIdPredicate;
3098
3099    /**
3100     * Cache the paddingRight set by the user to append to the scrollbar's size.
3101     *
3102     * @hide
3103     */
3104    @ViewDebug.ExportedProperty(category = "padding")
3105    protected int mUserPaddingRight;
3106
3107    /**
3108     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3109     *
3110     * @hide
3111     */
3112    @ViewDebug.ExportedProperty(category = "padding")
3113    protected int mUserPaddingBottom;
3114
3115    /**
3116     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3117     *
3118     * @hide
3119     */
3120    @ViewDebug.ExportedProperty(category = "padding")
3121    protected int mUserPaddingLeft;
3122
3123    /**
3124     * Cache the paddingStart set by the user to append to the scrollbar's size.
3125     *
3126     */
3127    @ViewDebug.ExportedProperty(category = "padding")
3128    int mUserPaddingStart;
3129
3130    /**
3131     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3132     *
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    int mUserPaddingEnd;
3136
3137    /**
3138     * Cache initial left padding.
3139     *
3140     * @hide
3141     */
3142    int mUserPaddingLeftInitial;
3143
3144    /**
3145     * Cache initial right padding.
3146     *
3147     * @hide
3148     */
3149    int mUserPaddingRightInitial;
3150
3151    /**
3152     * Default undefined padding
3153     */
3154    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3155
3156    /**
3157     * Cache if a left padding has been defined
3158     */
3159    private boolean mLeftPaddingDefined = false;
3160
3161    /**
3162     * Cache if a right padding has been defined
3163     */
3164    private boolean mRightPaddingDefined = false;
3165
3166    /**
3167     * @hide
3168     */
3169    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3170    /**
3171     * @hide
3172     */
3173    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3174
3175    private LongSparseLongArray mMeasureCache;
3176
3177    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3178    private Drawable mBackground;
3179    private ColorStateList mBackgroundTint = null;
3180    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3181    private boolean mHasBackgroundTint = false;
3182
3183    /**
3184     * RenderNode used for backgrounds.
3185     * <p>
3186     * When non-null and valid, this is expected to contain an up-to-date copy
3187     * of the background drawable. It is cleared on temporary detach, and reset
3188     * on cleanup.
3189     */
3190    private RenderNode mBackgroundRenderNode;
3191
3192    private int mBackgroundResource;
3193    private boolean mBackgroundSizeChanged;
3194
3195    private String mTransitionName;
3196
3197    static class ListenerInfo {
3198        /**
3199         * Listener used to dispatch focus change events.
3200         * This field should be made private, so it is hidden from the SDK.
3201         * {@hide}
3202         */
3203        protected OnFocusChangeListener mOnFocusChangeListener;
3204
3205        /**
3206         * Listeners for layout change events.
3207         */
3208        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3209
3210        /**
3211         * Listeners for attach events.
3212         */
3213        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3214
3215        /**
3216         * Listener used to dispatch click events.
3217         * This field should be made private, so it is hidden from the SDK.
3218         * {@hide}
3219         */
3220        public OnClickListener mOnClickListener;
3221
3222        /**
3223         * Listener used to dispatch long click events.
3224         * This field should be made private, so it is hidden from the SDK.
3225         * {@hide}
3226         */
3227        protected OnLongClickListener mOnLongClickListener;
3228
3229        /**
3230         * Listener used to build the context menu.
3231         * This field should be made private, so it is hidden from the SDK.
3232         * {@hide}
3233         */
3234        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3235
3236        private OnKeyListener mOnKeyListener;
3237
3238        private OnTouchListener mOnTouchListener;
3239
3240        private OnHoverListener mOnHoverListener;
3241
3242        private OnGenericMotionListener mOnGenericMotionListener;
3243
3244        private OnDragListener mOnDragListener;
3245
3246        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3247
3248        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3249    }
3250
3251    ListenerInfo mListenerInfo;
3252
3253    /**
3254     * The application environment this view lives in.
3255     * This field should be made private, so it is hidden from the SDK.
3256     * {@hide}
3257     */
3258    protected Context mContext;
3259
3260    private final Resources mResources;
3261
3262    private ScrollabilityCache mScrollCache;
3263
3264    private int[] mDrawableState = null;
3265
3266    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3267
3268    /**
3269     * Animator that automatically runs based on state changes.
3270     */
3271    private StateListAnimator mStateListAnimator;
3272
3273    /**
3274     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3275     * the user may specify which view to go to next.
3276     */
3277    private int mNextFocusLeftId = View.NO_ID;
3278
3279    /**
3280     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3281     * the user may specify which view to go to next.
3282     */
3283    private int mNextFocusRightId = View.NO_ID;
3284
3285    /**
3286     * When this view has focus and the next focus is {@link #FOCUS_UP},
3287     * the user may specify which view to go to next.
3288     */
3289    private int mNextFocusUpId = View.NO_ID;
3290
3291    /**
3292     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3293     * the user may specify which view to go to next.
3294     */
3295    private int mNextFocusDownId = View.NO_ID;
3296
3297    /**
3298     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3299     * the user may specify which view to go to next.
3300     */
3301    int mNextFocusForwardId = View.NO_ID;
3302
3303    private CheckForLongPress mPendingCheckForLongPress;
3304    private CheckForTap mPendingCheckForTap = null;
3305    private PerformClick mPerformClick;
3306    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3307
3308    private UnsetPressedState mUnsetPressedState;
3309
3310    /**
3311     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3312     * up event while a long press is invoked as soon as the long press duration is reached, so
3313     * a long press could be performed before the tap is checked, in which case the tap's action
3314     * should not be invoked.
3315     */
3316    private boolean mHasPerformedLongPress;
3317
3318    /**
3319     * The minimum height of the view. We'll try our best to have the height
3320     * of this view to at least this amount.
3321     */
3322    @ViewDebug.ExportedProperty(category = "measurement")
3323    private int mMinHeight;
3324
3325    /**
3326     * The minimum width of the view. We'll try our best to have the width
3327     * of this view to at least this amount.
3328     */
3329    @ViewDebug.ExportedProperty(category = "measurement")
3330    private int mMinWidth;
3331
3332    /**
3333     * The delegate to handle touch events that are physically in this view
3334     * but should be handled by another view.
3335     */
3336    private TouchDelegate mTouchDelegate = null;
3337
3338    /**
3339     * Solid color to use as a background when creating the drawing cache. Enables
3340     * the cache to use 16 bit bitmaps instead of 32 bit.
3341     */
3342    private int mDrawingCacheBackgroundColor = 0;
3343
3344    /**
3345     * Special tree observer used when mAttachInfo is null.
3346     */
3347    private ViewTreeObserver mFloatingTreeObserver;
3348
3349    /**
3350     * Cache the touch slop from the context that created the view.
3351     */
3352    private int mTouchSlop;
3353
3354    /**
3355     * Object that handles automatic animation of view properties.
3356     */
3357    private ViewPropertyAnimator mAnimator = null;
3358
3359    /**
3360     * Flag indicating that a drag can cross window boundaries.  When
3361     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3362     * with this flag set, all visible applications will be able to participate
3363     * in the drag operation and receive the dragged content.
3364     *
3365     * @hide
3366     */
3367    public static final int DRAG_FLAG_GLOBAL = 1;
3368
3369    /**
3370     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3371     */
3372    private float mVerticalScrollFactor;
3373
3374    /**
3375     * Position of the vertical scroll bar.
3376     */
3377    private int mVerticalScrollbarPosition;
3378
3379    /**
3380     * Position the scroll bar at the default position as determined by the system.
3381     */
3382    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3383
3384    /**
3385     * Position the scroll bar along the left edge.
3386     */
3387    public static final int SCROLLBAR_POSITION_LEFT = 1;
3388
3389    /**
3390     * Position the scroll bar along the right edge.
3391     */
3392    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3393
3394    /**
3395     * Indicates that the view does not have a layer.
3396     *
3397     * @see #getLayerType()
3398     * @see #setLayerType(int, android.graphics.Paint)
3399     * @see #LAYER_TYPE_SOFTWARE
3400     * @see #LAYER_TYPE_HARDWARE
3401     */
3402    public static final int LAYER_TYPE_NONE = 0;
3403
3404    /**
3405     * <p>Indicates that the view has a software layer. A software layer is backed
3406     * by a bitmap and causes the view to be rendered using Android's software
3407     * rendering pipeline, even if hardware acceleration is enabled.</p>
3408     *
3409     * <p>Software layers have various usages:</p>
3410     * <p>When the application is not using hardware acceleration, a software layer
3411     * is useful to apply a specific color filter and/or blending mode and/or
3412     * translucency to a view and all its children.</p>
3413     * <p>When the application is using hardware acceleration, a software layer
3414     * is useful to render drawing primitives not supported by the hardware
3415     * accelerated pipeline. It can also be used to cache a complex view tree
3416     * into a texture and reduce the complexity of drawing operations. For instance,
3417     * when animating a complex view tree with a translation, a software layer can
3418     * be used to render the view tree only once.</p>
3419     * <p>Software layers should be avoided when the affected view tree updates
3420     * often. Every update will require to re-render the software layer, which can
3421     * potentially be slow (particularly when hardware acceleration is turned on
3422     * since the layer will have to be uploaded into a hardware texture after every
3423     * update.)</p>
3424     *
3425     * @see #getLayerType()
3426     * @see #setLayerType(int, android.graphics.Paint)
3427     * @see #LAYER_TYPE_NONE
3428     * @see #LAYER_TYPE_HARDWARE
3429     */
3430    public static final int LAYER_TYPE_SOFTWARE = 1;
3431
3432    /**
3433     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3434     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3435     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3436     * rendering pipeline, but only if hardware acceleration is turned on for the
3437     * view hierarchy. When hardware acceleration is turned off, hardware layers
3438     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3439     *
3440     * <p>A hardware layer is useful to apply a specific color filter and/or
3441     * blending mode and/or translucency to a view and all its children.</p>
3442     * <p>A hardware layer can be used to cache a complex view tree into a
3443     * texture and reduce the complexity of drawing operations. For instance,
3444     * when animating a complex view tree with a translation, a hardware layer can
3445     * be used to render the view tree only once.</p>
3446     * <p>A hardware layer can also be used to increase the rendering quality when
3447     * rotation transformations are applied on a view. It can also be used to
3448     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3449     *
3450     * @see #getLayerType()
3451     * @see #setLayerType(int, android.graphics.Paint)
3452     * @see #LAYER_TYPE_NONE
3453     * @see #LAYER_TYPE_SOFTWARE
3454     */
3455    public static final int LAYER_TYPE_HARDWARE = 2;
3456
3457    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3458            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3459            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3460            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3461    })
3462    int mLayerType = LAYER_TYPE_NONE;
3463    Paint mLayerPaint;
3464
3465    /**
3466     * Set to true when drawing cache is enabled and cannot be created.
3467     *
3468     * @hide
3469     */
3470    public boolean mCachingFailed;
3471    private Bitmap mDrawingCache;
3472    private Bitmap mUnscaledDrawingCache;
3473
3474    /**
3475     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3476     * <p>
3477     * When non-null and valid, this is expected to contain an up-to-date copy
3478     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3479     * cleanup.
3480     */
3481    final RenderNode mRenderNode;
3482
3483    /**
3484     * Set to true when the view is sending hover accessibility events because it
3485     * is the innermost hovered view.
3486     */
3487    private boolean mSendingHoverAccessibilityEvents;
3488
3489    /**
3490     * Delegate for injecting accessibility functionality.
3491     */
3492    AccessibilityDelegate mAccessibilityDelegate;
3493
3494    /**
3495     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3496     * and add/remove objects to/from the overlay directly through the Overlay methods.
3497     */
3498    ViewOverlay mOverlay;
3499
3500    /**
3501     * The currently active parent view for receiving delegated nested scrolling events.
3502     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3503     * by {@link #stopNestedScroll()} at the same point where we clear
3504     * requestDisallowInterceptTouchEvent.
3505     */
3506    private ViewParent mNestedScrollingParent;
3507
3508    /**
3509     * Consistency verifier for debugging purposes.
3510     * @hide
3511     */
3512    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3513            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3514                    new InputEventConsistencyVerifier(this, 0) : null;
3515
3516    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3517
3518    private int[] mTempNestedScrollConsumed;
3519
3520    /**
3521     * An overlay is going to draw this View instead of being drawn as part of this
3522     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3523     * when this view is invalidated.
3524     */
3525    GhostView mGhostView;
3526
3527    /**
3528     * Simple constructor to use when creating a view from code.
3529     *
3530     * @param context The Context the view is running in, through which it can
3531     *        access the current theme, resources, etc.
3532     */
3533    public View(Context context) {
3534        mContext = context;
3535        mResources = context != null ? context.getResources() : null;
3536        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3537        // Set some flags defaults
3538        mPrivateFlags2 =
3539                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3540                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3541                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3542                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3543                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3544                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3545        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3546        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3547        mUserPaddingStart = UNDEFINED_PADDING;
3548        mUserPaddingEnd = UNDEFINED_PADDING;
3549        mRenderNode = RenderNode.create(getClass().getName());
3550
3551        if (!sCompatibilityDone && context != null) {
3552            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3553
3554            // Older apps may need this compatibility hack for measurement.
3555            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3556
3557            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3558            // of whether a layout was requested on that View.
3559            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3560
3561            sCompatibilityDone = true;
3562        }
3563    }
3564
3565    /**
3566     * Constructor that is called when inflating a view from XML. This is called
3567     * when a view is being constructed from an XML file, supplying attributes
3568     * that were specified in the XML file. This version uses a default style of
3569     * 0, so the only attribute values applied are those in the Context's Theme
3570     * and the given AttributeSet.
3571     *
3572     * <p>
3573     * The method onFinishInflate() will be called after all children have been
3574     * added.
3575     *
3576     * @param context The Context the view is running in, through which it can
3577     *        access the current theme, resources, etc.
3578     * @param attrs The attributes of the XML tag that is inflating the view.
3579     * @see #View(Context, AttributeSet, int)
3580     */
3581    public View(Context context, AttributeSet attrs) {
3582        this(context, attrs, 0);
3583    }
3584
3585    /**
3586     * Perform inflation from XML and apply a class-specific base style from a
3587     * theme attribute. This constructor of View allows subclasses to use their
3588     * own base style when they are inflating. For example, a Button class's
3589     * constructor would call this version of the super class constructor and
3590     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3591     * allows the theme's button style to modify all of the base view attributes
3592     * (in particular its background) as well as the Button class's attributes.
3593     *
3594     * @param context The Context the view is running in, through which it can
3595     *        access the current theme, resources, etc.
3596     * @param attrs The attributes of the XML tag that is inflating the view.
3597     * @param defStyleAttr An attribute in the current theme that contains a
3598     *        reference to a style resource that supplies default values for
3599     *        the view. Can be 0 to not look for defaults.
3600     * @see #View(Context, AttributeSet)
3601     */
3602    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3603        this(context, attrs, defStyleAttr, 0);
3604    }
3605
3606    /**
3607     * Perform inflation from XML and apply a class-specific base style from a
3608     * theme attribute or style resource. This constructor of View allows
3609     * subclasses to use their own base style when they are inflating.
3610     * <p>
3611     * When determining the final value of a particular attribute, there are
3612     * four inputs that come into play:
3613     * <ol>
3614     * <li>Any attribute values in the given AttributeSet.
3615     * <li>The style resource specified in the AttributeSet (named "style").
3616     * <li>The default style specified by <var>defStyleAttr</var>.
3617     * <li>The default style specified by <var>defStyleRes</var>.
3618     * <li>The base values in this theme.
3619     * </ol>
3620     * <p>
3621     * Each of these inputs is considered in-order, with the first listed taking
3622     * precedence over the following ones. In other words, if in the
3623     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3624     * , then the button's text will <em>always</em> be black, regardless of
3625     * what is specified in any of the styles.
3626     *
3627     * @param context The Context the view is running in, through which it can
3628     *        access the current theme, resources, etc.
3629     * @param attrs The attributes of the XML tag that is inflating the view.
3630     * @param defStyleAttr An attribute in the current theme that contains a
3631     *        reference to a style resource that supplies default values for
3632     *        the view. Can be 0 to not look for defaults.
3633     * @param defStyleRes A resource identifier of a style resource that
3634     *        supplies default values for the view, used only if
3635     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3636     *        to not look for defaults.
3637     * @see #View(Context, AttributeSet, int)
3638     */
3639    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3640        this(context);
3641
3642        final TypedArray a = context.obtainStyledAttributes(
3643                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3644
3645        Drawable background = null;
3646
3647        int leftPadding = -1;
3648        int topPadding = -1;
3649        int rightPadding = -1;
3650        int bottomPadding = -1;
3651        int startPadding = UNDEFINED_PADDING;
3652        int endPadding = UNDEFINED_PADDING;
3653
3654        int padding = -1;
3655
3656        int viewFlagValues = 0;
3657        int viewFlagMasks = 0;
3658
3659        boolean setScrollContainer = false;
3660
3661        int x = 0;
3662        int y = 0;
3663
3664        float tx = 0;
3665        float ty = 0;
3666        float tz = 0;
3667        float elevation = 0;
3668        float rotation = 0;
3669        float rotationX = 0;
3670        float rotationY = 0;
3671        float sx = 1f;
3672        float sy = 1f;
3673        boolean transformSet = false;
3674
3675        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3676        int overScrollMode = mOverScrollMode;
3677        boolean initializeScrollbars = false;
3678
3679        boolean startPaddingDefined = false;
3680        boolean endPaddingDefined = false;
3681        boolean leftPaddingDefined = false;
3682        boolean rightPaddingDefined = false;
3683
3684        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3685
3686        final int N = a.getIndexCount();
3687        for (int i = 0; i < N; i++) {
3688            int attr = a.getIndex(i);
3689            switch (attr) {
3690                case com.android.internal.R.styleable.View_background:
3691                    background = a.getDrawable(attr);
3692                    break;
3693                case com.android.internal.R.styleable.View_padding:
3694                    padding = a.getDimensionPixelSize(attr, -1);
3695                    mUserPaddingLeftInitial = padding;
3696                    mUserPaddingRightInitial = padding;
3697                    leftPaddingDefined = true;
3698                    rightPaddingDefined = true;
3699                    break;
3700                 case com.android.internal.R.styleable.View_paddingLeft:
3701                    leftPadding = a.getDimensionPixelSize(attr, -1);
3702                    mUserPaddingLeftInitial = leftPadding;
3703                    leftPaddingDefined = true;
3704                    break;
3705                case com.android.internal.R.styleable.View_paddingTop:
3706                    topPadding = a.getDimensionPixelSize(attr, -1);
3707                    break;
3708                case com.android.internal.R.styleable.View_paddingRight:
3709                    rightPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingRightInitial = rightPadding;
3711                    rightPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingBottom:
3714                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingStart:
3717                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3718                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3719                    break;
3720                case com.android.internal.R.styleable.View_paddingEnd:
3721                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3722                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3723                    break;
3724                case com.android.internal.R.styleable.View_scrollX:
3725                    x = a.getDimensionPixelOffset(attr, 0);
3726                    break;
3727                case com.android.internal.R.styleable.View_scrollY:
3728                    y = a.getDimensionPixelOffset(attr, 0);
3729                    break;
3730                case com.android.internal.R.styleable.View_alpha:
3731                    setAlpha(a.getFloat(attr, 1f));
3732                    break;
3733                case com.android.internal.R.styleable.View_transformPivotX:
3734                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3735                    break;
3736                case com.android.internal.R.styleable.View_transformPivotY:
3737                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3738                    break;
3739                case com.android.internal.R.styleable.View_translationX:
3740                    tx = a.getDimensionPixelOffset(attr, 0);
3741                    transformSet = true;
3742                    break;
3743                case com.android.internal.R.styleable.View_translationY:
3744                    ty = a.getDimensionPixelOffset(attr, 0);
3745                    transformSet = true;
3746                    break;
3747                case com.android.internal.R.styleable.View_translationZ:
3748                    tz = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_elevation:
3752                    elevation = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_rotation:
3756                    rotation = a.getFloat(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_rotationX:
3760                    rotationX = a.getFloat(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotationY:
3764                    rotationY = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_scaleX:
3768                    sx = a.getFloat(attr, 1f);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_scaleY:
3772                    sy = a.getFloat(attr, 1f);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_id:
3776                    mID = a.getResourceId(attr, NO_ID);
3777                    break;
3778                case com.android.internal.R.styleable.View_tag:
3779                    mTag = a.getText(attr);
3780                    break;
3781                case com.android.internal.R.styleable.View_fitsSystemWindows:
3782                    if (a.getBoolean(attr, false)) {
3783                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3784                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3785                    }
3786                    break;
3787                case com.android.internal.R.styleable.View_focusable:
3788                    if (a.getBoolean(attr, false)) {
3789                        viewFlagValues |= FOCUSABLE;
3790                        viewFlagMasks |= FOCUSABLE_MASK;
3791                    }
3792                    break;
3793                case com.android.internal.R.styleable.View_focusableInTouchMode:
3794                    if (a.getBoolean(attr, false)) {
3795                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3796                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3797                    }
3798                    break;
3799                case com.android.internal.R.styleable.View_clickable:
3800                    if (a.getBoolean(attr, false)) {
3801                        viewFlagValues |= CLICKABLE;
3802                        viewFlagMasks |= CLICKABLE;
3803                    }
3804                    break;
3805                case com.android.internal.R.styleable.View_longClickable:
3806                    if (a.getBoolean(attr, false)) {
3807                        viewFlagValues |= LONG_CLICKABLE;
3808                        viewFlagMasks |= LONG_CLICKABLE;
3809                    }
3810                    break;
3811                case com.android.internal.R.styleable.View_saveEnabled:
3812                    if (!a.getBoolean(attr, true)) {
3813                        viewFlagValues |= SAVE_DISABLED;
3814                        viewFlagMasks |= SAVE_DISABLED_MASK;
3815                    }
3816                    break;
3817                case com.android.internal.R.styleable.View_duplicateParentState:
3818                    if (a.getBoolean(attr, false)) {
3819                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3820                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3821                    }
3822                    break;
3823                case com.android.internal.R.styleable.View_visibility:
3824                    final int visibility = a.getInt(attr, 0);
3825                    if (visibility != 0) {
3826                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3827                        viewFlagMasks |= VISIBILITY_MASK;
3828                    }
3829                    break;
3830                case com.android.internal.R.styleable.View_layoutDirection:
3831                    // Clear any layout direction flags (included resolved bits) already set
3832                    mPrivateFlags2 &=
3833                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3834                    // Set the layout direction flags depending on the value of the attribute
3835                    final int layoutDirection = a.getInt(attr, -1);
3836                    final int value = (layoutDirection != -1) ?
3837                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3838                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3839                    break;
3840                case com.android.internal.R.styleable.View_drawingCacheQuality:
3841                    final int cacheQuality = a.getInt(attr, 0);
3842                    if (cacheQuality != 0) {
3843                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3844                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3845                    }
3846                    break;
3847                case com.android.internal.R.styleable.View_contentDescription:
3848                    setContentDescription(a.getString(attr));
3849                    break;
3850                case com.android.internal.R.styleable.View_labelFor:
3851                    setLabelFor(a.getResourceId(attr, NO_ID));
3852                    break;
3853                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3854                    if (!a.getBoolean(attr, true)) {
3855                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3856                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3860                    if (!a.getBoolean(attr, true)) {
3861                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3862                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3863                    }
3864                    break;
3865                case R.styleable.View_scrollbars:
3866                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3867                    if (scrollbars != SCROLLBARS_NONE) {
3868                        viewFlagValues |= scrollbars;
3869                        viewFlagMasks |= SCROLLBARS_MASK;
3870                        initializeScrollbars = true;
3871                    }
3872                    break;
3873                //noinspection deprecation
3874                case R.styleable.View_fadingEdge:
3875                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3876                        // Ignore the attribute starting with ICS
3877                        break;
3878                    }
3879                    // With builds < ICS, fall through and apply fading edges
3880                case R.styleable.View_requiresFadingEdge:
3881                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3882                    if (fadingEdge != FADING_EDGE_NONE) {
3883                        viewFlagValues |= fadingEdge;
3884                        viewFlagMasks |= FADING_EDGE_MASK;
3885                        initializeFadingEdgeInternal(a);
3886                    }
3887                    break;
3888                case R.styleable.View_scrollbarStyle:
3889                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3890                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3891                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3892                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3893                    }
3894                    break;
3895                case R.styleable.View_isScrollContainer:
3896                    setScrollContainer = true;
3897                    if (a.getBoolean(attr, false)) {
3898                        setScrollContainer(true);
3899                    }
3900                    break;
3901                case com.android.internal.R.styleable.View_keepScreenOn:
3902                    if (a.getBoolean(attr, false)) {
3903                        viewFlagValues |= KEEP_SCREEN_ON;
3904                        viewFlagMasks |= KEEP_SCREEN_ON;
3905                    }
3906                    break;
3907                case R.styleable.View_filterTouchesWhenObscured:
3908                    if (a.getBoolean(attr, false)) {
3909                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3910                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3911                    }
3912                    break;
3913                case R.styleable.View_nextFocusLeft:
3914                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3915                    break;
3916                case R.styleable.View_nextFocusRight:
3917                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3918                    break;
3919                case R.styleable.View_nextFocusUp:
3920                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3921                    break;
3922                case R.styleable.View_nextFocusDown:
3923                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3924                    break;
3925                case R.styleable.View_nextFocusForward:
3926                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3927                    break;
3928                case R.styleable.View_minWidth:
3929                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3930                    break;
3931                case R.styleable.View_minHeight:
3932                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3933                    break;
3934                case R.styleable.View_onClick:
3935                    if (context.isRestricted()) {
3936                        throw new IllegalStateException("The android:onClick attribute cannot "
3937                                + "be used within a restricted context");
3938                    }
3939
3940                    final String handlerName = a.getString(attr);
3941                    if (handlerName != null) {
3942                        setOnClickListener(new OnClickListener() {
3943                            private Method mHandler;
3944
3945                            public void onClick(View v) {
3946                                if (mHandler == null) {
3947                                    try {
3948                                        mHandler = getContext().getClass().getMethod(handlerName,
3949                                                View.class);
3950                                    } catch (NoSuchMethodException e) {
3951                                        int id = getId();
3952                                        String idText = id == NO_ID ? "" : " with id '"
3953                                                + getContext().getResources().getResourceEntryName(
3954                                                    id) + "'";
3955                                        throw new IllegalStateException("Could not find a method " +
3956                                                handlerName + "(View) in the activity "
3957                                                + getContext().getClass() + " for onClick handler"
3958                                                + " on view " + View.this.getClass() + idText, e);
3959                                    }
3960                                }
3961
3962                                try {
3963                                    mHandler.invoke(getContext(), View.this);
3964                                } catch (IllegalAccessException e) {
3965                                    throw new IllegalStateException("Could not execute non "
3966                                            + "public method of the activity", e);
3967                                } catch (InvocationTargetException e) {
3968                                    throw new IllegalStateException("Could not execute "
3969                                            + "method of the activity", e);
3970                                }
3971                            }
3972                        });
3973                    }
3974                    break;
3975                case R.styleable.View_overScrollMode:
3976                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3977                    break;
3978                case R.styleable.View_verticalScrollbarPosition:
3979                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3980                    break;
3981                case R.styleable.View_layerType:
3982                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3983                    break;
3984                case R.styleable.View_textDirection:
3985                    // Clear any text direction flag already set
3986                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3987                    // Set the text direction flags depending on the value of the attribute
3988                    final int textDirection = a.getInt(attr, -1);
3989                    if (textDirection != -1) {
3990                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3991                    }
3992                    break;
3993                case R.styleable.View_textAlignment:
3994                    // Clear any text alignment flag already set
3995                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3996                    // Set the text alignment flag depending on the value of the attribute
3997                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3998                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3999                    break;
4000                case R.styleable.View_importantForAccessibility:
4001                    setImportantForAccessibility(a.getInt(attr,
4002                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4003                    break;
4004                case R.styleable.View_accessibilityLiveRegion:
4005                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4006                    break;
4007                case R.styleable.View_transitionName:
4008                    setTransitionName(a.getString(attr));
4009                    break;
4010                case R.styleable.View_nestedScrollingEnabled:
4011                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4012                    break;
4013                case R.styleable.View_stateListAnimator:
4014                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4015                            a.getResourceId(attr, 0)));
4016                    break;
4017                case R.styleable.View_backgroundTint:
4018                    // This will get applied later during setBackground().
4019                    mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint);
4020                    mHasBackgroundTint = true;
4021                    break;
4022                case R.styleable.View_backgroundTintMode:
4023                    // This will get applied later during setBackground().
4024                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4025                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4026                    break;
4027            }
4028        }
4029
4030        setOverScrollMode(overScrollMode);
4031
4032        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4033        // the resolved layout direction). Those cached values will be used later during padding
4034        // resolution.
4035        mUserPaddingStart = startPadding;
4036        mUserPaddingEnd = endPadding;
4037
4038        if (background != null) {
4039            setBackground(background);
4040        }
4041
4042        // setBackground above will record that padding is currently provided by the background.
4043        // If we have padding specified via xml, record that here instead and use it.
4044        mLeftPaddingDefined = leftPaddingDefined;
4045        mRightPaddingDefined = rightPaddingDefined;
4046
4047        if (padding >= 0) {
4048            leftPadding = padding;
4049            topPadding = padding;
4050            rightPadding = padding;
4051            bottomPadding = padding;
4052            mUserPaddingLeftInitial = padding;
4053            mUserPaddingRightInitial = padding;
4054        }
4055
4056        if (isRtlCompatibilityMode()) {
4057            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4058            // left / right padding are used if defined (meaning here nothing to do). If they are not
4059            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4060            // start / end and resolve them as left / right (layout direction is not taken into account).
4061            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4062            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4063            // defined.
4064            if (!mLeftPaddingDefined && startPaddingDefined) {
4065                leftPadding = startPadding;
4066            }
4067            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4068            if (!mRightPaddingDefined && endPaddingDefined) {
4069                rightPadding = endPadding;
4070            }
4071            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4072        } else {
4073            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4074            // values defined. Otherwise, left /right values are used.
4075            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4076            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4077            // defined.
4078            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4079
4080            if (mLeftPaddingDefined && !hasRelativePadding) {
4081                mUserPaddingLeftInitial = leftPadding;
4082            }
4083            if (mRightPaddingDefined && !hasRelativePadding) {
4084                mUserPaddingRightInitial = rightPadding;
4085            }
4086        }
4087
4088        internalSetPadding(
4089                mUserPaddingLeftInitial,
4090                topPadding >= 0 ? topPadding : mPaddingTop,
4091                mUserPaddingRightInitial,
4092                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4093
4094        if (viewFlagMasks != 0) {
4095            setFlags(viewFlagValues, viewFlagMasks);
4096        }
4097
4098        if (initializeScrollbars) {
4099            initializeScrollbarsInternal(a);
4100        }
4101
4102        a.recycle();
4103
4104        // Needs to be called after mViewFlags is set
4105        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4106            recomputePadding();
4107        }
4108
4109        if (x != 0 || y != 0) {
4110            scrollTo(x, y);
4111        }
4112
4113        if (transformSet) {
4114            setTranslationX(tx);
4115            setTranslationY(ty);
4116            setTranslationZ(tz);
4117            setElevation(elevation);
4118            setRotation(rotation);
4119            setRotationX(rotationX);
4120            setRotationY(rotationY);
4121            setScaleX(sx);
4122            setScaleY(sy);
4123        }
4124
4125        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4126            setScrollContainer(true);
4127        }
4128
4129        computeOpaqueFlags();
4130    }
4131
4132    /**
4133     * Non-public constructor for use in testing
4134     */
4135    View() {
4136        mResources = null;
4137        mRenderNode = RenderNode.create(getClass().getName());
4138    }
4139
4140    public String toString() {
4141        StringBuilder out = new StringBuilder(128);
4142        out.append(getClass().getName());
4143        out.append('{');
4144        out.append(Integer.toHexString(System.identityHashCode(this)));
4145        out.append(' ');
4146        switch (mViewFlags&VISIBILITY_MASK) {
4147            case VISIBLE: out.append('V'); break;
4148            case INVISIBLE: out.append('I'); break;
4149            case GONE: out.append('G'); break;
4150            default: out.append('.'); break;
4151        }
4152        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4153        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4154        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4155        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4156        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4157        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4158        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4159        out.append(' ');
4160        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4161        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4162        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4163        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4164            out.append('p');
4165        } else {
4166            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4167        }
4168        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4169        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4170        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4171        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4172        out.append(' ');
4173        out.append(mLeft);
4174        out.append(',');
4175        out.append(mTop);
4176        out.append('-');
4177        out.append(mRight);
4178        out.append(',');
4179        out.append(mBottom);
4180        final int id = getId();
4181        if (id != NO_ID) {
4182            out.append(" #");
4183            out.append(Integer.toHexString(id));
4184            final Resources r = mResources;
4185            if (Resources.resourceHasPackage(id) && r != null) {
4186                try {
4187                    String pkgname;
4188                    switch (id&0xff000000) {
4189                        case 0x7f000000:
4190                            pkgname="app";
4191                            break;
4192                        case 0x01000000:
4193                            pkgname="android";
4194                            break;
4195                        default:
4196                            pkgname = r.getResourcePackageName(id);
4197                            break;
4198                    }
4199                    String typename = r.getResourceTypeName(id);
4200                    String entryname = r.getResourceEntryName(id);
4201                    out.append(" ");
4202                    out.append(pkgname);
4203                    out.append(":");
4204                    out.append(typename);
4205                    out.append("/");
4206                    out.append(entryname);
4207                } catch (Resources.NotFoundException e) {
4208                }
4209            }
4210        }
4211        out.append("}");
4212        return out.toString();
4213    }
4214
4215    /**
4216     * <p>
4217     * Initializes the fading edges from a given set of styled attributes. This
4218     * method should be called by subclasses that need fading edges and when an
4219     * instance of these subclasses is created programmatically rather than
4220     * being inflated from XML. This method is automatically called when the XML
4221     * is inflated.
4222     * </p>
4223     *
4224     * @param a the styled attributes set to initialize the fading edges from
4225     */
4226    protected void initializeFadingEdge(TypedArray a) {
4227        // This method probably shouldn't have been included in the SDK to begin with.
4228        // It relies on 'a' having been initialized using an attribute filter array that is
4229        // not publicly available to the SDK. The old method has been renamed
4230        // to initializeFadingEdgeInternal and hidden for framework use only;
4231        // this one initializes using defaults to make it safe to call for apps.
4232
4233        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4234
4235        initializeFadingEdgeInternal(arr);
4236
4237        arr.recycle();
4238    }
4239
4240    /**
4241     * <p>
4242     * Initializes the fading edges from a given set of styled attributes. This
4243     * method should be called by subclasses that need fading edges and when an
4244     * instance of these subclasses is created programmatically rather than
4245     * being inflated from XML. This method is automatically called when the XML
4246     * is inflated.
4247     * </p>
4248     *
4249     * @param a the styled attributes set to initialize the fading edges from
4250     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4251     */
4252    protected void initializeFadingEdgeInternal(TypedArray a) {
4253        initScrollCache();
4254
4255        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4256                R.styleable.View_fadingEdgeLength,
4257                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4258    }
4259
4260    /**
4261     * Returns the size of the vertical faded edges used to indicate that more
4262     * content in this view is visible.
4263     *
4264     * @return The size in pixels of the vertical faded edge or 0 if vertical
4265     *         faded edges are not enabled for this view.
4266     * @attr ref android.R.styleable#View_fadingEdgeLength
4267     */
4268    public int getVerticalFadingEdgeLength() {
4269        if (isVerticalFadingEdgeEnabled()) {
4270            ScrollabilityCache cache = mScrollCache;
4271            if (cache != null) {
4272                return cache.fadingEdgeLength;
4273            }
4274        }
4275        return 0;
4276    }
4277
4278    /**
4279     * Set the size of the faded edge used to indicate that more content in this
4280     * view is available.  Will not change whether the fading edge is enabled; use
4281     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4282     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4283     * for the vertical or horizontal fading edges.
4284     *
4285     * @param length The size in pixels of the faded edge used to indicate that more
4286     *        content in this view is visible.
4287     */
4288    public void setFadingEdgeLength(int length) {
4289        initScrollCache();
4290        mScrollCache.fadingEdgeLength = length;
4291    }
4292
4293    /**
4294     * Returns the size of the horizontal faded edges used to indicate that more
4295     * content in this view is visible.
4296     *
4297     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4298     *         faded edges are not enabled for this view.
4299     * @attr ref android.R.styleable#View_fadingEdgeLength
4300     */
4301    public int getHorizontalFadingEdgeLength() {
4302        if (isHorizontalFadingEdgeEnabled()) {
4303            ScrollabilityCache cache = mScrollCache;
4304            if (cache != null) {
4305                return cache.fadingEdgeLength;
4306            }
4307        }
4308        return 0;
4309    }
4310
4311    /**
4312     * Returns the width of the vertical scrollbar.
4313     *
4314     * @return The width in pixels of the vertical scrollbar or 0 if there
4315     *         is no vertical scrollbar.
4316     */
4317    public int getVerticalScrollbarWidth() {
4318        ScrollabilityCache cache = mScrollCache;
4319        if (cache != null) {
4320            ScrollBarDrawable scrollBar = cache.scrollBar;
4321            if (scrollBar != null) {
4322                int size = scrollBar.getSize(true);
4323                if (size <= 0) {
4324                    size = cache.scrollBarSize;
4325                }
4326                return size;
4327            }
4328            return 0;
4329        }
4330        return 0;
4331    }
4332
4333    /**
4334     * Returns the height of the horizontal scrollbar.
4335     *
4336     * @return The height in pixels of the horizontal scrollbar or 0 if
4337     *         there is no horizontal scrollbar.
4338     */
4339    protected int getHorizontalScrollbarHeight() {
4340        ScrollabilityCache cache = mScrollCache;
4341        if (cache != null) {
4342            ScrollBarDrawable scrollBar = cache.scrollBar;
4343            if (scrollBar != null) {
4344                int size = scrollBar.getSize(false);
4345                if (size <= 0) {
4346                    size = cache.scrollBarSize;
4347                }
4348                return size;
4349            }
4350            return 0;
4351        }
4352        return 0;
4353    }
4354
4355    /**
4356     * <p>
4357     * Initializes the scrollbars from a given set of styled attributes. This
4358     * method should be called by subclasses that need scrollbars and when an
4359     * instance of these subclasses is created programmatically rather than
4360     * being inflated from XML. This method is automatically called when the XML
4361     * is inflated.
4362     * </p>
4363     *
4364     * @param a the styled attributes set to initialize the scrollbars from
4365     */
4366    protected void initializeScrollbars(TypedArray a) {
4367        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4368        // using the View filter array which is not available to the SDK. As such, internal
4369        // framework usage now uses initializeScrollbarsInternal and we grab a default
4370        // TypedArray with the right filter instead here.
4371        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4372
4373        initializeScrollbarsInternal(arr);
4374
4375        // We ignored the method parameter. Recycle the one we actually did use.
4376        arr.recycle();
4377    }
4378
4379    /**
4380     * <p>
4381     * Initializes the scrollbars from a given set of styled attributes. This
4382     * method should be called by subclasses that need scrollbars and when an
4383     * instance of these subclasses is created programmatically rather than
4384     * being inflated from XML. This method is automatically called when the XML
4385     * is inflated.
4386     * </p>
4387     *
4388     * @param a the styled attributes set to initialize the scrollbars from
4389     * @hide
4390     */
4391    protected void initializeScrollbarsInternal(TypedArray a) {
4392        initScrollCache();
4393
4394        final ScrollabilityCache scrollabilityCache = mScrollCache;
4395
4396        if (scrollabilityCache.scrollBar == null) {
4397            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4398        }
4399
4400        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4401
4402        if (!fadeScrollbars) {
4403            scrollabilityCache.state = ScrollabilityCache.ON;
4404        }
4405        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4406
4407
4408        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4409                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4410                        .getScrollBarFadeDuration());
4411        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4412                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4413                ViewConfiguration.getScrollDefaultDelay());
4414
4415
4416        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4417                com.android.internal.R.styleable.View_scrollbarSize,
4418                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4419
4420        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4421        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4422
4423        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4424        if (thumb != null) {
4425            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4426        }
4427
4428        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4429                false);
4430        if (alwaysDraw) {
4431            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4432        }
4433
4434        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4435        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4436
4437        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4438        if (thumb != null) {
4439            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4440        }
4441
4442        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4443                false);
4444        if (alwaysDraw) {
4445            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4446        }
4447
4448        // Apply layout direction to the new Drawables if needed
4449        final int layoutDirection = getLayoutDirection();
4450        if (track != null) {
4451            track.setLayoutDirection(layoutDirection);
4452        }
4453        if (thumb != null) {
4454            thumb.setLayoutDirection(layoutDirection);
4455        }
4456
4457        // Re-apply user/background padding so that scrollbar(s) get added
4458        resolvePadding();
4459    }
4460
4461    /**
4462     * <p>
4463     * Initalizes the scrollability cache if necessary.
4464     * </p>
4465     */
4466    private void initScrollCache() {
4467        if (mScrollCache == null) {
4468            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4469        }
4470    }
4471
4472    private ScrollabilityCache getScrollCache() {
4473        initScrollCache();
4474        return mScrollCache;
4475    }
4476
4477    /**
4478     * Set the position of the vertical scroll bar. Should be one of
4479     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4480     * {@link #SCROLLBAR_POSITION_RIGHT}.
4481     *
4482     * @param position Where the vertical scroll bar should be positioned.
4483     */
4484    public void setVerticalScrollbarPosition(int position) {
4485        if (mVerticalScrollbarPosition != position) {
4486            mVerticalScrollbarPosition = position;
4487            computeOpaqueFlags();
4488            resolvePadding();
4489        }
4490    }
4491
4492    /**
4493     * @return The position where the vertical scroll bar will show, if applicable.
4494     * @see #setVerticalScrollbarPosition(int)
4495     */
4496    public int getVerticalScrollbarPosition() {
4497        return mVerticalScrollbarPosition;
4498    }
4499
4500    ListenerInfo getListenerInfo() {
4501        if (mListenerInfo != null) {
4502            return mListenerInfo;
4503        }
4504        mListenerInfo = new ListenerInfo();
4505        return mListenerInfo;
4506    }
4507
4508    /**
4509     * Register a callback to be invoked when focus of this view changed.
4510     *
4511     * @param l The callback that will run.
4512     */
4513    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4514        getListenerInfo().mOnFocusChangeListener = l;
4515    }
4516
4517    /**
4518     * Add a listener that will be called when the bounds of the view change due to
4519     * layout processing.
4520     *
4521     * @param listener The listener that will be called when layout bounds change.
4522     */
4523    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4524        ListenerInfo li = getListenerInfo();
4525        if (li.mOnLayoutChangeListeners == null) {
4526            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4527        }
4528        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4529            li.mOnLayoutChangeListeners.add(listener);
4530        }
4531    }
4532
4533    /**
4534     * Remove a listener for layout changes.
4535     *
4536     * @param listener The listener for layout bounds change.
4537     */
4538    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4539        ListenerInfo li = mListenerInfo;
4540        if (li == null || li.mOnLayoutChangeListeners == null) {
4541            return;
4542        }
4543        li.mOnLayoutChangeListeners.remove(listener);
4544    }
4545
4546    /**
4547     * Add a listener for attach state changes.
4548     *
4549     * This listener will be called whenever this view is attached or detached
4550     * from a window. Remove the listener using
4551     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4552     *
4553     * @param listener Listener to attach
4554     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4555     */
4556    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4557        ListenerInfo li = getListenerInfo();
4558        if (li.mOnAttachStateChangeListeners == null) {
4559            li.mOnAttachStateChangeListeners
4560                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4561        }
4562        li.mOnAttachStateChangeListeners.add(listener);
4563    }
4564
4565    /**
4566     * Remove a listener for attach state changes. The listener will receive no further
4567     * notification of window attach/detach events.
4568     *
4569     * @param listener Listener to remove
4570     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4571     */
4572    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4573        ListenerInfo li = mListenerInfo;
4574        if (li == null || li.mOnAttachStateChangeListeners == null) {
4575            return;
4576        }
4577        li.mOnAttachStateChangeListeners.remove(listener);
4578    }
4579
4580    /**
4581     * Returns the focus-change callback registered for this view.
4582     *
4583     * @return The callback, or null if one is not registered.
4584     */
4585    public OnFocusChangeListener getOnFocusChangeListener() {
4586        ListenerInfo li = mListenerInfo;
4587        return li != null ? li.mOnFocusChangeListener : null;
4588    }
4589
4590    /**
4591     * Register a callback to be invoked when this view is clicked. If this view is not
4592     * clickable, it becomes clickable.
4593     *
4594     * @param l The callback that will run
4595     *
4596     * @see #setClickable(boolean)
4597     */
4598    public void setOnClickListener(OnClickListener l) {
4599        if (!isClickable()) {
4600            setClickable(true);
4601        }
4602        getListenerInfo().mOnClickListener = l;
4603    }
4604
4605    /**
4606     * Return whether this view has an attached OnClickListener.  Returns
4607     * true if there is a listener, false if there is none.
4608     */
4609    public boolean hasOnClickListeners() {
4610        ListenerInfo li = mListenerInfo;
4611        return (li != null && li.mOnClickListener != null);
4612    }
4613
4614    /**
4615     * Register a callback to be invoked when this view is clicked and held. If this view is not
4616     * long clickable, it becomes long clickable.
4617     *
4618     * @param l The callback that will run
4619     *
4620     * @see #setLongClickable(boolean)
4621     */
4622    public void setOnLongClickListener(OnLongClickListener l) {
4623        if (!isLongClickable()) {
4624            setLongClickable(true);
4625        }
4626        getListenerInfo().mOnLongClickListener = l;
4627    }
4628
4629    /**
4630     * Register a callback to be invoked when the context menu for this view is
4631     * being built. If this view is not long clickable, it becomes long clickable.
4632     *
4633     * @param l The callback that will run
4634     *
4635     */
4636    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4637        if (!isLongClickable()) {
4638            setLongClickable(true);
4639        }
4640        getListenerInfo().mOnCreateContextMenuListener = l;
4641    }
4642
4643    /**
4644     * Call this view's OnClickListener, if it is defined.  Performs all normal
4645     * actions associated with clicking: reporting accessibility event, playing
4646     * a sound, etc.
4647     *
4648     * @return True there was an assigned OnClickListener that was called, false
4649     *         otherwise is returned.
4650     */
4651    public boolean performClick() {
4652        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4653
4654        ListenerInfo li = mListenerInfo;
4655        if (li != null && li.mOnClickListener != null) {
4656            playSoundEffect(SoundEffectConstants.CLICK);
4657            li.mOnClickListener.onClick(this);
4658            return true;
4659        }
4660
4661        return false;
4662    }
4663
4664    /**
4665     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4666     * this only calls the listener, and does not do any associated clicking
4667     * actions like reporting an accessibility event.
4668     *
4669     * @return True there was an assigned OnClickListener that was called, false
4670     *         otherwise is returned.
4671     */
4672    public boolean callOnClick() {
4673        ListenerInfo li = mListenerInfo;
4674        if (li != null && li.mOnClickListener != null) {
4675            li.mOnClickListener.onClick(this);
4676            return true;
4677        }
4678        return false;
4679    }
4680
4681    /**
4682     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4683     * OnLongClickListener did not consume the event.
4684     *
4685     * @return True if one of the above receivers consumed the event, false otherwise.
4686     */
4687    public boolean performLongClick() {
4688        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4689
4690        boolean handled = false;
4691        ListenerInfo li = mListenerInfo;
4692        if (li != null && li.mOnLongClickListener != null) {
4693            handled = li.mOnLongClickListener.onLongClick(View.this);
4694        }
4695        if (!handled) {
4696            handled = showContextMenu();
4697        }
4698        if (handled) {
4699            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4700        }
4701        return handled;
4702    }
4703
4704    /**
4705     * Performs button-related actions during a touch down event.
4706     *
4707     * @param event The event.
4708     * @return True if the down was consumed.
4709     *
4710     * @hide
4711     */
4712    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4713        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4714            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4715                return true;
4716            }
4717        }
4718        return false;
4719    }
4720
4721    /**
4722     * Bring up the context menu for this view.
4723     *
4724     * @return Whether a context menu was displayed.
4725     */
4726    public boolean showContextMenu() {
4727        return getParent().showContextMenuForChild(this);
4728    }
4729
4730    /**
4731     * Bring up the context menu for this view, referring to the item under the specified point.
4732     *
4733     * @param x The referenced x coordinate.
4734     * @param y The referenced y coordinate.
4735     * @param metaState The keyboard modifiers that were pressed.
4736     * @return Whether a context menu was displayed.
4737     *
4738     * @hide
4739     */
4740    public boolean showContextMenu(float x, float y, int metaState) {
4741        return showContextMenu();
4742    }
4743
4744    /**
4745     * Start an action mode.
4746     *
4747     * @param callback Callback that will control the lifecycle of the action mode
4748     * @return The new action mode if it is started, null otherwise
4749     *
4750     * @see ActionMode
4751     */
4752    public ActionMode startActionMode(ActionMode.Callback callback) {
4753        ViewParent parent = getParent();
4754        if (parent == null) return null;
4755        return parent.startActionModeForChild(this, callback);
4756    }
4757
4758    /**
4759     * Register a callback to be invoked when a hardware key is pressed in this view.
4760     * Key presses in software input methods will generally not trigger the methods of
4761     * this listener.
4762     * @param l the key listener to attach to this view
4763     */
4764    public void setOnKeyListener(OnKeyListener l) {
4765        getListenerInfo().mOnKeyListener = l;
4766    }
4767
4768    /**
4769     * Register a callback to be invoked when a touch event is sent to this view.
4770     * @param l the touch listener to attach to this view
4771     */
4772    public void setOnTouchListener(OnTouchListener l) {
4773        getListenerInfo().mOnTouchListener = l;
4774    }
4775
4776    /**
4777     * Register a callback to be invoked when a generic motion event is sent to this view.
4778     * @param l the generic motion listener to attach to this view
4779     */
4780    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4781        getListenerInfo().mOnGenericMotionListener = l;
4782    }
4783
4784    /**
4785     * Register a callback to be invoked when a hover event is sent to this view.
4786     * @param l the hover listener to attach to this view
4787     */
4788    public void setOnHoverListener(OnHoverListener l) {
4789        getListenerInfo().mOnHoverListener = l;
4790    }
4791
4792    /**
4793     * Register a drag event listener callback object for this View. The parameter is
4794     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4795     * View, the system calls the
4796     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4797     * @param l An implementation of {@link android.view.View.OnDragListener}.
4798     */
4799    public void setOnDragListener(OnDragListener l) {
4800        getListenerInfo().mOnDragListener = l;
4801    }
4802
4803    /**
4804     * Give this view focus. This will cause
4805     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4806     *
4807     * Note: this does not check whether this {@link View} should get focus, it just
4808     * gives it focus no matter what.  It should only be called internally by framework
4809     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4810     *
4811     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4812     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4813     *        focus moved when requestFocus() is called. It may not always
4814     *        apply, in which case use the default View.FOCUS_DOWN.
4815     * @param previouslyFocusedRect The rectangle of the view that had focus
4816     *        prior in this View's coordinate system.
4817     */
4818    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4819        if (DBG) {
4820            System.out.println(this + " requestFocus()");
4821        }
4822
4823        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4824            mPrivateFlags |= PFLAG_FOCUSED;
4825
4826            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4827
4828            if (mParent != null) {
4829                mParent.requestChildFocus(this, this);
4830            }
4831
4832            if (mAttachInfo != null) {
4833                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4834            }
4835
4836            onFocusChanged(true, direction, previouslyFocusedRect);
4837            manageFocusHotspot(true, oldFocus);
4838            refreshDrawableState();
4839        }
4840    }
4841
4842    /**
4843     * Forwards focus information to the background drawable, if necessary. When
4844     * the view is gaining focus, <code>v</code> is the previous focus holder.
4845     * When the view is losing focus, <code>v</code> is the next focus holder.
4846     *
4847     * @param focused whether this view is focused
4848     * @param v previous or the next focus holder, or null if none
4849     */
4850    private void manageFocusHotspot(boolean focused, View v) {
4851        final Rect r = new Rect();
4852        if (v != null && mAttachInfo != null) {
4853            v.getHotspotBounds(r);
4854            final int[] location = mAttachInfo.mTmpLocation;
4855            getLocationOnScreen(location);
4856            r.offset(-location[0], -location[1]);
4857        } else {
4858            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4859        }
4860
4861        final float x = r.exactCenterX();
4862        final float y = r.exactCenterY();
4863        drawableHotspotChanged(x, y);
4864    }
4865
4866    /**
4867     * Populates <code>outRect</code> with the hotspot bounds. By default,
4868     * the hotspot bounds are identical to the screen bounds.
4869     *
4870     * @param outRect rect to populate with hotspot bounds
4871     * @hide Only for internal use by views and widgets.
4872     */
4873    public void getHotspotBounds(Rect outRect) {
4874        final Drawable background = getBackground();
4875        if (background != null) {
4876            background.getHotspotBounds(outRect);
4877        } else {
4878            getBoundsOnScreen(outRect);
4879        }
4880    }
4881
4882    /**
4883     * Request that a rectangle of this view be visible on the screen,
4884     * scrolling if necessary just enough.
4885     *
4886     * <p>A View should call this if it maintains some notion of which part
4887     * of its content is interesting.  For example, a text editing view
4888     * should call this when its cursor moves.
4889     *
4890     * @param rectangle The rectangle.
4891     * @return Whether any parent scrolled.
4892     */
4893    public boolean requestRectangleOnScreen(Rect rectangle) {
4894        return requestRectangleOnScreen(rectangle, false);
4895    }
4896
4897    /**
4898     * Request that a rectangle of this view be visible on the screen,
4899     * scrolling if necessary just enough.
4900     *
4901     * <p>A View should call this if it maintains some notion of which part
4902     * of its content is interesting.  For example, a text editing view
4903     * should call this when its cursor moves.
4904     *
4905     * <p>When <code>immediate</code> is set to true, scrolling will not be
4906     * animated.
4907     *
4908     * @param rectangle The rectangle.
4909     * @param immediate True to forbid animated scrolling, false otherwise
4910     * @return Whether any parent scrolled.
4911     */
4912    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4913        if (mParent == null) {
4914            return false;
4915        }
4916
4917        View child = this;
4918
4919        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4920        position.set(rectangle);
4921
4922        ViewParent parent = mParent;
4923        boolean scrolled = false;
4924        while (parent != null) {
4925            rectangle.set((int) position.left, (int) position.top,
4926                    (int) position.right, (int) position.bottom);
4927
4928            scrolled |= parent.requestChildRectangleOnScreen(child,
4929                    rectangle, immediate);
4930
4931            if (!child.hasIdentityMatrix()) {
4932                child.getMatrix().mapRect(position);
4933            }
4934
4935            position.offset(child.mLeft, child.mTop);
4936
4937            if (!(parent instanceof View)) {
4938                break;
4939            }
4940
4941            View parentView = (View) parent;
4942
4943            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4944
4945            child = parentView;
4946            parent = child.getParent();
4947        }
4948
4949        return scrolled;
4950    }
4951
4952    /**
4953     * Called when this view wants to give up focus. If focus is cleared
4954     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4955     * <p>
4956     * <strong>Note:</strong> When a View clears focus the framework is trying
4957     * to give focus to the first focusable View from the top. Hence, if this
4958     * View is the first from the top that can take focus, then all callbacks
4959     * related to clearing focus will be invoked after wich the framework will
4960     * give focus to this view.
4961     * </p>
4962     */
4963    public void clearFocus() {
4964        if (DBG) {
4965            System.out.println(this + " clearFocus()");
4966        }
4967
4968        clearFocusInternal(null, true, true);
4969    }
4970
4971    /**
4972     * Clears focus from the view, optionally propagating the change up through
4973     * the parent hierarchy and requesting that the root view place new focus.
4974     *
4975     * @param propagate whether to propagate the change up through the parent
4976     *            hierarchy
4977     * @param refocus when propagate is true, specifies whether to request the
4978     *            root view place new focus
4979     */
4980    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4981        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4982            mPrivateFlags &= ~PFLAG_FOCUSED;
4983
4984            if (propagate && mParent != null) {
4985                mParent.clearChildFocus(this);
4986            }
4987
4988            onFocusChanged(false, 0, null);
4989
4990            manageFocusHotspot(false, focused);
4991            refreshDrawableState();
4992
4993            if (propagate && (!refocus || !rootViewRequestFocus())) {
4994                notifyGlobalFocusCleared(this);
4995            }
4996        }
4997    }
4998
4999    void notifyGlobalFocusCleared(View oldFocus) {
5000        if (oldFocus != null && mAttachInfo != null) {
5001            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5002        }
5003    }
5004
5005    boolean rootViewRequestFocus() {
5006        final View root = getRootView();
5007        return root != null && root.requestFocus();
5008    }
5009
5010    /**
5011     * Called internally by the view system when a new view is getting focus.
5012     * This is what clears the old focus.
5013     * <p>
5014     * <b>NOTE:</b> The parent view's focused child must be updated manually
5015     * after calling this method. Otherwise, the view hierarchy may be left in
5016     * an inconstent state.
5017     */
5018    void unFocus(View focused) {
5019        if (DBG) {
5020            System.out.println(this + " unFocus()");
5021        }
5022
5023        clearFocusInternal(focused, false, false);
5024    }
5025
5026    /**
5027     * Returns true if this view has focus iteself, or is the ancestor of the
5028     * view that has focus.
5029     *
5030     * @return True if this view has or contains focus, false otherwise.
5031     */
5032    @ViewDebug.ExportedProperty(category = "focus")
5033    public boolean hasFocus() {
5034        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5035    }
5036
5037    /**
5038     * Returns true if this view is focusable or if it contains a reachable View
5039     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5040     * is a View whose parents do not block descendants focus.
5041     *
5042     * Only {@link #VISIBLE} views are considered focusable.
5043     *
5044     * @return True if the view is focusable or if the view contains a focusable
5045     *         View, false otherwise.
5046     *
5047     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5048     * @see ViewGroup#getTouchscreenBlocksFocus()
5049     */
5050    public boolean hasFocusable() {
5051        if (!isFocusableInTouchMode()) {
5052            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5053                final ViewGroup g = (ViewGroup) p;
5054                if (g.shouldBlockFocusForTouchscreen()) {
5055                    return false;
5056                }
5057            }
5058        }
5059        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5060    }
5061
5062    /**
5063     * Called by the view system when the focus state of this view changes.
5064     * When the focus change event is caused by directional navigation, direction
5065     * and previouslyFocusedRect provide insight into where the focus is coming from.
5066     * When overriding, be sure to call up through to the super class so that
5067     * the standard focus handling will occur.
5068     *
5069     * @param gainFocus True if the View has focus; false otherwise.
5070     * @param direction The direction focus has moved when requestFocus()
5071     *                  is called to give this view focus. Values are
5072     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5073     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5074     *                  It may not always apply, in which case use the default.
5075     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5076     *        system, of the previously focused view.  If applicable, this will be
5077     *        passed in as finer grained information about where the focus is coming
5078     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5079     */
5080    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5081            @Nullable Rect previouslyFocusedRect) {
5082        if (gainFocus) {
5083            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5084        } else {
5085            notifyViewAccessibilityStateChangedIfNeeded(
5086                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5087        }
5088
5089        InputMethodManager imm = InputMethodManager.peekInstance();
5090        if (!gainFocus) {
5091            if (isPressed()) {
5092                setPressed(false);
5093            }
5094            if (imm != null && mAttachInfo != null
5095                    && mAttachInfo.mHasWindowFocus) {
5096                imm.focusOut(this);
5097            }
5098            onFocusLost();
5099        } else if (imm != null && mAttachInfo != null
5100                && mAttachInfo.mHasWindowFocus) {
5101            imm.focusIn(this);
5102        }
5103
5104        invalidate(true);
5105        ListenerInfo li = mListenerInfo;
5106        if (li != null && li.mOnFocusChangeListener != null) {
5107            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5108        }
5109
5110        if (mAttachInfo != null) {
5111            mAttachInfo.mKeyDispatchState.reset(this);
5112        }
5113    }
5114
5115    /**
5116     * Sends an accessibility event of the given type. If accessibility is
5117     * not enabled this method has no effect. The default implementation calls
5118     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5119     * to populate information about the event source (this View), then calls
5120     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5121     * populate the text content of the event source including its descendants,
5122     * and last calls
5123     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5124     * on its parent to resuest sending of the event to interested parties.
5125     * <p>
5126     * If an {@link AccessibilityDelegate} has been specified via calling
5127     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5128     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5129     * responsible for handling this call.
5130     * </p>
5131     *
5132     * @param eventType The type of the event to send, as defined by several types from
5133     * {@link android.view.accessibility.AccessibilityEvent}, such as
5134     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5135     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5136     *
5137     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5138     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5139     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5140     * @see AccessibilityDelegate
5141     */
5142    public void sendAccessibilityEvent(int eventType) {
5143        if (mAccessibilityDelegate != null) {
5144            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5145        } else {
5146            sendAccessibilityEventInternal(eventType);
5147        }
5148    }
5149
5150    /**
5151     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5152     * {@link AccessibilityEvent} to make an announcement which is related to some
5153     * sort of a context change for which none of the events representing UI transitions
5154     * is a good fit. For example, announcing a new page in a book. If accessibility
5155     * is not enabled this method does nothing.
5156     *
5157     * @param text The announcement text.
5158     */
5159    public void announceForAccessibility(CharSequence text) {
5160        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5161            AccessibilityEvent event = AccessibilityEvent.obtain(
5162                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5163            onInitializeAccessibilityEvent(event);
5164            event.getText().add(text);
5165            event.setContentDescription(null);
5166            mParent.requestSendAccessibilityEvent(this, event);
5167        }
5168    }
5169
5170    /**
5171     * @see #sendAccessibilityEvent(int)
5172     *
5173     * Note: Called from the default {@link AccessibilityDelegate}.
5174     */
5175    void sendAccessibilityEventInternal(int eventType) {
5176        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5177            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5178        }
5179    }
5180
5181    /**
5182     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5183     * takes as an argument an empty {@link AccessibilityEvent} and does not
5184     * perform a check whether accessibility is enabled.
5185     * <p>
5186     * If an {@link AccessibilityDelegate} has been specified via calling
5187     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5188     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5189     * is responsible for handling this call.
5190     * </p>
5191     *
5192     * @param event The event to send.
5193     *
5194     * @see #sendAccessibilityEvent(int)
5195     */
5196    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5197        if (mAccessibilityDelegate != null) {
5198            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5199        } else {
5200            sendAccessibilityEventUncheckedInternal(event);
5201        }
5202    }
5203
5204    /**
5205     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5206     *
5207     * Note: Called from the default {@link AccessibilityDelegate}.
5208     */
5209    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5210        if (!isShown()) {
5211            return;
5212        }
5213        onInitializeAccessibilityEvent(event);
5214        // Only a subset of accessibility events populates text content.
5215        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5216            dispatchPopulateAccessibilityEvent(event);
5217        }
5218        // In the beginning we called #isShown(), so we know that getParent() is not null.
5219        getParent().requestSendAccessibilityEvent(this, event);
5220    }
5221
5222    /**
5223     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5224     * to its children for adding their text content to the event. Note that the
5225     * event text is populated in a separate dispatch path since we add to the
5226     * event not only the text of the source but also the text of all its descendants.
5227     * A typical implementation will call
5228     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5229     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5230     * on each child. Override this method if custom population of the event text
5231     * content is required.
5232     * <p>
5233     * If an {@link AccessibilityDelegate} has been specified via calling
5234     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5235     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5236     * is responsible for handling this call.
5237     * </p>
5238     * <p>
5239     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5240     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5241     * </p>
5242     *
5243     * @param event The event.
5244     *
5245     * @return True if the event population was completed.
5246     */
5247    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5248        if (mAccessibilityDelegate != null) {
5249            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5250        } else {
5251            return dispatchPopulateAccessibilityEventInternal(event);
5252        }
5253    }
5254
5255    /**
5256     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5257     *
5258     * Note: Called from the default {@link AccessibilityDelegate}.
5259     */
5260    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5261        onPopulateAccessibilityEvent(event);
5262        return false;
5263    }
5264
5265    /**
5266     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5267     * giving a chance to this View to populate the accessibility event with its
5268     * text content. While this method is free to modify event
5269     * attributes other than text content, doing so should normally be performed in
5270     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5271     * <p>
5272     * Example: Adding formatted date string to an accessibility event in addition
5273     *          to the text added by the super implementation:
5274     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5275     *     super.onPopulateAccessibilityEvent(event);
5276     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5277     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5278     *         mCurrentDate.getTimeInMillis(), flags);
5279     *     event.getText().add(selectedDateUtterance);
5280     * }</pre>
5281     * <p>
5282     * If an {@link AccessibilityDelegate} has been specified via calling
5283     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5284     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5285     * is responsible for handling this call.
5286     * </p>
5287     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5288     * information to the event, in case the default implementation has basic information to add.
5289     * </p>
5290     *
5291     * @param event The accessibility event which to populate.
5292     *
5293     * @see #sendAccessibilityEvent(int)
5294     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5295     */
5296    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5297        if (mAccessibilityDelegate != null) {
5298            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5299        } else {
5300            onPopulateAccessibilityEventInternal(event);
5301        }
5302    }
5303
5304    /**
5305     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5306     *
5307     * Note: Called from the default {@link AccessibilityDelegate}.
5308     */
5309    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5310    }
5311
5312    /**
5313     * Initializes an {@link AccessibilityEvent} with information about
5314     * this View which is the event source. In other words, the source of
5315     * an accessibility event is the view whose state change triggered firing
5316     * the event.
5317     * <p>
5318     * Example: Setting the password property of an event in addition
5319     *          to properties set by the super implementation:
5320     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5321     *     super.onInitializeAccessibilityEvent(event);
5322     *     event.setPassword(true);
5323     * }</pre>
5324     * <p>
5325     * If an {@link AccessibilityDelegate} has been specified via calling
5326     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5327     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5328     * is responsible for handling this call.
5329     * </p>
5330     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5331     * information to the event, in case the default implementation has basic information to add.
5332     * </p>
5333     * @param event The event to initialize.
5334     *
5335     * @see #sendAccessibilityEvent(int)
5336     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5337     */
5338    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5339        if (mAccessibilityDelegate != null) {
5340            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5341        } else {
5342            onInitializeAccessibilityEventInternal(event);
5343        }
5344    }
5345
5346    /**
5347     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5348     *
5349     * Note: Called from the default {@link AccessibilityDelegate}.
5350     */
5351    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5352        event.setSource(this);
5353        event.setClassName(View.class.getName());
5354        event.setPackageName(getContext().getPackageName());
5355        event.setEnabled(isEnabled());
5356        event.setContentDescription(mContentDescription);
5357
5358        switch (event.getEventType()) {
5359            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5360                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5361                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5362                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5363                event.setItemCount(focusablesTempList.size());
5364                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5365                if (mAttachInfo != null) {
5366                    focusablesTempList.clear();
5367                }
5368            } break;
5369            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5370                CharSequence text = getIterableTextForAccessibility();
5371                if (text != null && text.length() > 0) {
5372                    event.setFromIndex(getAccessibilitySelectionStart());
5373                    event.setToIndex(getAccessibilitySelectionEnd());
5374                    event.setItemCount(text.length());
5375                }
5376            } break;
5377        }
5378    }
5379
5380    /**
5381     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5382     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5383     * This method is responsible for obtaining an accessibility node info from a
5384     * pool of reusable instances and calling
5385     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5386     * initialize the former.
5387     * <p>
5388     * Note: The client is responsible for recycling the obtained instance by calling
5389     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5390     * </p>
5391     *
5392     * @return A populated {@link AccessibilityNodeInfo}.
5393     *
5394     * @see AccessibilityNodeInfo
5395     */
5396    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5397        if (mAccessibilityDelegate != null) {
5398            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5399        } else {
5400            return createAccessibilityNodeInfoInternal();
5401        }
5402    }
5403
5404    /**
5405     * @see #createAccessibilityNodeInfo()
5406     */
5407    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5408        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5409        if (provider != null) {
5410            return provider.createAccessibilityNodeInfo(View.NO_ID);
5411        } else {
5412            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5413            onInitializeAccessibilityNodeInfo(info);
5414            return info;
5415        }
5416    }
5417
5418    /**
5419     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5420     * The base implementation sets:
5421     * <ul>
5422     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5423     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5424     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5425     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5426     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5427     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5428     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5429     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5430     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5431     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5432     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5433     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5434     * </ul>
5435     * <p>
5436     * Subclasses should override this method, call the super implementation,
5437     * and set additional attributes.
5438     * </p>
5439     * <p>
5440     * If an {@link AccessibilityDelegate} has been specified via calling
5441     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5442     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5443     * is responsible for handling this call.
5444     * </p>
5445     *
5446     * @param info The instance to initialize.
5447     */
5448    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5449        if (mAccessibilityDelegate != null) {
5450            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5451        } else {
5452            onInitializeAccessibilityNodeInfoInternal(info);
5453        }
5454    }
5455
5456    /**
5457     * Gets the location of this view in screen coordintates.
5458     *
5459     * @param outRect The output location
5460     * @hide
5461     */
5462    public void getBoundsOnScreen(Rect outRect) {
5463        if (mAttachInfo == null) {
5464            return;
5465        }
5466
5467        RectF position = mAttachInfo.mTmpTransformRect;
5468        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5469
5470        if (!hasIdentityMatrix()) {
5471            getMatrix().mapRect(position);
5472        }
5473
5474        position.offset(mLeft, mTop);
5475
5476        ViewParent parent = mParent;
5477        while (parent instanceof View) {
5478            View parentView = (View) parent;
5479
5480            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5481
5482            if (!parentView.hasIdentityMatrix()) {
5483                parentView.getMatrix().mapRect(position);
5484            }
5485
5486            position.offset(parentView.mLeft, parentView.mTop);
5487
5488            parent = parentView.mParent;
5489        }
5490
5491        if (parent instanceof ViewRootImpl) {
5492            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5493            position.offset(0, -viewRootImpl.mCurScrollY);
5494        }
5495
5496        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5497
5498        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5499                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5500    }
5501
5502    /**
5503     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5504     *
5505     * Note: Called from the default {@link AccessibilityDelegate}.
5506     */
5507    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5508        Rect bounds = mAttachInfo.mTmpInvalRect;
5509
5510        getDrawingRect(bounds);
5511        info.setBoundsInParent(bounds);
5512
5513        getBoundsOnScreen(bounds);
5514        info.setBoundsInScreen(bounds);
5515
5516        ViewParent parent = getParentForAccessibility();
5517        if (parent instanceof View) {
5518            info.setParent((View) parent);
5519        }
5520
5521        if (mID != View.NO_ID) {
5522            View rootView = getRootView();
5523            if (rootView == null) {
5524                rootView = this;
5525            }
5526            View label = rootView.findLabelForView(this, mID);
5527            if (label != null) {
5528                info.setLabeledBy(label);
5529            }
5530
5531            if ((mAttachInfo.mAccessibilityFetchFlags
5532                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5533                    && Resources.resourceHasPackage(mID)) {
5534                try {
5535                    String viewId = getResources().getResourceName(mID);
5536                    info.setViewIdResourceName(viewId);
5537                } catch (Resources.NotFoundException nfe) {
5538                    /* ignore */
5539                }
5540            }
5541        }
5542
5543        if (mLabelForId != View.NO_ID) {
5544            View rootView = getRootView();
5545            if (rootView == null) {
5546                rootView = this;
5547            }
5548            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5549            if (labeled != null) {
5550                info.setLabelFor(labeled);
5551            }
5552        }
5553
5554        info.setVisibleToUser(isVisibleToUser());
5555
5556        info.setPackageName(mContext.getPackageName());
5557        info.setClassName(View.class.getName());
5558        info.setContentDescription(getContentDescription());
5559
5560        info.setEnabled(isEnabled());
5561        info.setClickable(isClickable());
5562        info.setFocusable(isFocusable());
5563        info.setFocused(isFocused());
5564        info.setAccessibilityFocused(isAccessibilityFocused());
5565        info.setSelected(isSelected());
5566        info.setLongClickable(isLongClickable());
5567        info.setLiveRegion(getAccessibilityLiveRegion());
5568
5569        // TODO: These make sense only if we are in an AdapterView but all
5570        // views can be selected. Maybe from accessibility perspective
5571        // we should report as selectable view in an AdapterView.
5572        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5573        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5574
5575        if (isFocusable()) {
5576            if (isFocused()) {
5577                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5578            } else {
5579                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5580            }
5581        }
5582
5583        if (!isAccessibilityFocused()) {
5584            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5585        } else {
5586            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5587        }
5588
5589        if (isClickable() && isEnabled()) {
5590            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5591        }
5592
5593        if (isLongClickable() && isEnabled()) {
5594            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5595        }
5596
5597        CharSequence text = getIterableTextForAccessibility();
5598        if (text != null && text.length() > 0) {
5599            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5600
5601            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5602            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5603            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5604            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5605                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5606                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5607        }
5608    }
5609
5610    private View findLabelForView(View view, int labeledId) {
5611        if (mMatchLabelForPredicate == null) {
5612            mMatchLabelForPredicate = new MatchLabelForPredicate();
5613        }
5614        mMatchLabelForPredicate.mLabeledId = labeledId;
5615        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5616    }
5617
5618    /**
5619     * Computes whether this view is visible to the user. Such a view is
5620     * attached, visible, all its predecessors are visible, it is not clipped
5621     * entirely by its predecessors, and has an alpha greater than zero.
5622     *
5623     * @return Whether the view is visible on the screen.
5624     *
5625     * @hide
5626     */
5627    protected boolean isVisibleToUser() {
5628        return isVisibleToUser(null);
5629    }
5630
5631    /**
5632     * Computes whether the given portion of this view is visible to the user.
5633     * Such a view is attached, visible, all its predecessors are visible,
5634     * has an alpha greater than zero, and the specified portion is not
5635     * clipped entirely by its predecessors.
5636     *
5637     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5638     *                    <code>null</code>, and the entire view will be tested in this case.
5639     *                    When <code>true</code> is returned by the function, the actual visible
5640     *                    region will be stored in this parameter; that is, if boundInView is fully
5641     *                    contained within the view, no modification will be made, otherwise regions
5642     *                    outside of the visible area of the view will be clipped.
5643     *
5644     * @return Whether the specified portion of the view is visible on the screen.
5645     *
5646     * @hide
5647     */
5648    protected boolean isVisibleToUser(Rect boundInView) {
5649        if (mAttachInfo != null) {
5650            // Attached to invisible window means this view is not visible.
5651            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5652                return false;
5653            }
5654            // An invisible predecessor or one with alpha zero means
5655            // that this view is not visible to the user.
5656            Object current = this;
5657            while (current instanceof View) {
5658                View view = (View) current;
5659                // We have attach info so this view is attached and there is no
5660                // need to check whether we reach to ViewRootImpl on the way up.
5661                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5662                        view.getVisibility() != VISIBLE) {
5663                    return false;
5664                }
5665                current = view.mParent;
5666            }
5667            // Check if the view is entirely covered by its predecessors.
5668            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5669            Point offset = mAttachInfo.mPoint;
5670            if (!getGlobalVisibleRect(visibleRect, offset)) {
5671                return false;
5672            }
5673            // Check if the visible portion intersects the rectangle of interest.
5674            if (boundInView != null) {
5675                visibleRect.offset(-offset.x, -offset.y);
5676                return boundInView.intersect(visibleRect);
5677            }
5678            return true;
5679        }
5680        return false;
5681    }
5682
5683    /**
5684     * Returns the delegate for implementing accessibility support via
5685     * composition. For more details see {@link AccessibilityDelegate}.
5686     *
5687     * @return The delegate, or null if none set.
5688     *
5689     * @hide
5690     */
5691    public AccessibilityDelegate getAccessibilityDelegate() {
5692        return mAccessibilityDelegate;
5693    }
5694
5695    /**
5696     * Sets a delegate for implementing accessibility support via composition as
5697     * opposed to inheritance. The delegate's primary use is for implementing
5698     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5699     *
5700     * @param delegate The delegate instance.
5701     *
5702     * @see AccessibilityDelegate
5703     */
5704    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5705        mAccessibilityDelegate = delegate;
5706    }
5707
5708    /**
5709     * Gets the provider for managing a virtual view hierarchy rooted at this View
5710     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5711     * that explore the window content.
5712     * <p>
5713     * If this method returns an instance, this instance is responsible for managing
5714     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5715     * View including the one representing the View itself. Similarly the returned
5716     * instance is responsible for performing accessibility actions on any virtual
5717     * view or the root view itself.
5718     * </p>
5719     * <p>
5720     * If an {@link AccessibilityDelegate} has been specified via calling
5721     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5722     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5723     * is responsible for handling this call.
5724     * </p>
5725     *
5726     * @return The provider.
5727     *
5728     * @see AccessibilityNodeProvider
5729     */
5730    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5731        if (mAccessibilityDelegate != null) {
5732            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5733        } else {
5734            return null;
5735        }
5736    }
5737
5738    /**
5739     * Gets the unique identifier of this view on the screen for accessibility purposes.
5740     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5741     *
5742     * @return The view accessibility id.
5743     *
5744     * @hide
5745     */
5746    public int getAccessibilityViewId() {
5747        if (mAccessibilityViewId == NO_ID) {
5748            mAccessibilityViewId = sNextAccessibilityViewId++;
5749        }
5750        return mAccessibilityViewId;
5751    }
5752
5753    /**
5754     * Gets the unique identifier of the window in which this View reseides.
5755     *
5756     * @return The window accessibility id.
5757     *
5758     * @hide
5759     */
5760    public int getAccessibilityWindowId() {
5761        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5762                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5763    }
5764
5765    /**
5766     * Gets the {@link View} description. It briefly describes the view and is
5767     * primarily used for accessibility support. Set this property to enable
5768     * better accessibility support for your application. This is especially
5769     * true for views that do not have textual representation (For example,
5770     * ImageButton).
5771     *
5772     * @return The content description.
5773     *
5774     * @attr ref android.R.styleable#View_contentDescription
5775     */
5776    @ViewDebug.ExportedProperty(category = "accessibility")
5777    public CharSequence getContentDescription() {
5778        return mContentDescription;
5779    }
5780
5781    /**
5782     * Sets the {@link View} description. It briefly describes the view and is
5783     * primarily used for accessibility support. Set this property to enable
5784     * better accessibility support for your application. This is especially
5785     * true for views that do not have textual representation (For example,
5786     * ImageButton).
5787     *
5788     * @param contentDescription The content description.
5789     *
5790     * @attr ref android.R.styleable#View_contentDescription
5791     */
5792    @RemotableViewMethod
5793    public void setContentDescription(CharSequence contentDescription) {
5794        if (mContentDescription == null) {
5795            if (contentDescription == null) {
5796                return;
5797            }
5798        } else if (mContentDescription.equals(contentDescription)) {
5799            return;
5800        }
5801        mContentDescription = contentDescription;
5802        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5803        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5804            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5805            notifySubtreeAccessibilityStateChangedIfNeeded();
5806        } else {
5807            notifyViewAccessibilityStateChangedIfNeeded(
5808                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5809        }
5810    }
5811
5812    /**
5813     * Gets the id of a view for which this view serves as a label for
5814     * accessibility purposes.
5815     *
5816     * @return The labeled view id.
5817     */
5818    @ViewDebug.ExportedProperty(category = "accessibility")
5819    public int getLabelFor() {
5820        return mLabelForId;
5821    }
5822
5823    /**
5824     * Sets the id of a view for which this view serves as a label for
5825     * accessibility purposes.
5826     *
5827     * @param id The labeled view id.
5828     */
5829    @RemotableViewMethod
5830    public void setLabelFor(int id) {
5831        mLabelForId = id;
5832        if (mLabelForId != View.NO_ID
5833                && mID == View.NO_ID) {
5834            mID = generateViewId();
5835        }
5836    }
5837
5838    /**
5839     * Invoked whenever this view loses focus, either by losing window focus or by losing
5840     * focus within its window. This method can be used to clear any state tied to the
5841     * focus. For instance, if a button is held pressed with the trackball and the window
5842     * loses focus, this method can be used to cancel the press.
5843     *
5844     * Subclasses of View overriding this method should always call super.onFocusLost().
5845     *
5846     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5847     * @see #onWindowFocusChanged(boolean)
5848     *
5849     * @hide pending API council approval
5850     */
5851    protected void onFocusLost() {
5852        resetPressedState();
5853    }
5854
5855    private void resetPressedState() {
5856        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5857            return;
5858        }
5859
5860        if (isPressed()) {
5861            setPressed(false);
5862
5863            if (!mHasPerformedLongPress) {
5864                removeLongPressCallback();
5865            }
5866        }
5867    }
5868
5869    /**
5870     * Returns true if this view has focus
5871     *
5872     * @return True if this view has focus, false otherwise.
5873     */
5874    @ViewDebug.ExportedProperty(category = "focus")
5875    public boolean isFocused() {
5876        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5877    }
5878
5879    /**
5880     * Find the view in the hierarchy rooted at this view that currently has
5881     * focus.
5882     *
5883     * @return The view that currently has focus, or null if no focused view can
5884     *         be found.
5885     */
5886    public View findFocus() {
5887        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5888    }
5889
5890    /**
5891     * Indicates whether this view is one of the set of scrollable containers in
5892     * its window.
5893     *
5894     * @return whether this view is one of the set of scrollable containers in
5895     * its window
5896     *
5897     * @attr ref android.R.styleable#View_isScrollContainer
5898     */
5899    public boolean isScrollContainer() {
5900        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5901    }
5902
5903    /**
5904     * Change whether this view is one of the set of scrollable containers in
5905     * its window.  This will be used to determine whether the window can
5906     * resize or must pan when a soft input area is open -- scrollable
5907     * containers allow the window to use resize mode since the container
5908     * will appropriately shrink.
5909     *
5910     * @attr ref android.R.styleable#View_isScrollContainer
5911     */
5912    public void setScrollContainer(boolean isScrollContainer) {
5913        if (isScrollContainer) {
5914            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5915                mAttachInfo.mScrollContainers.add(this);
5916                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5917            }
5918            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5919        } else {
5920            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5921                mAttachInfo.mScrollContainers.remove(this);
5922            }
5923            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5924        }
5925    }
5926
5927    /**
5928     * Returns the quality of the drawing cache.
5929     *
5930     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5931     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5932     *
5933     * @see #setDrawingCacheQuality(int)
5934     * @see #setDrawingCacheEnabled(boolean)
5935     * @see #isDrawingCacheEnabled()
5936     *
5937     * @attr ref android.R.styleable#View_drawingCacheQuality
5938     */
5939    @DrawingCacheQuality
5940    public int getDrawingCacheQuality() {
5941        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5942    }
5943
5944    /**
5945     * Set the drawing cache quality of this view. This value is used only when the
5946     * drawing cache is enabled
5947     *
5948     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5949     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5950     *
5951     * @see #getDrawingCacheQuality()
5952     * @see #setDrawingCacheEnabled(boolean)
5953     * @see #isDrawingCacheEnabled()
5954     *
5955     * @attr ref android.R.styleable#View_drawingCacheQuality
5956     */
5957    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5958        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5959    }
5960
5961    /**
5962     * Returns whether the screen should remain on, corresponding to the current
5963     * value of {@link #KEEP_SCREEN_ON}.
5964     *
5965     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5966     *
5967     * @see #setKeepScreenOn(boolean)
5968     *
5969     * @attr ref android.R.styleable#View_keepScreenOn
5970     */
5971    public boolean getKeepScreenOn() {
5972        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5973    }
5974
5975    /**
5976     * Controls whether the screen should remain on, modifying the
5977     * value of {@link #KEEP_SCREEN_ON}.
5978     *
5979     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5980     *
5981     * @see #getKeepScreenOn()
5982     *
5983     * @attr ref android.R.styleable#View_keepScreenOn
5984     */
5985    public void setKeepScreenOn(boolean keepScreenOn) {
5986        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5987    }
5988
5989    /**
5990     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5991     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5992     *
5993     * @attr ref android.R.styleable#View_nextFocusLeft
5994     */
5995    public int getNextFocusLeftId() {
5996        return mNextFocusLeftId;
5997    }
5998
5999    /**
6000     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6001     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6002     * decide automatically.
6003     *
6004     * @attr ref android.R.styleable#View_nextFocusLeft
6005     */
6006    public void setNextFocusLeftId(int nextFocusLeftId) {
6007        mNextFocusLeftId = nextFocusLeftId;
6008    }
6009
6010    /**
6011     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6012     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6013     *
6014     * @attr ref android.R.styleable#View_nextFocusRight
6015     */
6016    public int getNextFocusRightId() {
6017        return mNextFocusRightId;
6018    }
6019
6020    /**
6021     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6022     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6023     * decide automatically.
6024     *
6025     * @attr ref android.R.styleable#View_nextFocusRight
6026     */
6027    public void setNextFocusRightId(int nextFocusRightId) {
6028        mNextFocusRightId = nextFocusRightId;
6029    }
6030
6031    /**
6032     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6033     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6034     *
6035     * @attr ref android.R.styleable#View_nextFocusUp
6036     */
6037    public int getNextFocusUpId() {
6038        return mNextFocusUpId;
6039    }
6040
6041    /**
6042     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6043     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6044     * decide automatically.
6045     *
6046     * @attr ref android.R.styleable#View_nextFocusUp
6047     */
6048    public void setNextFocusUpId(int nextFocusUpId) {
6049        mNextFocusUpId = nextFocusUpId;
6050    }
6051
6052    /**
6053     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6054     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6055     *
6056     * @attr ref android.R.styleable#View_nextFocusDown
6057     */
6058    public int getNextFocusDownId() {
6059        return mNextFocusDownId;
6060    }
6061
6062    /**
6063     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6064     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6065     * decide automatically.
6066     *
6067     * @attr ref android.R.styleable#View_nextFocusDown
6068     */
6069    public void setNextFocusDownId(int nextFocusDownId) {
6070        mNextFocusDownId = nextFocusDownId;
6071    }
6072
6073    /**
6074     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6075     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6076     *
6077     * @attr ref android.R.styleable#View_nextFocusForward
6078     */
6079    public int getNextFocusForwardId() {
6080        return mNextFocusForwardId;
6081    }
6082
6083    /**
6084     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6085     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6086     * decide automatically.
6087     *
6088     * @attr ref android.R.styleable#View_nextFocusForward
6089     */
6090    public void setNextFocusForwardId(int nextFocusForwardId) {
6091        mNextFocusForwardId = nextFocusForwardId;
6092    }
6093
6094    /**
6095     * Returns the visibility of this view and all of its ancestors
6096     *
6097     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6098     */
6099    public boolean isShown() {
6100        View current = this;
6101        //noinspection ConstantConditions
6102        do {
6103            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6104                return false;
6105            }
6106            ViewParent parent = current.mParent;
6107            if (parent == null) {
6108                return false; // We are not attached to the view root
6109            }
6110            if (!(parent instanceof View)) {
6111                return true;
6112            }
6113            current = (View) parent;
6114        } while (current != null);
6115
6116        return false;
6117    }
6118
6119    /**
6120     * Called by the view hierarchy when the content insets for a window have
6121     * changed, to allow it to adjust its content to fit within those windows.
6122     * The content insets tell you the space that the status bar, input method,
6123     * and other system windows infringe on the application's window.
6124     *
6125     * <p>You do not normally need to deal with this function, since the default
6126     * window decoration given to applications takes care of applying it to the
6127     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6128     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6129     * and your content can be placed under those system elements.  You can then
6130     * use this method within your view hierarchy if you have parts of your UI
6131     * which you would like to ensure are not being covered.
6132     *
6133     * <p>The default implementation of this method simply applies the content
6134     * insets to the view's padding, consuming that content (modifying the
6135     * insets to be 0), and returning true.  This behavior is off by default, but can
6136     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6137     *
6138     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6139     * insets object is propagated down the hierarchy, so any changes made to it will
6140     * be seen by all following views (including potentially ones above in
6141     * the hierarchy since this is a depth-first traversal).  The first view
6142     * that returns true will abort the entire traversal.
6143     *
6144     * <p>The default implementation works well for a situation where it is
6145     * used with a container that covers the entire window, allowing it to
6146     * apply the appropriate insets to its content on all edges.  If you need
6147     * a more complicated layout (such as two different views fitting system
6148     * windows, one on the top of the window, and one on the bottom),
6149     * you can override the method and handle the insets however you would like.
6150     * Note that the insets provided by the framework are always relative to the
6151     * far edges of the window, not accounting for the location of the called view
6152     * within that window.  (In fact when this method is called you do not yet know
6153     * where the layout will place the view, as it is done before layout happens.)
6154     *
6155     * <p>Note: unlike many View methods, there is no dispatch phase to this
6156     * call.  If you are overriding it in a ViewGroup and want to allow the
6157     * call to continue to your children, you must be sure to call the super
6158     * implementation.
6159     *
6160     * <p>Here is a sample layout that makes use of fitting system windows
6161     * to have controls for a video view placed inside of the window decorations
6162     * that it hides and shows.  This can be used with code like the second
6163     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6164     *
6165     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6166     *
6167     * @param insets Current content insets of the window.  Prior to
6168     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6169     * the insets or else you and Android will be unhappy.
6170     *
6171     * @return {@code true} if this view applied the insets and it should not
6172     * continue propagating further down the hierarchy, {@code false} otherwise.
6173     * @see #getFitsSystemWindows()
6174     * @see #setFitsSystemWindows(boolean)
6175     * @see #setSystemUiVisibility(int)
6176     *
6177     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6178     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6179     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6180     * to implement handling their own insets.
6181     */
6182    protected boolean fitSystemWindows(Rect insets) {
6183        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6184            if (insets == null) {
6185                // Null insets by definition have already been consumed.
6186                // This call cannot apply insets since there are none to apply,
6187                // so return false.
6188                return false;
6189            }
6190            // If we're not in the process of dispatching the newer apply insets call,
6191            // that means we're not in the compatibility path. Dispatch into the newer
6192            // apply insets path and take things from there.
6193            try {
6194                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6195                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6196            } finally {
6197                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6198            }
6199        } else {
6200            // We're being called from the newer apply insets path.
6201            // Perform the standard fallback behavior.
6202            return fitSystemWindowsInt(insets);
6203        }
6204    }
6205
6206    private boolean fitSystemWindowsInt(Rect insets) {
6207        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6208            mUserPaddingStart = UNDEFINED_PADDING;
6209            mUserPaddingEnd = UNDEFINED_PADDING;
6210            Rect localInsets = sThreadLocal.get();
6211            if (localInsets == null) {
6212                localInsets = new Rect();
6213                sThreadLocal.set(localInsets);
6214            }
6215            boolean res = computeFitSystemWindows(insets, localInsets);
6216            mUserPaddingLeftInitial = localInsets.left;
6217            mUserPaddingRightInitial = localInsets.right;
6218            internalSetPadding(localInsets.left, localInsets.top,
6219                    localInsets.right, localInsets.bottom);
6220            return res;
6221        }
6222        return false;
6223    }
6224
6225    /**
6226     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6227     *
6228     * <p>This method should be overridden by views that wish to apply a policy different from or
6229     * in addition to the default behavior. Clients that wish to force a view subtree
6230     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6231     *
6232     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6233     * it will be called during dispatch instead of this method. The listener may optionally
6234     * call this method from its own implementation if it wishes to apply the view's default
6235     * insets policy in addition to its own.</p>
6236     *
6237     * <p>Implementations of this method should either return the insets parameter unchanged
6238     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6239     * that this view applied itself. This allows new inset types added in future platform
6240     * versions to pass through existing implementations unchanged without being erroneously
6241     * consumed.</p>
6242     *
6243     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6244     * property is set then the view will consume the system window insets and apply them
6245     * as padding for the view.</p>
6246     *
6247     * @param insets Insets to apply
6248     * @return The supplied insets with any applied insets consumed
6249     */
6250    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6251        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6252            // We weren't called from within a direct call to fitSystemWindows,
6253            // call into it as a fallback in case we're in a class that overrides it
6254            // and has logic to perform.
6255            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6256                return insets.consumeSystemWindowInsets();
6257            }
6258        } else {
6259            // We were called from within a direct call to fitSystemWindows.
6260            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6261                return insets.consumeSystemWindowInsets();
6262            }
6263        }
6264        return insets;
6265    }
6266
6267    /**
6268     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6269     * window insets to this view. The listener's
6270     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6271     * method will be called instead of the view's
6272     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6273     *
6274     * @param listener Listener to set
6275     *
6276     * @see #onApplyWindowInsets(WindowInsets)
6277     */
6278    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6279        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6280    }
6281
6282    /**
6283     * Request to apply the given window insets to this view or another view in its subtree.
6284     *
6285     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6286     * obscured by window decorations or overlays. This can include the status and navigation bars,
6287     * action bars, input methods and more. New inset categories may be added in the future.
6288     * The method returns the insets provided minus any that were applied by this view or its
6289     * children.</p>
6290     *
6291     * <p>Clients wishing to provide custom behavior should override the
6292     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6293     * {@link OnApplyWindowInsetsListener} via the
6294     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6295     * method.</p>
6296     *
6297     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6298     * </p>
6299     *
6300     * @param insets Insets to apply
6301     * @return The provided insets minus the insets that were consumed
6302     */
6303    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6304        try {
6305            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6306            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6307                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6308            } else {
6309                return onApplyWindowInsets(insets);
6310            }
6311        } finally {
6312            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6313        }
6314    }
6315
6316    /**
6317     * @hide Compute the insets that should be consumed by this view and the ones
6318     * that should propagate to those under it.
6319     */
6320    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6321        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6322                || mAttachInfo == null
6323                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6324                        && !mAttachInfo.mOverscanRequested)) {
6325            outLocalInsets.set(inoutInsets);
6326            inoutInsets.set(0, 0, 0, 0);
6327            return true;
6328        } else {
6329            // The application wants to take care of fitting system window for
6330            // the content...  however we still need to take care of any overscan here.
6331            final Rect overscan = mAttachInfo.mOverscanInsets;
6332            outLocalInsets.set(overscan);
6333            inoutInsets.left -= overscan.left;
6334            inoutInsets.top -= overscan.top;
6335            inoutInsets.right -= overscan.right;
6336            inoutInsets.bottom -= overscan.bottom;
6337            return false;
6338        }
6339    }
6340
6341    /**
6342     * Sets whether or not this view should account for system screen decorations
6343     * such as the status bar and inset its content; that is, controlling whether
6344     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6345     * executed.  See that method for more details.
6346     *
6347     * <p>Note that if you are providing your own implementation of
6348     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6349     * flag to true -- your implementation will be overriding the default
6350     * implementation that checks this flag.
6351     *
6352     * @param fitSystemWindows If true, then the default implementation of
6353     * {@link #fitSystemWindows(Rect)} will be executed.
6354     *
6355     * @attr ref android.R.styleable#View_fitsSystemWindows
6356     * @see #getFitsSystemWindows()
6357     * @see #fitSystemWindows(Rect)
6358     * @see #setSystemUiVisibility(int)
6359     */
6360    public void setFitsSystemWindows(boolean fitSystemWindows) {
6361        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6362    }
6363
6364    /**
6365     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6366     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6367     * will be executed.
6368     *
6369     * @return {@code true} if the default implementation of
6370     * {@link #fitSystemWindows(Rect)} will be executed.
6371     *
6372     * @attr ref android.R.styleable#View_fitsSystemWindows
6373     * @see #setFitsSystemWindows(boolean)
6374     * @see #fitSystemWindows(Rect)
6375     * @see #setSystemUiVisibility(int)
6376     */
6377    public boolean getFitsSystemWindows() {
6378        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6379    }
6380
6381    /** @hide */
6382    public boolean fitsSystemWindows() {
6383        return getFitsSystemWindows();
6384    }
6385
6386    /**
6387     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6388     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6389     */
6390    public void requestFitSystemWindows() {
6391        if (mParent != null) {
6392            mParent.requestFitSystemWindows();
6393        }
6394    }
6395
6396    /**
6397     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6398     */
6399    public void requestApplyInsets() {
6400        requestFitSystemWindows();
6401    }
6402
6403    /**
6404     * For use by PhoneWindow to make its own system window fitting optional.
6405     * @hide
6406     */
6407    public void makeOptionalFitsSystemWindows() {
6408        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6409    }
6410
6411    /**
6412     * Returns the visibility status for this view.
6413     *
6414     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6415     * @attr ref android.R.styleable#View_visibility
6416     */
6417    @ViewDebug.ExportedProperty(mapping = {
6418        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6419        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6420        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6421    })
6422    @Visibility
6423    public int getVisibility() {
6424        return mViewFlags & VISIBILITY_MASK;
6425    }
6426
6427    /**
6428     * Set the enabled state of this view.
6429     *
6430     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6431     * @attr ref android.R.styleable#View_visibility
6432     */
6433    @RemotableViewMethod
6434    public void setVisibility(@Visibility int visibility) {
6435        setFlags(visibility, VISIBILITY_MASK);
6436        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6437    }
6438
6439    /**
6440     * Returns the enabled status for this view. The interpretation of the
6441     * enabled state varies by subclass.
6442     *
6443     * @return True if this view is enabled, false otherwise.
6444     */
6445    @ViewDebug.ExportedProperty
6446    public boolean isEnabled() {
6447        return (mViewFlags & ENABLED_MASK) == ENABLED;
6448    }
6449
6450    /**
6451     * Set the enabled state of this view. The interpretation of the enabled
6452     * state varies by subclass.
6453     *
6454     * @param enabled True if this view is enabled, false otherwise.
6455     */
6456    @RemotableViewMethod
6457    public void setEnabled(boolean enabled) {
6458        if (enabled == isEnabled()) return;
6459
6460        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6461
6462        /*
6463         * The View most likely has to change its appearance, so refresh
6464         * the drawable state.
6465         */
6466        refreshDrawableState();
6467
6468        // Invalidate too, since the default behavior for views is to be
6469        // be drawn at 50% alpha rather than to change the drawable.
6470        invalidate(true);
6471
6472        if (!enabled) {
6473            cancelPendingInputEvents();
6474        }
6475    }
6476
6477    /**
6478     * Set whether this view can receive the focus.
6479     *
6480     * Setting this to false will also ensure that this view is not focusable
6481     * in touch mode.
6482     *
6483     * @param focusable If true, this view can receive the focus.
6484     *
6485     * @see #setFocusableInTouchMode(boolean)
6486     * @attr ref android.R.styleable#View_focusable
6487     */
6488    public void setFocusable(boolean focusable) {
6489        if (!focusable) {
6490            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6491        }
6492        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6493    }
6494
6495    /**
6496     * Set whether this view can receive focus while in touch mode.
6497     *
6498     * Setting this to true will also ensure that this view is focusable.
6499     *
6500     * @param focusableInTouchMode If true, this view can receive the focus while
6501     *   in touch mode.
6502     *
6503     * @see #setFocusable(boolean)
6504     * @attr ref android.R.styleable#View_focusableInTouchMode
6505     */
6506    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6507        // Focusable in touch mode should always be set before the focusable flag
6508        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6509        // which, in touch mode, will not successfully request focus on this view
6510        // because the focusable in touch mode flag is not set
6511        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6512        if (focusableInTouchMode) {
6513            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6514        }
6515    }
6516
6517    /**
6518     * Set whether this view should have sound effects enabled for events such as
6519     * clicking and touching.
6520     *
6521     * <p>You may wish to disable sound effects for a view if you already play sounds,
6522     * for instance, a dial key that plays dtmf tones.
6523     *
6524     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6525     * @see #isSoundEffectsEnabled()
6526     * @see #playSoundEffect(int)
6527     * @attr ref android.R.styleable#View_soundEffectsEnabled
6528     */
6529    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6530        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6531    }
6532
6533    /**
6534     * @return whether this view should have sound effects enabled for events such as
6535     *     clicking and touching.
6536     *
6537     * @see #setSoundEffectsEnabled(boolean)
6538     * @see #playSoundEffect(int)
6539     * @attr ref android.R.styleable#View_soundEffectsEnabled
6540     */
6541    @ViewDebug.ExportedProperty
6542    public boolean isSoundEffectsEnabled() {
6543        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6544    }
6545
6546    /**
6547     * Set whether this view should have haptic feedback for events such as
6548     * long presses.
6549     *
6550     * <p>You may wish to disable haptic feedback if your view already controls
6551     * its own haptic feedback.
6552     *
6553     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6554     * @see #isHapticFeedbackEnabled()
6555     * @see #performHapticFeedback(int)
6556     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6557     */
6558    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6559        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6560    }
6561
6562    /**
6563     * @return whether this view should have haptic feedback enabled for events
6564     * long presses.
6565     *
6566     * @see #setHapticFeedbackEnabled(boolean)
6567     * @see #performHapticFeedback(int)
6568     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6569     */
6570    @ViewDebug.ExportedProperty
6571    public boolean isHapticFeedbackEnabled() {
6572        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6573    }
6574
6575    /**
6576     * Returns the layout direction for this view.
6577     *
6578     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6579     *   {@link #LAYOUT_DIRECTION_RTL},
6580     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6581     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6582     *
6583     * @attr ref android.R.styleable#View_layoutDirection
6584     *
6585     * @hide
6586     */
6587    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6588        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6589        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6590        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6591        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6592    })
6593    @LayoutDir
6594    public int getRawLayoutDirection() {
6595        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6596    }
6597
6598    /**
6599     * Set the layout direction for this view. This will propagate a reset of layout direction
6600     * resolution to the view's children and resolve layout direction for this view.
6601     *
6602     * @param layoutDirection the layout direction to set. Should be one of:
6603     *
6604     * {@link #LAYOUT_DIRECTION_LTR},
6605     * {@link #LAYOUT_DIRECTION_RTL},
6606     * {@link #LAYOUT_DIRECTION_INHERIT},
6607     * {@link #LAYOUT_DIRECTION_LOCALE}.
6608     *
6609     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6610     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6611     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6612     *
6613     * @attr ref android.R.styleable#View_layoutDirection
6614     */
6615    @RemotableViewMethod
6616    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6617        if (getRawLayoutDirection() != layoutDirection) {
6618            // Reset the current layout direction and the resolved one
6619            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6620            resetRtlProperties();
6621            // Set the new layout direction (filtered)
6622            mPrivateFlags2 |=
6623                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6624            // We need to resolve all RTL properties as they all depend on layout direction
6625            resolveRtlPropertiesIfNeeded();
6626            requestLayout();
6627            invalidate(true);
6628        }
6629    }
6630
6631    /**
6632     * Returns the resolved layout direction for this view.
6633     *
6634     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6635     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6636     *
6637     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6638     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6639     *
6640     * @attr ref android.R.styleable#View_layoutDirection
6641     */
6642    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6643        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6644        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6645    })
6646    @ResolvedLayoutDir
6647    public int getLayoutDirection() {
6648        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6649        if (targetSdkVersion < JELLY_BEAN_MR1) {
6650            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6651            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6652        }
6653        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6654                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6655    }
6656
6657    /**
6658     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6659     * layout attribute and/or the inherited value from the parent
6660     *
6661     * @return true if the layout is right-to-left.
6662     *
6663     * @hide
6664     */
6665    @ViewDebug.ExportedProperty(category = "layout")
6666    public boolean isLayoutRtl() {
6667        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6668    }
6669
6670    /**
6671     * Indicates whether the view is currently tracking transient state that the
6672     * app should not need to concern itself with saving and restoring, but that
6673     * the framework should take special note to preserve when possible.
6674     *
6675     * <p>A view with transient state cannot be trivially rebound from an external
6676     * data source, such as an adapter binding item views in a list. This may be
6677     * because the view is performing an animation, tracking user selection
6678     * of content, or similar.</p>
6679     *
6680     * @return true if the view has transient state
6681     */
6682    @ViewDebug.ExportedProperty(category = "layout")
6683    public boolean hasTransientState() {
6684        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6685    }
6686
6687    /**
6688     * Set whether this view is currently tracking transient state that the
6689     * framework should attempt to preserve when possible. This flag is reference counted,
6690     * so every call to setHasTransientState(true) should be paired with a later call
6691     * to setHasTransientState(false).
6692     *
6693     * <p>A view with transient state cannot be trivially rebound from an external
6694     * data source, such as an adapter binding item views in a list. This may be
6695     * because the view is performing an animation, tracking user selection
6696     * of content, or similar.</p>
6697     *
6698     * @param hasTransientState true if this view has transient state
6699     */
6700    public void setHasTransientState(boolean hasTransientState) {
6701        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6702                mTransientStateCount - 1;
6703        if (mTransientStateCount < 0) {
6704            mTransientStateCount = 0;
6705            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6706                    "unmatched pair of setHasTransientState calls");
6707        } else if ((hasTransientState && mTransientStateCount == 1) ||
6708                (!hasTransientState && mTransientStateCount == 0)) {
6709            // update flag if we've just incremented up from 0 or decremented down to 0
6710            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6711                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6712            if (mParent != null) {
6713                try {
6714                    mParent.childHasTransientStateChanged(this, hasTransientState);
6715                } catch (AbstractMethodError e) {
6716                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6717                            " does not fully implement ViewParent", e);
6718                }
6719            }
6720        }
6721    }
6722
6723    /**
6724     * Returns true if this view is currently attached to a window.
6725     */
6726    public boolean isAttachedToWindow() {
6727        return mAttachInfo != null;
6728    }
6729
6730    /**
6731     * Returns true if this view has been through at least one layout since it
6732     * was last attached to or detached from a window.
6733     */
6734    public boolean isLaidOut() {
6735        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6736    }
6737
6738    /**
6739     * If this view doesn't do any drawing on its own, set this flag to
6740     * allow further optimizations. By default, this flag is not set on
6741     * View, but could be set on some View subclasses such as ViewGroup.
6742     *
6743     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6744     * you should clear this flag.
6745     *
6746     * @param willNotDraw whether or not this View draw on its own
6747     */
6748    public void setWillNotDraw(boolean willNotDraw) {
6749        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6750    }
6751
6752    /**
6753     * Returns whether or not this View draws on its own.
6754     *
6755     * @return true if this view has nothing to draw, false otherwise
6756     */
6757    @ViewDebug.ExportedProperty(category = "drawing")
6758    public boolean willNotDraw() {
6759        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6760    }
6761
6762    /**
6763     * When a View's drawing cache is enabled, drawing is redirected to an
6764     * offscreen bitmap. Some views, like an ImageView, must be able to
6765     * bypass this mechanism if they already draw a single bitmap, to avoid
6766     * unnecessary usage of the memory.
6767     *
6768     * @param willNotCacheDrawing true if this view does not cache its
6769     *        drawing, false otherwise
6770     */
6771    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6772        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6773    }
6774
6775    /**
6776     * Returns whether or not this View can cache its drawing or not.
6777     *
6778     * @return true if this view does not cache its drawing, false otherwise
6779     */
6780    @ViewDebug.ExportedProperty(category = "drawing")
6781    public boolean willNotCacheDrawing() {
6782        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6783    }
6784
6785    /**
6786     * Indicates whether this view reacts to click events or not.
6787     *
6788     * @return true if the view is clickable, false otherwise
6789     *
6790     * @see #setClickable(boolean)
6791     * @attr ref android.R.styleable#View_clickable
6792     */
6793    @ViewDebug.ExportedProperty
6794    public boolean isClickable() {
6795        return (mViewFlags & CLICKABLE) == CLICKABLE;
6796    }
6797
6798    /**
6799     * Enables or disables click events for this view. When a view
6800     * is clickable it will change its state to "pressed" on every click.
6801     * Subclasses should set the view clickable to visually react to
6802     * user's clicks.
6803     *
6804     * @param clickable true to make the view clickable, false otherwise
6805     *
6806     * @see #isClickable()
6807     * @attr ref android.R.styleable#View_clickable
6808     */
6809    public void setClickable(boolean clickable) {
6810        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6811    }
6812
6813    /**
6814     * Indicates whether this view reacts to long click events or not.
6815     *
6816     * @return true if the view is long clickable, false otherwise
6817     *
6818     * @see #setLongClickable(boolean)
6819     * @attr ref android.R.styleable#View_longClickable
6820     */
6821    public boolean isLongClickable() {
6822        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6823    }
6824
6825    /**
6826     * Enables or disables long click events for this view. When a view is long
6827     * clickable it reacts to the user holding down the button for a longer
6828     * duration than a tap. This event can either launch the listener or a
6829     * context menu.
6830     *
6831     * @param longClickable true to make the view long clickable, false otherwise
6832     * @see #isLongClickable()
6833     * @attr ref android.R.styleable#View_longClickable
6834     */
6835    public void setLongClickable(boolean longClickable) {
6836        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6837    }
6838
6839    /**
6840     * Sets the pressed state for this view and provides a touch coordinate for
6841     * animation hinting.
6842     *
6843     * @param pressed Pass true to set the View's internal state to "pressed",
6844     *            or false to reverts the View's internal state from a
6845     *            previously set "pressed" state.
6846     * @param x The x coordinate of the touch that caused the press
6847     * @param y The y coordinate of the touch that caused the press
6848     */
6849    private void setPressed(boolean pressed, float x, float y) {
6850        if (pressed) {
6851            drawableHotspotChanged(x, y);
6852        }
6853
6854        setPressed(pressed);
6855    }
6856
6857    /**
6858     * Sets the pressed state for this view.
6859     *
6860     * @see #isClickable()
6861     * @see #setClickable(boolean)
6862     *
6863     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6864     *        the View's internal state from a previously set "pressed" state.
6865     */
6866    public void setPressed(boolean pressed) {
6867        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6868
6869        if (pressed) {
6870            mPrivateFlags |= PFLAG_PRESSED;
6871        } else {
6872            mPrivateFlags &= ~PFLAG_PRESSED;
6873        }
6874
6875        if (needsRefresh) {
6876            refreshDrawableState();
6877        }
6878        dispatchSetPressed(pressed);
6879    }
6880
6881    /**
6882     * Dispatch setPressed to all of this View's children.
6883     *
6884     * @see #setPressed(boolean)
6885     *
6886     * @param pressed The new pressed state
6887     */
6888    protected void dispatchSetPressed(boolean pressed) {
6889    }
6890
6891    /**
6892     * Indicates whether the view is currently in pressed state. Unless
6893     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6894     * the pressed state.
6895     *
6896     * @see #setPressed(boolean)
6897     * @see #isClickable()
6898     * @see #setClickable(boolean)
6899     *
6900     * @return true if the view is currently pressed, false otherwise
6901     */
6902    public boolean isPressed() {
6903        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6904    }
6905
6906    /**
6907     * Indicates whether this view will save its state (that is,
6908     * whether its {@link #onSaveInstanceState} method will be called).
6909     *
6910     * @return Returns true if the view state saving is enabled, else false.
6911     *
6912     * @see #setSaveEnabled(boolean)
6913     * @attr ref android.R.styleable#View_saveEnabled
6914     */
6915    public boolean isSaveEnabled() {
6916        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6917    }
6918
6919    /**
6920     * Controls whether the saving of this view's state is
6921     * enabled (that is, whether its {@link #onSaveInstanceState} method
6922     * will be called).  Note that even if freezing is enabled, the
6923     * view still must have an id assigned to it (via {@link #setId(int)})
6924     * for its state to be saved.  This flag can only disable the
6925     * saving of this view; any child views may still have their state saved.
6926     *
6927     * @param enabled Set to false to <em>disable</em> state saving, or true
6928     * (the default) to allow it.
6929     *
6930     * @see #isSaveEnabled()
6931     * @see #setId(int)
6932     * @see #onSaveInstanceState()
6933     * @attr ref android.R.styleable#View_saveEnabled
6934     */
6935    public void setSaveEnabled(boolean enabled) {
6936        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6937    }
6938
6939    /**
6940     * Gets whether the framework should discard touches when the view's
6941     * window is obscured by another visible window.
6942     * Refer to the {@link View} security documentation for more details.
6943     *
6944     * @return True if touch filtering is enabled.
6945     *
6946     * @see #setFilterTouchesWhenObscured(boolean)
6947     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6948     */
6949    @ViewDebug.ExportedProperty
6950    public boolean getFilterTouchesWhenObscured() {
6951        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6952    }
6953
6954    /**
6955     * Sets whether the framework should discard touches when the view's
6956     * window is obscured by another visible window.
6957     * Refer to the {@link View} security documentation for more details.
6958     *
6959     * @param enabled True if touch filtering should be enabled.
6960     *
6961     * @see #getFilterTouchesWhenObscured
6962     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6963     */
6964    public void setFilterTouchesWhenObscured(boolean enabled) {
6965        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6966                FILTER_TOUCHES_WHEN_OBSCURED);
6967    }
6968
6969    /**
6970     * Indicates whether the entire hierarchy under this view will save its
6971     * state when a state saving traversal occurs from its parent.  The default
6972     * is true; if false, these views will not be saved unless
6973     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6974     *
6975     * @return Returns true if the view state saving from parent is enabled, else false.
6976     *
6977     * @see #setSaveFromParentEnabled(boolean)
6978     */
6979    public boolean isSaveFromParentEnabled() {
6980        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6981    }
6982
6983    /**
6984     * Controls whether the entire hierarchy under this view will save its
6985     * state when a state saving traversal occurs from its parent.  The default
6986     * is true; if false, these views will not be saved unless
6987     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6988     *
6989     * @param enabled Set to false to <em>disable</em> state saving, or true
6990     * (the default) to allow it.
6991     *
6992     * @see #isSaveFromParentEnabled()
6993     * @see #setId(int)
6994     * @see #onSaveInstanceState()
6995     */
6996    public void setSaveFromParentEnabled(boolean enabled) {
6997        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6998    }
6999
7000
7001    /**
7002     * Returns whether this View is able to take focus.
7003     *
7004     * @return True if this view can take focus, or false otherwise.
7005     * @attr ref android.R.styleable#View_focusable
7006     */
7007    @ViewDebug.ExportedProperty(category = "focus")
7008    public final boolean isFocusable() {
7009        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7010    }
7011
7012    /**
7013     * When a view is focusable, it may not want to take focus when in touch mode.
7014     * For example, a button would like focus when the user is navigating via a D-pad
7015     * so that the user can click on it, but once the user starts touching the screen,
7016     * the button shouldn't take focus
7017     * @return Whether the view is focusable in touch mode.
7018     * @attr ref android.R.styleable#View_focusableInTouchMode
7019     */
7020    @ViewDebug.ExportedProperty
7021    public final boolean isFocusableInTouchMode() {
7022        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7023    }
7024
7025    /**
7026     * Find the nearest view in the specified direction that can take focus.
7027     * This does not actually give focus to that view.
7028     *
7029     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7030     *
7031     * @return The nearest focusable in the specified direction, or null if none
7032     *         can be found.
7033     */
7034    public View focusSearch(@FocusRealDirection int direction) {
7035        if (mParent != null) {
7036            return mParent.focusSearch(this, direction);
7037        } else {
7038            return null;
7039        }
7040    }
7041
7042    /**
7043     * This method is the last chance for the focused view and its ancestors to
7044     * respond to an arrow key. This is called when the focused view did not
7045     * consume the key internally, nor could the view system find a new view in
7046     * the requested direction to give focus to.
7047     *
7048     * @param focused The currently focused view.
7049     * @param direction The direction focus wants to move. One of FOCUS_UP,
7050     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7051     * @return True if the this view consumed this unhandled move.
7052     */
7053    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7054        return false;
7055    }
7056
7057    /**
7058     * If a user manually specified the next view id for a particular direction,
7059     * use the root to look up the view.
7060     * @param root The root view of the hierarchy containing this view.
7061     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7062     * or FOCUS_BACKWARD.
7063     * @return The user specified next view, or null if there is none.
7064     */
7065    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7066        switch (direction) {
7067            case FOCUS_LEFT:
7068                if (mNextFocusLeftId == View.NO_ID) return null;
7069                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7070            case FOCUS_RIGHT:
7071                if (mNextFocusRightId == View.NO_ID) return null;
7072                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7073            case FOCUS_UP:
7074                if (mNextFocusUpId == View.NO_ID) return null;
7075                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7076            case FOCUS_DOWN:
7077                if (mNextFocusDownId == View.NO_ID) return null;
7078                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7079            case FOCUS_FORWARD:
7080                if (mNextFocusForwardId == View.NO_ID) return null;
7081                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7082            case FOCUS_BACKWARD: {
7083                if (mID == View.NO_ID) return null;
7084                final int id = mID;
7085                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7086                    @Override
7087                    public boolean apply(View t) {
7088                        return t.mNextFocusForwardId == id;
7089                    }
7090                });
7091            }
7092        }
7093        return null;
7094    }
7095
7096    private View findViewInsideOutShouldExist(View root, int id) {
7097        if (mMatchIdPredicate == null) {
7098            mMatchIdPredicate = new MatchIdPredicate();
7099        }
7100        mMatchIdPredicate.mId = id;
7101        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7102        if (result == null) {
7103            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7104        }
7105        return result;
7106    }
7107
7108    /**
7109     * Find and return all focusable views that are descendants of this view,
7110     * possibly including this view if it is focusable itself.
7111     *
7112     * @param direction The direction of the focus
7113     * @return A list of focusable views
7114     */
7115    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7116        ArrayList<View> result = new ArrayList<View>(24);
7117        addFocusables(result, direction);
7118        return result;
7119    }
7120
7121    /**
7122     * Add any focusable views that are descendants of this view (possibly
7123     * including this view if it is focusable itself) to views.  If we are in touch mode,
7124     * only add views that are also focusable in touch mode.
7125     *
7126     * @param views Focusable views found so far
7127     * @param direction The direction of the focus
7128     */
7129    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7130        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7131    }
7132
7133    /**
7134     * Adds any focusable views that are descendants of this view (possibly
7135     * including this view if it is focusable itself) to views. This method
7136     * adds all focusable views regardless if we are in touch mode or
7137     * only views focusable in touch mode if we are in touch mode or
7138     * only views that can take accessibility focus if accessibility is enabeld
7139     * depending on the focusable mode paramater.
7140     *
7141     * @param views Focusable views found so far or null if all we are interested is
7142     *        the number of focusables.
7143     * @param direction The direction of the focus.
7144     * @param focusableMode The type of focusables to be added.
7145     *
7146     * @see #FOCUSABLES_ALL
7147     * @see #FOCUSABLES_TOUCH_MODE
7148     */
7149    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7150            @FocusableMode int focusableMode) {
7151        if (views == null) {
7152            return;
7153        }
7154        if (!isFocusable()) {
7155            return;
7156        }
7157        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7158                && isInTouchMode() && !isFocusableInTouchMode()) {
7159            return;
7160        }
7161        views.add(this);
7162    }
7163
7164    /**
7165     * Finds the Views that contain given text. The containment is case insensitive.
7166     * The search is performed by either the text that the View renders or the content
7167     * description that describes the view for accessibility purposes and the view does
7168     * not render or both. Clients can specify how the search is to be performed via
7169     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7170     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7171     *
7172     * @param outViews The output list of matching Views.
7173     * @param searched The text to match against.
7174     *
7175     * @see #FIND_VIEWS_WITH_TEXT
7176     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7177     * @see #setContentDescription(CharSequence)
7178     */
7179    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7180            @FindViewFlags int flags) {
7181        if (getAccessibilityNodeProvider() != null) {
7182            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7183                outViews.add(this);
7184            }
7185        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7186                && (searched != null && searched.length() > 0)
7187                && (mContentDescription != null && mContentDescription.length() > 0)) {
7188            String searchedLowerCase = searched.toString().toLowerCase();
7189            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7190            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7191                outViews.add(this);
7192            }
7193        }
7194    }
7195
7196    /**
7197     * Find and return all touchable views that are descendants of this view,
7198     * possibly including this view if it is touchable itself.
7199     *
7200     * @return A list of touchable views
7201     */
7202    public ArrayList<View> getTouchables() {
7203        ArrayList<View> result = new ArrayList<View>();
7204        addTouchables(result);
7205        return result;
7206    }
7207
7208    /**
7209     * Add any touchable views that are descendants of this view (possibly
7210     * including this view if it is touchable itself) to views.
7211     *
7212     * @param views Touchable views found so far
7213     */
7214    public void addTouchables(ArrayList<View> views) {
7215        final int viewFlags = mViewFlags;
7216
7217        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7218                && (viewFlags & ENABLED_MASK) == ENABLED) {
7219            views.add(this);
7220        }
7221    }
7222
7223    /**
7224     * Returns whether this View is accessibility focused.
7225     *
7226     * @return True if this View is accessibility focused.
7227     */
7228    public boolean isAccessibilityFocused() {
7229        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7230    }
7231
7232    /**
7233     * Call this to try to give accessibility focus to this view.
7234     *
7235     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7236     * returns false or the view is no visible or the view already has accessibility
7237     * focus.
7238     *
7239     * See also {@link #focusSearch(int)}, which is what you call to say that you
7240     * have focus, and you want your parent to look for the next one.
7241     *
7242     * @return Whether this view actually took accessibility focus.
7243     *
7244     * @hide
7245     */
7246    public boolean requestAccessibilityFocus() {
7247        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7248        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7249            return false;
7250        }
7251        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7252            return false;
7253        }
7254        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7255            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7256            ViewRootImpl viewRootImpl = getViewRootImpl();
7257            if (viewRootImpl != null) {
7258                viewRootImpl.setAccessibilityFocus(this, null);
7259            }
7260            invalidate();
7261            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7262            return true;
7263        }
7264        return false;
7265    }
7266
7267    /**
7268     * Call this to try to clear accessibility focus of this view.
7269     *
7270     * See also {@link #focusSearch(int)}, which is what you call to say that you
7271     * have focus, and you want your parent to look for the next one.
7272     *
7273     * @hide
7274     */
7275    public void clearAccessibilityFocus() {
7276        clearAccessibilityFocusNoCallbacks();
7277        // Clear the global reference of accessibility focus if this
7278        // view or any of its descendants had accessibility focus.
7279        ViewRootImpl viewRootImpl = getViewRootImpl();
7280        if (viewRootImpl != null) {
7281            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7282            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7283                viewRootImpl.setAccessibilityFocus(null, null);
7284            }
7285        }
7286    }
7287
7288    private void sendAccessibilityHoverEvent(int eventType) {
7289        // Since we are not delivering to a client accessibility events from not
7290        // important views (unless the clinet request that) we need to fire the
7291        // event from the deepest view exposed to the client. As a consequence if
7292        // the user crosses a not exposed view the client will see enter and exit
7293        // of the exposed predecessor followed by and enter and exit of that same
7294        // predecessor when entering and exiting the not exposed descendant. This
7295        // is fine since the client has a clear idea which view is hovered at the
7296        // price of a couple more events being sent. This is a simple and
7297        // working solution.
7298        View source = this;
7299        while (true) {
7300            if (source.includeForAccessibility()) {
7301                source.sendAccessibilityEvent(eventType);
7302                return;
7303            }
7304            ViewParent parent = source.getParent();
7305            if (parent instanceof View) {
7306                source = (View) parent;
7307            } else {
7308                return;
7309            }
7310        }
7311    }
7312
7313    /**
7314     * Clears accessibility focus without calling any callback methods
7315     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7316     * is used for clearing accessibility focus when giving this focus to
7317     * another view.
7318     */
7319    void clearAccessibilityFocusNoCallbacks() {
7320        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7321            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7322            invalidate();
7323            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7324        }
7325    }
7326
7327    /**
7328     * Call this to try to give focus to a specific view or to one of its
7329     * descendants.
7330     *
7331     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7332     * false), or if it is focusable and it is not focusable in touch mode
7333     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7334     *
7335     * See also {@link #focusSearch(int)}, which is what you call to say that you
7336     * have focus, and you want your parent to look for the next one.
7337     *
7338     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7339     * {@link #FOCUS_DOWN} and <code>null</code>.
7340     *
7341     * @return Whether this view or one of its descendants actually took focus.
7342     */
7343    public final boolean requestFocus() {
7344        return requestFocus(View.FOCUS_DOWN);
7345    }
7346
7347    /**
7348     * Call this to try to give focus to a specific view or to one of its
7349     * descendants and give it a hint about what direction focus is heading.
7350     *
7351     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7352     * false), or if it is focusable and it is not focusable in touch mode
7353     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7354     *
7355     * See also {@link #focusSearch(int)}, which is what you call to say that you
7356     * have focus, and you want your parent to look for the next one.
7357     *
7358     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7359     * <code>null</code> set for the previously focused rectangle.
7360     *
7361     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7362     * @return Whether this view or one of its descendants actually took focus.
7363     */
7364    public final boolean requestFocus(int direction) {
7365        return requestFocus(direction, null);
7366    }
7367
7368    /**
7369     * Call this to try to give focus to a specific view or to one of its descendants
7370     * and give it hints about the direction and a specific rectangle that the focus
7371     * is coming from.  The rectangle can help give larger views a finer grained hint
7372     * about where focus is coming from, and therefore, where to show selection, or
7373     * forward focus change internally.
7374     *
7375     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7376     * false), or if it is focusable and it is not focusable in touch mode
7377     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7378     *
7379     * A View will not take focus if it is not visible.
7380     *
7381     * A View will not take focus if one of its parents has
7382     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7383     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7384     *
7385     * See also {@link #focusSearch(int)}, which is what you call to say that you
7386     * have focus, and you want your parent to look for the next one.
7387     *
7388     * You may wish to override this method if your custom {@link View} has an internal
7389     * {@link View} that it wishes to forward the request to.
7390     *
7391     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7392     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7393     *        to give a finer grained hint about where focus is coming from.  May be null
7394     *        if there is no hint.
7395     * @return Whether this view or one of its descendants actually took focus.
7396     */
7397    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7398        return requestFocusNoSearch(direction, previouslyFocusedRect);
7399    }
7400
7401    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7402        // need to be focusable
7403        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7404                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7405            return false;
7406        }
7407
7408        // need to be focusable in touch mode if in touch mode
7409        if (isInTouchMode() &&
7410            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7411               return false;
7412        }
7413
7414        // need to not have any parents blocking us
7415        if (hasAncestorThatBlocksDescendantFocus()) {
7416            return false;
7417        }
7418
7419        handleFocusGainInternal(direction, previouslyFocusedRect);
7420        return true;
7421    }
7422
7423    /**
7424     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7425     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7426     * touch mode to request focus when they are touched.
7427     *
7428     * @return Whether this view or one of its descendants actually took focus.
7429     *
7430     * @see #isInTouchMode()
7431     *
7432     */
7433    public final boolean requestFocusFromTouch() {
7434        // Leave touch mode if we need to
7435        if (isInTouchMode()) {
7436            ViewRootImpl viewRoot = getViewRootImpl();
7437            if (viewRoot != null) {
7438                viewRoot.ensureTouchMode(false);
7439            }
7440        }
7441        return requestFocus(View.FOCUS_DOWN);
7442    }
7443
7444    /**
7445     * @return Whether any ancestor of this view blocks descendant focus.
7446     */
7447    private boolean hasAncestorThatBlocksDescendantFocus() {
7448        final boolean focusableInTouchMode = isFocusableInTouchMode();
7449        ViewParent ancestor = mParent;
7450        while (ancestor instanceof ViewGroup) {
7451            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7452            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7453                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7454                return true;
7455            } else {
7456                ancestor = vgAncestor.getParent();
7457            }
7458        }
7459        return false;
7460    }
7461
7462    /**
7463     * Gets the mode for determining whether this View is important for accessibility
7464     * which is if it fires accessibility events and if it is reported to
7465     * accessibility services that query the screen.
7466     *
7467     * @return The mode for determining whether a View is important for accessibility.
7468     *
7469     * @attr ref android.R.styleable#View_importantForAccessibility
7470     *
7471     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7472     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7473     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7474     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7475     */
7476    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7477            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7478            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7479            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7480            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7481                    to = "noHideDescendants")
7482        })
7483    public int getImportantForAccessibility() {
7484        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7485                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7486    }
7487
7488    /**
7489     * Sets the live region mode for this view. This indicates to accessibility
7490     * services whether they should automatically notify the user about changes
7491     * to the view's content description or text, or to the content descriptions
7492     * or text of the view's children (where applicable).
7493     * <p>
7494     * For example, in a login screen with a TextView that displays an "incorrect
7495     * password" notification, that view should be marked as a live region with
7496     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7497     * <p>
7498     * To disable change notifications for this view, use
7499     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7500     * mode for most views.
7501     * <p>
7502     * To indicate that the user should be notified of changes, use
7503     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7504     * <p>
7505     * If the view's changes should interrupt ongoing speech and notify the user
7506     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7507     *
7508     * @param mode The live region mode for this view, one of:
7509     *        <ul>
7510     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7511     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7512     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7513     *        </ul>
7514     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7515     */
7516    public void setAccessibilityLiveRegion(int mode) {
7517        if (mode != getAccessibilityLiveRegion()) {
7518            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7519            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7520                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7521            notifyViewAccessibilityStateChangedIfNeeded(
7522                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7523        }
7524    }
7525
7526    /**
7527     * Gets the live region mode for this View.
7528     *
7529     * @return The live region mode for the view.
7530     *
7531     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7532     *
7533     * @see #setAccessibilityLiveRegion(int)
7534     */
7535    public int getAccessibilityLiveRegion() {
7536        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7537                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7538    }
7539
7540    /**
7541     * Sets how to determine whether this view is important for accessibility
7542     * which is if it fires accessibility events and if it is reported to
7543     * accessibility services that query the screen.
7544     *
7545     * @param mode How to determine whether this view is important for accessibility.
7546     *
7547     * @attr ref android.R.styleable#View_importantForAccessibility
7548     *
7549     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7550     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7551     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7552     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7553     */
7554    public void setImportantForAccessibility(int mode) {
7555        final int oldMode = getImportantForAccessibility();
7556        if (mode != oldMode) {
7557            // If we're moving between AUTO and another state, we might not need
7558            // to send a subtree changed notification. We'll store the computed
7559            // importance, since we'll need to check it later to make sure.
7560            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7561                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7562            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7563            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7564            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7565                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7566            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7567                notifySubtreeAccessibilityStateChangedIfNeeded();
7568            } else {
7569                notifyViewAccessibilityStateChangedIfNeeded(
7570                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7571            }
7572        }
7573    }
7574
7575    /**
7576     * Computes whether this view should be exposed for accessibility. In
7577     * general, views that are interactive or provide information are exposed
7578     * while views that serve only as containers are hidden.
7579     * <p>
7580     * If an ancestor of this view has importance
7581     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7582     * returns <code>false</code>.
7583     * <p>
7584     * Otherwise, the value is computed according to the view's
7585     * {@link #getImportantForAccessibility()} value:
7586     * <ol>
7587     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7588     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7589     * </code>
7590     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7591     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7592     * view satisfies any of the following:
7593     * <ul>
7594     * <li>Is actionable, e.g. {@link #isClickable()},
7595     * {@link #isLongClickable()}, or {@link #isFocusable()}
7596     * <li>Has an {@link AccessibilityDelegate}
7597     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7598     * {@link OnKeyListener}, etc.
7599     * <li>Is an accessibility live region, e.g.
7600     * {@link #getAccessibilityLiveRegion()} is not
7601     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7602     * </ul>
7603     * </ol>
7604     *
7605     * @return Whether the view is exposed for accessibility.
7606     * @see #setImportantForAccessibility(int)
7607     * @see #getImportantForAccessibility()
7608     */
7609    public boolean isImportantForAccessibility() {
7610        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7611                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7612        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7613                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7614            return false;
7615        }
7616
7617        // Check parent mode to ensure we're not hidden.
7618        ViewParent parent = mParent;
7619        while (parent instanceof View) {
7620            if (((View) parent).getImportantForAccessibility()
7621                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7622                return false;
7623            }
7624            parent = parent.getParent();
7625        }
7626
7627        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7628                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7629                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7630    }
7631
7632    /**
7633     * Gets the parent for accessibility purposes. Note that the parent for
7634     * accessibility is not necessary the immediate parent. It is the first
7635     * predecessor that is important for accessibility.
7636     *
7637     * @return The parent for accessibility purposes.
7638     */
7639    public ViewParent getParentForAccessibility() {
7640        if (mParent instanceof View) {
7641            View parentView = (View) mParent;
7642            if (parentView.includeForAccessibility()) {
7643                return mParent;
7644            } else {
7645                return mParent.getParentForAccessibility();
7646            }
7647        }
7648        return null;
7649    }
7650
7651    /**
7652     * Adds the children of a given View for accessibility. Since some Views are
7653     * not important for accessibility the children for accessibility are not
7654     * necessarily direct children of the view, rather they are the first level of
7655     * descendants important for accessibility.
7656     *
7657     * @param children The list of children for accessibility.
7658     */
7659    public void addChildrenForAccessibility(ArrayList<View> children) {
7660
7661    }
7662
7663    /**
7664     * Whether to regard this view for accessibility. A view is regarded for
7665     * accessibility if it is important for accessibility or the querying
7666     * accessibility service has explicitly requested that view not
7667     * important for accessibility are regarded.
7668     *
7669     * @return Whether to regard the view for accessibility.
7670     *
7671     * @hide
7672     */
7673    public boolean includeForAccessibility() {
7674        if (mAttachInfo != null) {
7675            return (mAttachInfo.mAccessibilityFetchFlags
7676                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7677                    || isImportantForAccessibility();
7678        }
7679        return false;
7680    }
7681
7682    /**
7683     * Returns whether the View is considered actionable from
7684     * accessibility perspective. Such view are important for
7685     * accessibility.
7686     *
7687     * @return True if the view is actionable for accessibility.
7688     *
7689     * @hide
7690     */
7691    public boolean isActionableForAccessibility() {
7692        return (isClickable() || isLongClickable() || isFocusable());
7693    }
7694
7695    /**
7696     * Returns whether the View has registered callbacks which makes it
7697     * important for accessibility.
7698     *
7699     * @return True if the view is actionable for accessibility.
7700     */
7701    private boolean hasListenersForAccessibility() {
7702        ListenerInfo info = getListenerInfo();
7703        return mTouchDelegate != null || info.mOnKeyListener != null
7704                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7705                || info.mOnHoverListener != null || info.mOnDragListener != null;
7706    }
7707
7708    /**
7709     * Notifies that the accessibility state of this view changed. The change
7710     * is local to this view and does not represent structural changes such
7711     * as children and parent. For example, the view became focusable. The
7712     * notification is at at most once every
7713     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7714     * to avoid unnecessary load to the system. Also once a view has a pending
7715     * notification this method is a NOP until the notification has been sent.
7716     *
7717     * @hide
7718     */
7719    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7720        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7721            return;
7722        }
7723        if (mSendViewStateChangedAccessibilityEvent == null) {
7724            mSendViewStateChangedAccessibilityEvent =
7725                    new SendViewStateChangedAccessibilityEvent();
7726        }
7727        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7728    }
7729
7730    /**
7731     * Notifies that the accessibility state of this view changed. The change
7732     * is *not* local to this view and does represent structural changes such
7733     * as children and parent. For example, the view size changed. The
7734     * notification is at at most once every
7735     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7736     * to avoid unnecessary load to the system. Also once a view has a pending
7737     * notification this method is a NOP until the notification has been sent.
7738     *
7739     * @hide
7740     */
7741    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7742        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7743            return;
7744        }
7745        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7746            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7747            if (mParent != null) {
7748                try {
7749                    mParent.notifySubtreeAccessibilityStateChanged(
7750                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7751                } catch (AbstractMethodError e) {
7752                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7753                            " does not fully implement ViewParent", e);
7754                }
7755            }
7756        }
7757    }
7758
7759    /**
7760     * Reset the flag indicating the accessibility state of the subtree rooted
7761     * at this view changed.
7762     */
7763    void resetSubtreeAccessibilityStateChanged() {
7764        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7765    }
7766
7767    /**
7768     * Performs the specified accessibility action on the view. For
7769     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7770     * <p>
7771     * If an {@link AccessibilityDelegate} has been specified via calling
7772     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7773     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7774     * is responsible for handling this call.
7775     * </p>
7776     *
7777     * @param action The action to perform.
7778     * @param arguments Optional action arguments.
7779     * @return Whether the action was performed.
7780     */
7781    public boolean performAccessibilityAction(int action, Bundle arguments) {
7782      if (mAccessibilityDelegate != null) {
7783          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7784      } else {
7785          return performAccessibilityActionInternal(action, arguments);
7786      }
7787    }
7788
7789   /**
7790    * @see #performAccessibilityAction(int, Bundle)
7791    *
7792    * Note: Called from the default {@link AccessibilityDelegate}.
7793    */
7794    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7795        switch (action) {
7796            case AccessibilityNodeInfo.ACTION_CLICK: {
7797                if (isClickable()) {
7798                    performClick();
7799                    return true;
7800                }
7801            } break;
7802            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7803                if (isLongClickable()) {
7804                    performLongClick();
7805                    return true;
7806                }
7807            } break;
7808            case AccessibilityNodeInfo.ACTION_FOCUS: {
7809                if (!hasFocus()) {
7810                    // Get out of touch mode since accessibility
7811                    // wants to move focus around.
7812                    getViewRootImpl().ensureTouchMode(false);
7813                    return requestFocus();
7814                }
7815            } break;
7816            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7817                if (hasFocus()) {
7818                    clearFocus();
7819                    return !isFocused();
7820                }
7821            } break;
7822            case AccessibilityNodeInfo.ACTION_SELECT: {
7823                if (!isSelected()) {
7824                    setSelected(true);
7825                    return isSelected();
7826                }
7827            } break;
7828            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7829                if (isSelected()) {
7830                    setSelected(false);
7831                    return !isSelected();
7832                }
7833            } break;
7834            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7835                if (!isAccessibilityFocused()) {
7836                    return requestAccessibilityFocus();
7837                }
7838            } break;
7839            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7840                if (isAccessibilityFocused()) {
7841                    clearAccessibilityFocus();
7842                    return true;
7843                }
7844            } break;
7845            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7846                if (arguments != null) {
7847                    final int granularity = arguments.getInt(
7848                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7849                    final boolean extendSelection = arguments.getBoolean(
7850                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7851                    return traverseAtGranularity(granularity, true, extendSelection);
7852                }
7853            } break;
7854            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7855                if (arguments != null) {
7856                    final int granularity = arguments.getInt(
7857                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7858                    final boolean extendSelection = arguments.getBoolean(
7859                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7860                    return traverseAtGranularity(granularity, false, extendSelection);
7861                }
7862            } break;
7863            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7864                CharSequence text = getIterableTextForAccessibility();
7865                if (text == null) {
7866                    return false;
7867                }
7868                final int start = (arguments != null) ? arguments.getInt(
7869                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7870                final int end = (arguments != null) ? arguments.getInt(
7871                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7872                // Only cursor position can be specified (selection length == 0)
7873                if ((getAccessibilitySelectionStart() != start
7874                        || getAccessibilitySelectionEnd() != end)
7875                        && (start == end)) {
7876                    setAccessibilitySelection(start, end);
7877                    notifyViewAccessibilityStateChangedIfNeeded(
7878                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7879                    return true;
7880                }
7881            } break;
7882        }
7883        return false;
7884    }
7885
7886    private boolean traverseAtGranularity(int granularity, boolean forward,
7887            boolean extendSelection) {
7888        CharSequence text = getIterableTextForAccessibility();
7889        if (text == null || text.length() == 0) {
7890            return false;
7891        }
7892        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7893        if (iterator == null) {
7894            return false;
7895        }
7896        int current = getAccessibilitySelectionEnd();
7897        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7898            current = forward ? 0 : text.length();
7899        }
7900        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7901        if (range == null) {
7902            return false;
7903        }
7904        final int segmentStart = range[0];
7905        final int segmentEnd = range[1];
7906        int selectionStart;
7907        int selectionEnd;
7908        if (extendSelection && isAccessibilitySelectionExtendable()) {
7909            selectionStart = getAccessibilitySelectionStart();
7910            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7911                selectionStart = forward ? segmentStart : segmentEnd;
7912            }
7913            selectionEnd = forward ? segmentEnd : segmentStart;
7914        } else {
7915            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7916        }
7917        setAccessibilitySelection(selectionStart, selectionEnd);
7918        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7919                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7920        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7921        return true;
7922    }
7923
7924    /**
7925     * Gets the text reported for accessibility purposes.
7926     *
7927     * @return The accessibility text.
7928     *
7929     * @hide
7930     */
7931    public CharSequence getIterableTextForAccessibility() {
7932        return getContentDescription();
7933    }
7934
7935    /**
7936     * Gets whether accessibility selection can be extended.
7937     *
7938     * @return If selection is extensible.
7939     *
7940     * @hide
7941     */
7942    public boolean isAccessibilitySelectionExtendable() {
7943        return false;
7944    }
7945
7946    /**
7947     * @hide
7948     */
7949    public int getAccessibilitySelectionStart() {
7950        return mAccessibilityCursorPosition;
7951    }
7952
7953    /**
7954     * @hide
7955     */
7956    public int getAccessibilitySelectionEnd() {
7957        return getAccessibilitySelectionStart();
7958    }
7959
7960    /**
7961     * @hide
7962     */
7963    public void setAccessibilitySelection(int start, int end) {
7964        if (start ==  end && end == mAccessibilityCursorPosition) {
7965            return;
7966        }
7967        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7968            mAccessibilityCursorPosition = start;
7969        } else {
7970            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7971        }
7972        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7973    }
7974
7975    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7976            int fromIndex, int toIndex) {
7977        if (mParent == null) {
7978            return;
7979        }
7980        AccessibilityEvent event = AccessibilityEvent.obtain(
7981                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7982        onInitializeAccessibilityEvent(event);
7983        onPopulateAccessibilityEvent(event);
7984        event.setFromIndex(fromIndex);
7985        event.setToIndex(toIndex);
7986        event.setAction(action);
7987        event.setMovementGranularity(granularity);
7988        mParent.requestSendAccessibilityEvent(this, event);
7989    }
7990
7991    /**
7992     * @hide
7993     */
7994    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7995        switch (granularity) {
7996            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7997                CharSequence text = getIterableTextForAccessibility();
7998                if (text != null && text.length() > 0) {
7999                    CharacterTextSegmentIterator iterator =
8000                        CharacterTextSegmentIterator.getInstance(
8001                                mContext.getResources().getConfiguration().locale);
8002                    iterator.initialize(text.toString());
8003                    return iterator;
8004                }
8005            } break;
8006            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8007                CharSequence text = getIterableTextForAccessibility();
8008                if (text != null && text.length() > 0) {
8009                    WordTextSegmentIterator iterator =
8010                        WordTextSegmentIterator.getInstance(
8011                                mContext.getResources().getConfiguration().locale);
8012                    iterator.initialize(text.toString());
8013                    return iterator;
8014                }
8015            } break;
8016            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8017                CharSequence text = getIterableTextForAccessibility();
8018                if (text != null && text.length() > 0) {
8019                    ParagraphTextSegmentIterator iterator =
8020                        ParagraphTextSegmentIterator.getInstance();
8021                    iterator.initialize(text.toString());
8022                    return iterator;
8023                }
8024            } break;
8025        }
8026        return null;
8027    }
8028
8029    /**
8030     * @hide
8031     */
8032    public void dispatchStartTemporaryDetach() {
8033        onStartTemporaryDetach();
8034    }
8035
8036    /**
8037     * This is called when a container is going to temporarily detach a child, with
8038     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8039     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8040     * {@link #onDetachedFromWindow()} when the container is done.
8041     */
8042    public void onStartTemporaryDetach() {
8043        removeUnsetPressCallback();
8044        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8045    }
8046
8047    /**
8048     * @hide
8049     */
8050    public void dispatchFinishTemporaryDetach() {
8051        onFinishTemporaryDetach();
8052    }
8053
8054    /**
8055     * Called after {@link #onStartTemporaryDetach} when the container is done
8056     * changing the view.
8057     */
8058    public void onFinishTemporaryDetach() {
8059    }
8060
8061    /**
8062     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8063     * for this view's window.  Returns null if the view is not currently attached
8064     * to the window.  Normally you will not need to use this directly, but
8065     * just use the standard high-level event callbacks like
8066     * {@link #onKeyDown(int, KeyEvent)}.
8067     */
8068    public KeyEvent.DispatcherState getKeyDispatcherState() {
8069        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8070    }
8071
8072    /**
8073     * Dispatch a key event before it is processed by any input method
8074     * associated with the view hierarchy.  This can be used to intercept
8075     * key events in special situations before the IME consumes them; a
8076     * typical example would be handling the BACK key to update the application's
8077     * UI instead of allowing the IME to see it and close itself.
8078     *
8079     * @param event The key event to be dispatched.
8080     * @return True if the event was handled, false otherwise.
8081     */
8082    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8083        return onKeyPreIme(event.getKeyCode(), event);
8084    }
8085
8086    /**
8087     * Dispatch a key event to the next view on the focus path. This path runs
8088     * from the top of the view tree down to the currently focused view. If this
8089     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8090     * the next node down the focus path. This method also fires any key
8091     * listeners.
8092     *
8093     * @param event The key event to be dispatched.
8094     * @return True if the event was handled, false otherwise.
8095     */
8096    public boolean dispatchKeyEvent(KeyEvent event) {
8097        if (mInputEventConsistencyVerifier != null) {
8098            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8099        }
8100
8101        // Give any attached key listener a first crack at the event.
8102        //noinspection SimplifiableIfStatement
8103        ListenerInfo li = mListenerInfo;
8104        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8105                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8106            return true;
8107        }
8108
8109        if (event.dispatch(this, mAttachInfo != null
8110                ? mAttachInfo.mKeyDispatchState : null, this)) {
8111            return true;
8112        }
8113
8114        if (mInputEventConsistencyVerifier != null) {
8115            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8116        }
8117        return false;
8118    }
8119
8120    /**
8121     * Dispatches a key shortcut event.
8122     *
8123     * @param event The key event to be dispatched.
8124     * @return True if the event was handled by the view, false otherwise.
8125     */
8126    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8127        return onKeyShortcut(event.getKeyCode(), event);
8128    }
8129
8130    /**
8131     * Pass the touch screen motion event down to the target view, or this
8132     * view if it is the target.
8133     *
8134     * @param event The motion event to be dispatched.
8135     * @return True if the event was handled by the view, false otherwise.
8136     */
8137    public boolean dispatchTouchEvent(MotionEvent event) {
8138        boolean result = false;
8139
8140        if (mInputEventConsistencyVerifier != null) {
8141            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8142        }
8143
8144        final int actionMasked = event.getActionMasked();
8145        if (actionMasked == MotionEvent.ACTION_DOWN) {
8146            // Defensive cleanup for new gesture
8147            stopNestedScroll();
8148        }
8149
8150        if (onFilterTouchEventForSecurity(event)) {
8151            //noinspection SimplifiableIfStatement
8152            ListenerInfo li = mListenerInfo;
8153            if (li != null && li.mOnTouchListener != null
8154                    && (mViewFlags & ENABLED_MASK) == ENABLED
8155                    && li.mOnTouchListener.onTouch(this, event)) {
8156                result = true;
8157            }
8158
8159            if (!result && onTouchEvent(event)) {
8160                result = true;
8161            }
8162        }
8163
8164        if (!result && mInputEventConsistencyVerifier != null) {
8165            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8166        }
8167
8168        // Clean up after nested scrolls if this is the end of a gesture;
8169        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8170        // of the gesture.
8171        if (actionMasked == MotionEvent.ACTION_UP ||
8172                actionMasked == MotionEvent.ACTION_CANCEL ||
8173                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8174            stopNestedScroll();
8175        }
8176
8177        return result;
8178    }
8179
8180    /**
8181     * Filter the touch event to apply security policies.
8182     *
8183     * @param event The motion event to be filtered.
8184     * @return True if the event should be dispatched, false if the event should be dropped.
8185     *
8186     * @see #getFilterTouchesWhenObscured
8187     */
8188    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8189        //noinspection RedundantIfStatement
8190        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8191                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8192            // Window is obscured, drop this touch.
8193            return false;
8194        }
8195        return true;
8196    }
8197
8198    /**
8199     * Pass a trackball motion event down to the focused view.
8200     *
8201     * @param event The motion event to be dispatched.
8202     * @return True if the event was handled by the view, false otherwise.
8203     */
8204    public boolean dispatchTrackballEvent(MotionEvent event) {
8205        if (mInputEventConsistencyVerifier != null) {
8206            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8207        }
8208
8209        return onTrackballEvent(event);
8210    }
8211
8212    /**
8213     * Dispatch a generic motion event.
8214     * <p>
8215     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8216     * are delivered to the view under the pointer.  All other generic motion events are
8217     * delivered to the focused view.  Hover events are handled specially and are delivered
8218     * to {@link #onHoverEvent(MotionEvent)}.
8219     * </p>
8220     *
8221     * @param event The motion event to be dispatched.
8222     * @return True if the event was handled by the view, false otherwise.
8223     */
8224    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8225        if (mInputEventConsistencyVerifier != null) {
8226            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8227        }
8228
8229        final int source = event.getSource();
8230        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8231            final int action = event.getAction();
8232            if (action == MotionEvent.ACTION_HOVER_ENTER
8233                    || action == MotionEvent.ACTION_HOVER_MOVE
8234                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8235                if (dispatchHoverEvent(event)) {
8236                    return true;
8237                }
8238            } else if (dispatchGenericPointerEvent(event)) {
8239                return true;
8240            }
8241        } else if (dispatchGenericFocusedEvent(event)) {
8242            return true;
8243        }
8244
8245        if (dispatchGenericMotionEventInternal(event)) {
8246            return true;
8247        }
8248
8249        if (mInputEventConsistencyVerifier != null) {
8250            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8251        }
8252        return false;
8253    }
8254
8255    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8256        //noinspection SimplifiableIfStatement
8257        ListenerInfo li = mListenerInfo;
8258        if (li != null && li.mOnGenericMotionListener != null
8259                && (mViewFlags & ENABLED_MASK) == ENABLED
8260                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8261            return true;
8262        }
8263
8264        if (onGenericMotionEvent(event)) {
8265            return true;
8266        }
8267
8268        if (mInputEventConsistencyVerifier != null) {
8269            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8270        }
8271        return false;
8272    }
8273
8274    /**
8275     * Dispatch a hover event.
8276     * <p>
8277     * Do not call this method directly.
8278     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8279     * </p>
8280     *
8281     * @param event The motion event to be dispatched.
8282     * @return True if the event was handled by the view, false otherwise.
8283     */
8284    protected boolean dispatchHoverEvent(MotionEvent event) {
8285        ListenerInfo li = mListenerInfo;
8286        //noinspection SimplifiableIfStatement
8287        if (li != null && li.mOnHoverListener != null
8288                && (mViewFlags & ENABLED_MASK) == ENABLED
8289                && li.mOnHoverListener.onHover(this, event)) {
8290            return true;
8291        }
8292
8293        return onHoverEvent(event);
8294    }
8295
8296    /**
8297     * Returns true if the view has a child to which it has recently sent
8298     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8299     * it does not have a hovered child, then it must be the innermost hovered view.
8300     * @hide
8301     */
8302    protected boolean hasHoveredChild() {
8303        return false;
8304    }
8305
8306    /**
8307     * Dispatch a generic motion event to the view under the first pointer.
8308     * <p>
8309     * Do not call this method directly.
8310     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8311     * </p>
8312     *
8313     * @param event The motion event to be dispatched.
8314     * @return True if the event was handled by the view, false otherwise.
8315     */
8316    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8317        return false;
8318    }
8319
8320    /**
8321     * Dispatch a generic motion event to the currently focused view.
8322     * <p>
8323     * Do not call this method directly.
8324     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8325     * </p>
8326     *
8327     * @param event The motion event to be dispatched.
8328     * @return True if the event was handled by the view, false otherwise.
8329     */
8330    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8331        return false;
8332    }
8333
8334    /**
8335     * Dispatch a pointer event.
8336     * <p>
8337     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8338     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8339     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8340     * and should not be expected to handle other pointing device features.
8341     * </p>
8342     *
8343     * @param event The motion event to be dispatched.
8344     * @return True if the event was handled by the view, false otherwise.
8345     * @hide
8346     */
8347    public final boolean dispatchPointerEvent(MotionEvent event) {
8348        if (event.isTouchEvent()) {
8349            return dispatchTouchEvent(event);
8350        } else {
8351            return dispatchGenericMotionEvent(event);
8352        }
8353    }
8354
8355    /**
8356     * Called when the window containing this view gains or loses window focus.
8357     * ViewGroups should override to route to their children.
8358     *
8359     * @param hasFocus True if the window containing this view now has focus,
8360     *        false otherwise.
8361     */
8362    public void dispatchWindowFocusChanged(boolean hasFocus) {
8363        onWindowFocusChanged(hasFocus);
8364    }
8365
8366    /**
8367     * Called when the window containing this view gains or loses focus.  Note
8368     * that this is separate from view focus: to receive key events, both
8369     * your view and its window must have focus.  If a window is displayed
8370     * on top of yours that takes input focus, then your own window will lose
8371     * focus but the view focus will remain unchanged.
8372     *
8373     * @param hasWindowFocus True if the window containing this view now has
8374     *        focus, false otherwise.
8375     */
8376    public void onWindowFocusChanged(boolean hasWindowFocus) {
8377        InputMethodManager imm = InputMethodManager.peekInstance();
8378        if (!hasWindowFocus) {
8379            if (isPressed()) {
8380                setPressed(false);
8381            }
8382            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8383                imm.focusOut(this);
8384            }
8385            removeLongPressCallback();
8386            removeTapCallback();
8387            onFocusLost();
8388        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8389            imm.focusIn(this);
8390        }
8391        refreshDrawableState();
8392    }
8393
8394    /**
8395     * Returns true if this view is in a window that currently has window focus.
8396     * Note that this is not the same as the view itself having focus.
8397     *
8398     * @return True if this view is in a window that currently has window focus.
8399     */
8400    public boolean hasWindowFocus() {
8401        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8402    }
8403
8404    /**
8405     * Dispatch a view visibility change down the view hierarchy.
8406     * ViewGroups should override to route to their children.
8407     * @param changedView The view whose visibility changed. Could be 'this' or
8408     * an ancestor view.
8409     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8410     * {@link #INVISIBLE} or {@link #GONE}.
8411     */
8412    protected void dispatchVisibilityChanged(@NonNull View changedView,
8413            @Visibility int visibility) {
8414        onVisibilityChanged(changedView, visibility);
8415    }
8416
8417    /**
8418     * Called when the visibility of the view or an ancestor of the view is changed.
8419     * @param changedView The view whose visibility changed. Could be 'this' or
8420     * an ancestor view.
8421     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8422     * {@link #INVISIBLE} or {@link #GONE}.
8423     */
8424    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8425        if (visibility == VISIBLE) {
8426            if (mAttachInfo != null) {
8427                initialAwakenScrollBars();
8428            } else {
8429                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8430            }
8431        }
8432    }
8433
8434    /**
8435     * Dispatch a hint about whether this view is displayed. For instance, when
8436     * a View moves out of the screen, it might receives a display hint indicating
8437     * the view is not displayed. Applications should not <em>rely</em> on this hint
8438     * as there is no guarantee that they will receive one.
8439     *
8440     * @param hint A hint about whether or not this view is displayed:
8441     * {@link #VISIBLE} or {@link #INVISIBLE}.
8442     */
8443    public void dispatchDisplayHint(@Visibility int hint) {
8444        onDisplayHint(hint);
8445    }
8446
8447    /**
8448     * Gives this view a hint about whether is displayed or not. For instance, when
8449     * a View moves out of the screen, it might receives a display hint indicating
8450     * the view is not displayed. Applications should not <em>rely</em> on this hint
8451     * as there is no guarantee that they will receive one.
8452     *
8453     * @param hint A hint about whether or not this view is displayed:
8454     * {@link #VISIBLE} or {@link #INVISIBLE}.
8455     */
8456    protected void onDisplayHint(@Visibility int hint) {
8457    }
8458
8459    /**
8460     * Dispatch a window visibility change down the view hierarchy.
8461     * ViewGroups should override to route to their children.
8462     *
8463     * @param visibility The new visibility of the window.
8464     *
8465     * @see #onWindowVisibilityChanged(int)
8466     */
8467    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8468        onWindowVisibilityChanged(visibility);
8469    }
8470
8471    /**
8472     * Called when the window containing has change its visibility
8473     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8474     * that this tells you whether or not your window is being made visible
8475     * to the window manager; this does <em>not</em> tell you whether or not
8476     * your window is obscured by other windows on the screen, even if it
8477     * is itself visible.
8478     *
8479     * @param visibility The new visibility of the window.
8480     */
8481    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8482        if (visibility == VISIBLE) {
8483            initialAwakenScrollBars();
8484        }
8485    }
8486
8487    /**
8488     * Returns the current visibility of the window this view is attached to
8489     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8490     *
8491     * @return Returns the current visibility of the view's window.
8492     */
8493    @Visibility
8494    public int getWindowVisibility() {
8495        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8496    }
8497
8498    /**
8499     * Retrieve the overall visible display size in which the window this view is
8500     * attached to has been positioned in.  This takes into account screen
8501     * decorations above the window, for both cases where the window itself
8502     * is being position inside of them or the window is being placed under
8503     * then and covered insets are used for the window to position its content
8504     * inside.  In effect, this tells you the available area where content can
8505     * be placed and remain visible to users.
8506     *
8507     * <p>This function requires an IPC back to the window manager to retrieve
8508     * the requested information, so should not be used in performance critical
8509     * code like drawing.
8510     *
8511     * @param outRect Filled in with the visible display frame.  If the view
8512     * is not attached to a window, this is simply the raw display size.
8513     */
8514    public void getWindowVisibleDisplayFrame(Rect outRect) {
8515        if (mAttachInfo != null) {
8516            try {
8517                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8518            } catch (RemoteException e) {
8519                return;
8520            }
8521            // XXX This is really broken, and probably all needs to be done
8522            // in the window manager, and we need to know more about whether
8523            // we want the area behind or in front of the IME.
8524            final Rect insets = mAttachInfo.mVisibleInsets;
8525            outRect.left += insets.left;
8526            outRect.top += insets.top;
8527            outRect.right -= insets.right;
8528            outRect.bottom -= insets.bottom;
8529            return;
8530        }
8531        // The view is not attached to a display so we don't have a context.
8532        // Make a best guess about the display size.
8533        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8534        d.getRectSize(outRect);
8535    }
8536
8537    /**
8538     * Dispatch a notification about a resource configuration change down
8539     * the view hierarchy.
8540     * ViewGroups should override to route to their children.
8541     *
8542     * @param newConfig The new resource configuration.
8543     *
8544     * @see #onConfigurationChanged(android.content.res.Configuration)
8545     */
8546    public void dispatchConfigurationChanged(Configuration newConfig) {
8547        onConfigurationChanged(newConfig);
8548    }
8549
8550    /**
8551     * Called when the current configuration of the resources being used
8552     * by the application have changed.  You can use this to decide when
8553     * to reload resources that can changed based on orientation and other
8554     * configuration characterstics.  You only need to use this if you are
8555     * not relying on the normal {@link android.app.Activity} mechanism of
8556     * recreating the activity instance upon a configuration change.
8557     *
8558     * @param newConfig The new resource configuration.
8559     */
8560    protected void onConfigurationChanged(Configuration newConfig) {
8561    }
8562
8563    /**
8564     * Private function to aggregate all per-view attributes in to the view
8565     * root.
8566     */
8567    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8568        performCollectViewAttributes(attachInfo, visibility);
8569    }
8570
8571    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8572        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8573            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8574                attachInfo.mKeepScreenOn = true;
8575            }
8576            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8577            ListenerInfo li = mListenerInfo;
8578            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8579                attachInfo.mHasSystemUiListeners = true;
8580            }
8581        }
8582    }
8583
8584    void needGlobalAttributesUpdate(boolean force) {
8585        final AttachInfo ai = mAttachInfo;
8586        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8587            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8588                    || ai.mHasSystemUiListeners) {
8589                ai.mRecomputeGlobalAttributes = true;
8590            }
8591        }
8592    }
8593
8594    /**
8595     * Returns whether the device is currently in touch mode.  Touch mode is entered
8596     * once the user begins interacting with the device by touch, and affects various
8597     * things like whether focus is always visible to the user.
8598     *
8599     * @return Whether the device is in touch mode.
8600     */
8601    @ViewDebug.ExportedProperty
8602    public boolean isInTouchMode() {
8603        if (mAttachInfo != null) {
8604            return mAttachInfo.mInTouchMode;
8605        } else {
8606            return ViewRootImpl.isInTouchMode();
8607        }
8608    }
8609
8610    /**
8611     * Returns the context the view is running in, through which it can
8612     * access the current theme, resources, etc.
8613     *
8614     * @return The view's Context.
8615     */
8616    @ViewDebug.CapturedViewProperty
8617    public final Context getContext() {
8618        return mContext;
8619    }
8620
8621    /**
8622     * Handle a key event before it is processed by any input method
8623     * associated with the view hierarchy.  This can be used to intercept
8624     * key events in special situations before the IME consumes them; a
8625     * typical example would be handling the BACK key to update the application's
8626     * UI instead of allowing the IME to see it and close itself.
8627     *
8628     * @param keyCode The value in event.getKeyCode().
8629     * @param event Description of the key event.
8630     * @return If you handled the event, return true. If you want to allow the
8631     *         event to be handled by the next receiver, return false.
8632     */
8633    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8634        return false;
8635    }
8636
8637    /**
8638     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8639     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8640     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8641     * is released, if the view is enabled and clickable.
8642     *
8643     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8644     * although some may elect to do so in some situations. Do not rely on this to
8645     * catch software key presses.
8646     *
8647     * @param keyCode A key code that represents the button pressed, from
8648     *                {@link android.view.KeyEvent}.
8649     * @param event   The KeyEvent object that defines the button action.
8650     */
8651    public boolean onKeyDown(int keyCode, KeyEvent event) {
8652        boolean result = false;
8653
8654        if (KeyEvent.isConfirmKey(keyCode)) {
8655            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8656                return true;
8657            }
8658            // Long clickable items don't necessarily have to be clickable
8659            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8660                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8661                    (event.getRepeatCount() == 0)) {
8662                setPressed(true);
8663                checkForLongClick(0);
8664                return true;
8665            }
8666        }
8667        return result;
8668    }
8669
8670    /**
8671     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8672     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8673     * the event).
8674     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8675     * although some may elect to do so in some situations. Do not rely on this to
8676     * catch software key presses.
8677     */
8678    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8679        return false;
8680    }
8681
8682    /**
8683     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8684     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8685     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8686     * {@link KeyEvent#KEYCODE_ENTER} is released.
8687     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8688     * although some may elect to do so in some situations. Do not rely on this to
8689     * catch software key presses.
8690     *
8691     * @param keyCode A key code that represents the button pressed, from
8692     *                {@link android.view.KeyEvent}.
8693     * @param event   The KeyEvent object that defines the button action.
8694     */
8695    public boolean onKeyUp(int keyCode, KeyEvent event) {
8696        if (KeyEvent.isConfirmKey(keyCode)) {
8697            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8698                return true;
8699            }
8700            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8701                setPressed(false);
8702
8703                if (!mHasPerformedLongPress) {
8704                    // This is a tap, so remove the longpress check
8705                    removeLongPressCallback();
8706                    return performClick();
8707                }
8708            }
8709        }
8710        return false;
8711    }
8712
8713    /**
8714     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8715     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8716     * the event).
8717     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8718     * although some may elect to do so in some situations. Do not rely on this to
8719     * catch software key presses.
8720     *
8721     * @param keyCode     A key code that represents the button pressed, from
8722     *                    {@link android.view.KeyEvent}.
8723     * @param repeatCount The number of times the action was made.
8724     * @param event       The KeyEvent object that defines the button action.
8725     */
8726    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8727        return false;
8728    }
8729
8730    /**
8731     * Called on the focused view when a key shortcut event is not handled.
8732     * Override this method to implement local key shortcuts for the View.
8733     * Key shortcuts can also be implemented by setting the
8734     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8735     *
8736     * @param keyCode The value in event.getKeyCode().
8737     * @param event Description of the key event.
8738     * @return If you handled the event, return true. If you want to allow the
8739     *         event to be handled by the next receiver, return false.
8740     */
8741    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8742        return false;
8743    }
8744
8745    /**
8746     * Check whether the called view is a text editor, in which case it
8747     * would make sense to automatically display a soft input window for
8748     * it.  Subclasses should override this if they implement
8749     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8750     * a call on that method would return a non-null InputConnection, and
8751     * they are really a first-class editor that the user would normally
8752     * start typing on when the go into a window containing your view.
8753     *
8754     * <p>The default implementation always returns false.  This does
8755     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8756     * will not be called or the user can not otherwise perform edits on your
8757     * view; it is just a hint to the system that this is not the primary
8758     * purpose of this view.
8759     *
8760     * @return Returns true if this view is a text editor, else false.
8761     */
8762    public boolean onCheckIsTextEditor() {
8763        return false;
8764    }
8765
8766    /**
8767     * Create a new InputConnection for an InputMethod to interact
8768     * with the view.  The default implementation returns null, since it doesn't
8769     * support input methods.  You can override this to implement such support.
8770     * This is only needed for views that take focus and text input.
8771     *
8772     * <p>When implementing this, you probably also want to implement
8773     * {@link #onCheckIsTextEditor()} to indicate you will return a
8774     * non-null InputConnection.</p>
8775     *
8776     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8777     * object correctly and in its entirety, so that the connected IME can rely
8778     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8779     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8780     * must be filled in with the correct cursor position for IMEs to work correctly
8781     * with your application.</p>
8782     *
8783     * @param outAttrs Fill in with attribute information about the connection.
8784     */
8785    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8786        return null;
8787    }
8788
8789    /**
8790     * Called by the {@link android.view.inputmethod.InputMethodManager}
8791     * when a view who is not the current
8792     * input connection target is trying to make a call on the manager.  The
8793     * default implementation returns false; you can override this to return
8794     * true for certain views if you are performing InputConnection proxying
8795     * to them.
8796     * @param view The View that is making the InputMethodManager call.
8797     * @return Return true to allow the call, false to reject.
8798     */
8799    public boolean checkInputConnectionProxy(View view) {
8800        return false;
8801    }
8802
8803    /**
8804     * Show the context menu for this view. It is not safe to hold on to the
8805     * menu after returning from this method.
8806     *
8807     * You should normally not overload this method. Overload
8808     * {@link #onCreateContextMenu(ContextMenu)} or define an
8809     * {@link OnCreateContextMenuListener} to add items to the context menu.
8810     *
8811     * @param menu The context menu to populate
8812     */
8813    public void createContextMenu(ContextMenu menu) {
8814        ContextMenuInfo menuInfo = getContextMenuInfo();
8815
8816        // Sets the current menu info so all items added to menu will have
8817        // my extra info set.
8818        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8819
8820        onCreateContextMenu(menu);
8821        ListenerInfo li = mListenerInfo;
8822        if (li != null && li.mOnCreateContextMenuListener != null) {
8823            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8824        }
8825
8826        // Clear the extra information so subsequent items that aren't mine don't
8827        // have my extra info.
8828        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8829
8830        if (mParent != null) {
8831            mParent.createContextMenu(menu);
8832        }
8833    }
8834
8835    /**
8836     * Views should implement this if they have extra information to associate
8837     * with the context menu. The return result is supplied as a parameter to
8838     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8839     * callback.
8840     *
8841     * @return Extra information about the item for which the context menu
8842     *         should be shown. This information will vary across different
8843     *         subclasses of View.
8844     */
8845    protected ContextMenuInfo getContextMenuInfo() {
8846        return null;
8847    }
8848
8849    /**
8850     * Views should implement this if the view itself is going to add items to
8851     * the context menu.
8852     *
8853     * @param menu the context menu to populate
8854     */
8855    protected void onCreateContextMenu(ContextMenu menu) {
8856    }
8857
8858    /**
8859     * Implement this method to handle trackball motion events.  The
8860     * <em>relative</em> movement of the trackball since the last event
8861     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8862     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8863     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8864     * they will often be fractional values, representing the more fine-grained
8865     * movement information available from a trackball).
8866     *
8867     * @param event The motion event.
8868     * @return True if the event was handled, false otherwise.
8869     */
8870    public boolean onTrackballEvent(MotionEvent event) {
8871        return false;
8872    }
8873
8874    /**
8875     * Implement this method to handle generic motion events.
8876     * <p>
8877     * Generic motion events describe joystick movements, mouse hovers, track pad
8878     * touches, scroll wheel movements and other input events.  The
8879     * {@link MotionEvent#getSource() source} of the motion event specifies
8880     * the class of input that was received.  Implementations of this method
8881     * must examine the bits in the source before processing the event.
8882     * The following code example shows how this is done.
8883     * </p><p>
8884     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8885     * are delivered to the view under the pointer.  All other generic motion events are
8886     * delivered to the focused view.
8887     * </p>
8888     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8889     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8890     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8891     *             // process the joystick movement...
8892     *             return true;
8893     *         }
8894     *     }
8895     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8896     *         switch (event.getAction()) {
8897     *             case MotionEvent.ACTION_HOVER_MOVE:
8898     *                 // process the mouse hover movement...
8899     *                 return true;
8900     *             case MotionEvent.ACTION_SCROLL:
8901     *                 // process the scroll wheel movement...
8902     *                 return true;
8903     *         }
8904     *     }
8905     *     return super.onGenericMotionEvent(event);
8906     * }</pre>
8907     *
8908     * @param event The generic motion event being processed.
8909     * @return True if the event was handled, false otherwise.
8910     */
8911    public boolean onGenericMotionEvent(MotionEvent event) {
8912        return false;
8913    }
8914
8915    /**
8916     * Implement this method to handle hover events.
8917     * <p>
8918     * This method is called whenever a pointer is hovering into, over, or out of the
8919     * bounds of a view and the view is not currently being touched.
8920     * Hover events are represented as pointer events with action
8921     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8922     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8923     * </p>
8924     * <ul>
8925     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8926     * when the pointer enters the bounds of the view.</li>
8927     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8928     * when the pointer has already entered the bounds of the view and has moved.</li>
8929     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8930     * when the pointer has exited the bounds of the view or when the pointer is
8931     * about to go down due to a button click, tap, or similar user action that
8932     * causes the view to be touched.</li>
8933     * </ul>
8934     * <p>
8935     * The view should implement this method to return true to indicate that it is
8936     * handling the hover event, such as by changing its drawable state.
8937     * </p><p>
8938     * The default implementation calls {@link #setHovered} to update the hovered state
8939     * of the view when a hover enter or hover exit event is received, if the view
8940     * is enabled and is clickable.  The default implementation also sends hover
8941     * accessibility events.
8942     * </p>
8943     *
8944     * @param event The motion event that describes the hover.
8945     * @return True if the view handled the hover event.
8946     *
8947     * @see #isHovered
8948     * @see #setHovered
8949     * @see #onHoverChanged
8950     */
8951    public boolean onHoverEvent(MotionEvent event) {
8952        // The root view may receive hover (or touch) events that are outside the bounds of
8953        // the window.  This code ensures that we only send accessibility events for
8954        // hovers that are actually within the bounds of the root view.
8955        final int action = event.getActionMasked();
8956        if (!mSendingHoverAccessibilityEvents) {
8957            if ((action == MotionEvent.ACTION_HOVER_ENTER
8958                    || action == MotionEvent.ACTION_HOVER_MOVE)
8959                    && !hasHoveredChild()
8960                    && pointInView(event.getX(), event.getY())) {
8961                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8962                mSendingHoverAccessibilityEvents = true;
8963            }
8964        } else {
8965            if (action == MotionEvent.ACTION_HOVER_EXIT
8966                    || (action == MotionEvent.ACTION_MOVE
8967                            && !pointInView(event.getX(), event.getY()))) {
8968                mSendingHoverAccessibilityEvents = false;
8969                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8970            }
8971        }
8972
8973        if (isHoverable()) {
8974            switch (action) {
8975                case MotionEvent.ACTION_HOVER_ENTER:
8976                    setHovered(true);
8977                    break;
8978                case MotionEvent.ACTION_HOVER_EXIT:
8979                    setHovered(false);
8980                    break;
8981            }
8982
8983            // Dispatch the event to onGenericMotionEvent before returning true.
8984            // This is to provide compatibility with existing applications that
8985            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8986            // break because of the new default handling for hoverable views
8987            // in onHoverEvent.
8988            // Note that onGenericMotionEvent will be called by default when
8989            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8990            dispatchGenericMotionEventInternal(event);
8991            // The event was already handled by calling setHovered(), so always
8992            // return true.
8993            return true;
8994        }
8995
8996        return false;
8997    }
8998
8999    /**
9000     * Returns true if the view should handle {@link #onHoverEvent}
9001     * by calling {@link #setHovered} to change its hovered state.
9002     *
9003     * @return True if the view is hoverable.
9004     */
9005    private boolean isHoverable() {
9006        final int viewFlags = mViewFlags;
9007        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9008            return false;
9009        }
9010
9011        return (viewFlags & CLICKABLE) == CLICKABLE
9012                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9013    }
9014
9015    /**
9016     * Returns true if the view is currently hovered.
9017     *
9018     * @return True if the view is currently hovered.
9019     *
9020     * @see #setHovered
9021     * @see #onHoverChanged
9022     */
9023    @ViewDebug.ExportedProperty
9024    public boolean isHovered() {
9025        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9026    }
9027
9028    /**
9029     * Sets whether the view is currently hovered.
9030     * <p>
9031     * Calling this method also changes the drawable state of the view.  This
9032     * enables the view to react to hover by using different drawable resources
9033     * to change its appearance.
9034     * </p><p>
9035     * The {@link #onHoverChanged} method is called when the hovered state changes.
9036     * </p>
9037     *
9038     * @param hovered True if the view is hovered.
9039     *
9040     * @see #isHovered
9041     * @see #onHoverChanged
9042     */
9043    public void setHovered(boolean hovered) {
9044        if (hovered) {
9045            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9046                mPrivateFlags |= PFLAG_HOVERED;
9047                refreshDrawableState();
9048                onHoverChanged(true);
9049            }
9050        } else {
9051            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9052                mPrivateFlags &= ~PFLAG_HOVERED;
9053                refreshDrawableState();
9054                onHoverChanged(false);
9055            }
9056        }
9057    }
9058
9059    /**
9060     * Implement this method to handle hover state changes.
9061     * <p>
9062     * This method is called whenever the hover state changes as a result of a
9063     * call to {@link #setHovered}.
9064     * </p>
9065     *
9066     * @param hovered The current hover state, as returned by {@link #isHovered}.
9067     *
9068     * @see #isHovered
9069     * @see #setHovered
9070     */
9071    public void onHoverChanged(boolean hovered) {
9072    }
9073
9074    /**
9075     * Implement this method to handle touch screen motion events.
9076     * <p>
9077     * If this method is used to detect click actions, it is recommended that
9078     * the actions be performed by implementing and calling
9079     * {@link #performClick()}. This will ensure consistent system behavior,
9080     * including:
9081     * <ul>
9082     * <li>obeying click sound preferences
9083     * <li>dispatching OnClickListener calls
9084     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9085     * accessibility features are enabled
9086     * </ul>
9087     *
9088     * @param event The motion event.
9089     * @return True if the event was handled, false otherwise.
9090     */
9091    public boolean onTouchEvent(MotionEvent event) {
9092        final float x = event.getX();
9093        final float y = event.getY();
9094        final int viewFlags = mViewFlags;
9095
9096        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9097            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9098                setPressed(false);
9099            }
9100            // A disabled view that is clickable still consumes the touch
9101            // events, it just doesn't respond to them.
9102            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9103                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9104        }
9105
9106        if (mTouchDelegate != null) {
9107            if (mTouchDelegate.onTouchEvent(event)) {
9108                return true;
9109            }
9110        }
9111
9112        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9113                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9114            switch (event.getAction()) {
9115                case MotionEvent.ACTION_UP:
9116                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9117                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9118                        // take focus if we don't have it already and we should in
9119                        // touch mode.
9120                        boolean focusTaken = false;
9121                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9122                            focusTaken = requestFocus();
9123                        }
9124
9125                        if (prepressed) {
9126                            // The button is being released before we actually
9127                            // showed it as pressed.  Make it show the pressed
9128                            // state now (before scheduling the click) to ensure
9129                            // the user sees it.
9130                            setPressed(true, x, y);
9131                       }
9132
9133                        if (!mHasPerformedLongPress) {
9134                            // This is a tap, so remove the longpress check
9135                            removeLongPressCallback();
9136
9137                            // Only perform take click actions if we were in the pressed state
9138                            if (!focusTaken) {
9139                                // Use a Runnable and post this rather than calling
9140                                // performClick directly. This lets other visual state
9141                                // of the view update before click actions start.
9142                                if (mPerformClick == null) {
9143                                    mPerformClick = new PerformClick();
9144                                }
9145                                if (!post(mPerformClick)) {
9146                                    performClick();
9147                                }
9148                            }
9149                        }
9150
9151                        if (mUnsetPressedState == null) {
9152                            mUnsetPressedState = new UnsetPressedState();
9153                        }
9154
9155                        if (prepressed) {
9156                            postDelayed(mUnsetPressedState,
9157                                    ViewConfiguration.getPressedStateDuration());
9158                        } else if (!post(mUnsetPressedState)) {
9159                            // If the post failed, unpress right now
9160                            mUnsetPressedState.run();
9161                        }
9162
9163                        removeTapCallback();
9164                    }
9165                    break;
9166
9167                case MotionEvent.ACTION_DOWN:
9168                    mHasPerformedLongPress = false;
9169
9170                    if (performButtonActionOnTouchDown(event)) {
9171                        break;
9172                    }
9173
9174                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9175                    boolean isInScrollingContainer = isInScrollingContainer();
9176
9177                    // For views inside a scrolling container, delay the pressed feedback for
9178                    // a short period in case this is a scroll.
9179                    if (isInScrollingContainer) {
9180                        mPrivateFlags |= PFLAG_PREPRESSED;
9181                        if (mPendingCheckForTap == null) {
9182                            mPendingCheckForTap = new CheckForTap();
9183                        }
9184                        mPendingCheckForTap.x = event.getX();
9185                        mPendingCheckForTap.y = event.getY();
9186                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9187                    } else {
9188                        // Not inside a scrolling container, so show the feedback right away
9189                        setPressed(true, x, y);
9190                        checkForLongClick(0);
9191                    }
9192                    break;
9193
9194                case MotionEvent.ACTION_CANCEL:
9195                    setPressed(false);
9196                    removeTapCallback();
9197                    removeLongPressCallback();
9198                    break;
9199
9200                case MotionEvent.ACTION_MOVE:
9201                    drawableHotspotChanged(x, y);
9202
9203                    // Be lenient about moving outside of buttons
9204                    if (!pointInView(x, y, mTouchSlop)) {
9205                        // Outside button
9206                        removeTapCallback();
9207                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9208                            // Remove any future long press/tap checks
9209                            removeLongPressCallback();
9210
9211                            setPressed(false);
9212                        }
9213                    }
9214                    break;
9215            }
9216
9217            return true;
9218        }
9219
9220        return false;
9221    }
9222
9223    /**
9224     * @hide
9225     */
9226    public boolean isInScrollingContainer() {
9227        ViewParent p = getParent();
9228        while (p != null && p instanceof ViewGroup) {
9229            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9230                return true;
9231            }
9232            p = p.getParent();
9233        }
9234        return false;
9235    }
9236
9237    /**
9238     * Remove the longpress detection timer.
9239     */
9240    private void removeLongPressCallback() {
9241        if (mPendingCheckForLongPress != null) {
9242          removeCallbacks(mPendingCheckForLongPress);
9243        }
9244    }
9245
9246    /**
9247     * Remove the pending click action
9248     */
9249    private void removePerformClickCallback() {
9250        if (mPerformClick != null) {
9251            removeCallbacks(mPerformClick);
9252        }
9253    }
9254
9255    /**
9256     * Remove the prepress detection timer.
9257     */
9258    private void removeUnsetPressCallback() {
9259        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9260            setPressed(false);
9261            removeCallbacks(mUnsetPressedState);
9262        }
9263    }
9264
9265    /**
9266     * Remove the tap detection timer.
9267     */
9268    private void removeTapCallback() {
9269        if (mPendingCheckForTap != null) {
9270            mPrivateFlags &= ~PFLAG_PREPRESSED;
9271            removeCallbacks(mPendingCheckForTap);
9272        }
9273    }
9274
9275    /**
9276     * Cancels a pending long press.  Your subclass can use this if you
9277     * want the context menu to come up if the user presses and holds
9278     * at the same place, but you don't want it to come up if they press
9279     * and then move around enough to cause scrolling.
9280     */
9281    public void cancelLongPress() {
9282        removeLongPressCallback();
9283
9284        /*
9285         * The prepressed state handled by the tap callback is a display
9286         * construct, but the tap callback will post a long press callback
9287         * less its own timeout. Remove it here.
9288         */
9289        removeTapCallback();
9290    }
9291
9292    /**
9293     * Remove the pending callback for sending a
9294     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9295     */
9296    private void removeSendViewScrolledAccessibilityEventCallback() {
9297        if (mSendViewScrolledAccessibilityEvent != null) {
9298            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9299            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9300        }
9301    }
9302
9303    /**
9304     * Sets the TouchDelegate for this View.
9305     */
9306    public void setTouchDelegate(TouchDelegate delegate) {
9307        mTouchDelegate = delegate;
9308    }
9309
9310    /**
9311     * Gets the TouchDelegate for this View.
9312     */
9313    public TouchDelegate getTouchDelegate() {
9314        return mTouchDelegate;
9315    }
9316
9317    /**
9318     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9319     *
9320     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9321     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9322     * available. This method should only be called for touch events.
9323     *
9324     * <p class="note">This api is not intended for most applications. Buffered dispatch
9325     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9326     * streams will not improve your input latency. Side effects include: increased latency,
9327     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9328     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9329     * you.</p>
9330     */
9331    public final void requestUnbufferedDispatch(MotionEvent event) {
9332        final int action = event.getAction();
9333        if (mAttachInfo == null
9334                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9335                || !event.isTouchEvent()) {
9336            return;
9337        }
9338        mAttachInfo.mUnbufferedDispatchRequested = true;
9339    }
9340
9341    /**
9342     * Set flags controlling behavior of this view.
9343     *
9344     * @param flags Constant indicating the value which should be set
9345     * @param mask Constant indicating the bit range that should be changed
9346     */
9347    void setFlags(int flags, int mask) {
9348        final boolean accessibilityEnabled =
9349                AccessibilityManager.getInstance(mContext).isEnabled();
9350        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9351
9352        int old = mViewFlags;
9353        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9354
9355        int changed = mViewFlags ^ old;
9356        if (changed == 0) {
9357            return;
9358        }
9359        int privateFlags = mPrivateFlags;
9360
9361        /* Check if the FOCUSABLE bit has changed */
9362        if (((changed & FOCUSABLE_MASK) != 0) &&
9363                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9364            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9365                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9366                /* Give up focus if we are no longer focusable */
9367                clearFocus();
9368            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9369                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9370                /*
9371                 * Tell the view system that we are now available to take focus
9372                 * if no one else already has it.
9373                 */
9374                if (mParent != null) mParent.focusableViewAvailable(this);
9375            }
9376        }
9377
9378        final int newVisibility = flags & VISIBILITY_MASK;
9379        if (newVisibility == VISIBLE) {
9380            if ((changed & VISIBILITY_MASK) != 0) {
9381                /*
9382                 * If this view is becoming visible, invalidate it in case it changed while
9383                 * it was not visible. Marking it drawn ensures that the invalidation will
9384                 * go through.
9385                 */
9386                mPrivateFlags |= PFLAG_DRAWN;
9387                invalidate(true);
9388
9389                needGlobalAttributesUpdate(true);
9390
9391                // a view becoming visible is worth notifying the parent
9392                // about in case nothing has focus.  even if this specific view
9393                // isn't focusable, it may contain something that is, so let
9394                // the root view try to give this focus if nothing else does.
9395                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9396                    mParent.focusableViewAvailable(this);
9397                }
9398            }
9399        }
9400
9401        /* Check if the GONE bit has changed */
9402        if ((changed & GONE) != 0) {
9403            needGlobalAttributesUpdate(false);
9404            requestLayout();
9405
9406            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9407                if (hasFocus()) clearFocus();
9408                clearAccessibilityFocus();
9409                destroyDrawingCache();
9410                if (mParent instanceof View) {
9411                    // GONE views noop invalidation, so invalidate the parent
9412                    ((View) mParent).invalidate(true);
9413                }
9414                // Mark the view drawn to ensure that it gets invalidated properly the next
9415                // time it is visible and gets invalidated
9416                mPrivateFlags |= PFLAG_DRAWN;
9417            }
9418            if (mAttachInfo != null) {
9419                mAttachInfo.mViewVisibilityChanged = true;
9420            }
9421        }
9422
9423        /* Check if the VISIBLE bit has changed */
9424        if ((changed & INVISIBLE) != 0) {
9425            needGlobalAttributesUpdate(false);
9426            /*
9427             * If this view is becoming invisible, set the DRAWN flag so that
9428             * the next invalidate() will not be skipped.
9429             */
9430            mPrivateFlags |= PFLAG_DRAWN;
9431
9432            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9433                // root view becoming invisible shouldn't clear focus and accessibility focus
9434                if (getRootView() != this) {
9435                    if (hasFocus()) clearFocus();
9436                    clearAccessibilityFocus();
9437                }
9438            }
9439            if (mAttachInfo != null) {
9440                mAttachInfo.mViewVisibilityChanged = true;
9441            }
9442        }
9443
9444        if ((changed & VISIBILITY_MASK) != 0) {
9445            // If the view is invisible, cleanup its display list to free up resources
9446            if (newVisibility != VISIBLE && mAttachInfo != null) {
9447                cleanupDraw();
9448            }
9449
9450            if (mParent instanceof ViewGroup) {
9451                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9452                        (changed & VISIBILITY_MASK), newVisibility);
9453                ((View) mParent).invalidate(true);
9454            } else if (mParent != null) {
9455                mParent.invalidateChild(this, null);
9456            }
9457            dispatchVisibilityChanged(this, newVisibility);
9458
9459            notifySubtreeAccessibilityStateChangedIfNeeded();
9460        }
9461
9462        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9463            destroyDrawingCache();
9464        }
9465
9466        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9467            destroyDrawingCache();
9468            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9469            invalidateParentCaches();
9470        }
9471
9472        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9473            destroyDrawingCache();
9474            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9475        }
9476
9477        if ((changed & DRAW_MASK) != 0) {
9478            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9479                if (mBackground != null) {
9480                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9481                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9482                } else {
9483                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9484                }
9485            } else {
9486                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9487            }
9488            requestLayout();
9489            invalidate(true);
9490        }
9491
9492        if ((changed & KEEP_SCREEN_ON) != 0) {
9493            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9494                mParent.recomputeViewAttributes(this);
9495            }
9496        }
9497
9498        if (accessibilityEnabled) {
9499            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9500                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9501                if (oldIncludeForAccessibility != includeForAccessibility()) {
9502                    notifySubtreeAccessibilityStateChangedIfNeeded();
9503                } else {
9504                    notifyViewAccessibilityStateChangedIfNeeded(
9505                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9506                }
9507            } else if ((changed & ENABLED_MASK) != 0) {
9508                notifyViewAccessibilityStateChangedIfNeeded(
9509                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9510            }
9511        }
9512    }
9513
9514    /**
9515     * Change the view's z order in the tree, so it's on top of other sibling
9516     * views. This ordering change may affect layout, if the parent container
9517     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9518     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9519     * method should be followed by calls to {@link #requestLayout()} and
9520     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9521     * with the new child ordering.
9522     *
9523     * @see ViewGroup#bringChildToFront(View)
9524     */
9525    public void bringToFront() {
9526        if (mParent != null) {
9527            mParent.bringChildToFront(this);
9528        }
9529    }
9530
9531    /**
9532     * This is called in response to an internal scroll in this view (i.e., the
9533     * view scrolled its own contents). This is typically as a result of
9534     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9535     * called.
9536     *
9537     * @param l Current horizontal scroll origin.
9538     * @param t Current vertical scroll origin.
9539     * @param oldl Previous horizontal scroll origin.
9540     * @param oldt Previous vertical scroll origin.
9541     */
9542    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9543        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9544            postSendViewScrolledAccessibilityEventCallback();
9545        }
9546
9547        mBackgroundSizeChanged = true;
9548
9549        final AttachInfo ai = mAttachInfo;
9550        if (ai != null) {
9551            ai.mViewScrollChanged = true;
9552        }
9553    }
9554
9555    /**
9556     * Interface definition for a callback to be invoked when the layout bounds of a view
9557     * changes due to layout processing.
9558     */
9559    public interface OnLayoutChangeListener {
9560        /**
9561         * Called when the layout bounds of a view changes due to layout processing.
9562         *
9563         * @param v The view whose bounds have changed.
9564         * @param left The new value of the view's left property.
9565         * @param top The new value of the view's top property.
9566         * @param right The new value of the view's right property.
9567         * @param bottom The new value of the view's bottom property.
9568         * @param oldLeft The previous value of the view's left property.
9569         * @param oldTop The previous value of the view's top property.
9570         * @param oldRight The previous value of the view's right property.
9571         * @param oldBottom The previous value of the view's bottom property.
9572         */
9573        void onLayoutChange(View v, int left, int top, int right, int bottom,
9574            int oldLeft, int oldTop, int oldRight, int oldBottom);
9575    }
9576
9577    /**
9578     * This is called during layout when the size of this view has changed. If
9579     * you were just added to the view hierarchy, you're called with the old
9580     * values of 0.
9581     *
9582     * @param w Current width of this view.
9583     * @param h Current height of this view.
9584     * @param oldw Old width of this view.
9585     * @param oldh Old height of this view.
9586     */
9587    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9588    }
9589
9590    /**
9591     * Called by draw to draw the child views. This may be overridden
9592     * by derived classes to gain control just before its children are drawn
9593     * (but after its own view has been drawn).
9594     * @param canvas the canvas on which to draw the view
9595     */
9596    protected void dispatchDraw(Canvas canvas) {
9597
9598    }
9599
9600    /**
9601     * Gets the parent of this view. Note that the parent is a
9602     * ViewParent and not necessarily a View.
9603     *
9604     * @return Parent of this view.
9605     */
9606    public final ViewParent getParent() {
9607        return mParent;
9608    }
9609
9610    /**
9611     * Set the horizontal scrolled position of your view. This will cause a call to
9612     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9613     * invalidated.
9614     * @param value the x position to scroll to
9615     */
9616    public void setScrollX(int value) {
9617        scrollTo(value, mScrollY);
9618    }
9619
9620    /**
9621     * Set the vertical scrolled position of your view. This will cause a call to
9622     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9623     * invalidated.
9624     * @param value the y position to scroll to
9625     */
9626    public void setScrollY(int value) {
9627        scrollTo(mScrollX, value);
9628    }
9629
9630    /**
9631     * Return the scrolled left position of this view. This is the left edge of
9632     * the displayed part of your view. You do not need to draw any pixels
9633     * farther left, since those are outside of the frame of your view on
9634     * screen.
9635     *
9636     * @return The left edge of the displayed part of your view, in pixels.
9637     */
9638    public final int getScrollX() {
9639        return mScrollX;
9640    }
9641
9642    /**
9643     * Return the scrolled top position of this view. This is the top edge of
9644     * the displayed part of your view. You do not need to draw any pixels above
9645     * it, since those are outside of the frame of your view on screen.
9646     *
9647     * @return The top edge of the displayed part of your view, in pixels.
9648     */
9649    public final int getScrollY() {
9650        return mScrollY;
9651    }
9652
9653    /**
9654     * Return the width of the your view.
9655     *
9656     * @return The width of your view, in pixels.
9657     */
9658    @ViewDebug.ExportedProperty(category = "layout")
9659    public final int getWidth() {
9660        return mRight - mLeft;
9661    }
9662
9663    /**
9664     * Return the height of your view.
9665     *
9666     * @return The height of your view, in pixels.
9667     */
9668    @ViewDebug.ExportedProperty(category = "layout")
9669    public final int getHeight() {
9670        return mBottom - mTop;
9671    }
9672
9673    /**
9674     * Return the visible drawing bounds of your view. Fills in the output
9675     * rectangle with the values from getScrollX(), getScrollY(),
9676     * getWidth(), and getHeight(). These bounds do not account for any
9677     * transformation properties currently set on the view, such as
9678     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9679     *
9680     * @param outRect The (scrolled) drawing bounds of the view.
9681     */
9682    public void getDrawingRect(Rect outRect) {
9683        outRect.left = mScrollX;
9684        outRect.top = mScrollY;
9685        outRect.right = mScrollX + (mRight - mLeft);
9686        outRect.bottom = mScrollY + (mBottom - mTop);
9687    }
9688
9689    /**
9690     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9691     * raw width component (that is the result is masked by
9692     * {@link #MEASURED_SIZE_MASK}).
9693     *
9694     * @return The raw measured width of this view.
9695     */
9696    public final int getMeasuredWidth() {
9697        return mMeasuredWidth & MEASURED_SIZE_MASK;
9698    }
9699
9700    /**
9701     * Return the full width measurement information for this view as computed
9702     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9703     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9704     * This should be used during measurement and layout calculations only. Use
9705     * {@link #getWidth()} to see how wide a view is after layout.
9706     *
9707     * @return The measured width of this view as a bit mask.
9708     */
9709    public final int getMeasuredWidthAndState() {
9710        return mMeasuredWidth;
9711    }
9712
9713    /**
9714     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9715     * raw width component (that is the result is masked by
9716     * {@link #MEASURED_SIZE_MASK}).
9717     *
9718     * @return The raw measured height of this view.
9719     */
9720    public final int getMeasuredHeight() {
9721        return mMeasuredHeight & MEASURED_SIZE_MASK;
9722    }
9723
9724    /**
9725     * Return the full height measurement information for this view as computed
9726     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9727     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9728     * This should be used during measurement and layout calculations only. Use
9729     * {@link #getHeight()} to see how wide a view is after layout.
9730     *
9731     * @return The measured width of this view as a bit mask.
9732     */
9733    public final int getMeasuredHeightAndState() {
9734        return mMeasuredHeight;
9735    }
9736
9737    /**
9738     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9739     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9740     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9741     * and the height component is at the shifted bits
9742     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9743     */
9744    public final int getMeasuredState() {
9745        return (mMeasuredWidth&MEASURED_STATE_MASK)
9746                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9747                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9748    }
9749
9750    /**
9751     * The transform matrix of this view, which is calculated based on the current
9752     * rotation, scale, and pivot properties.
9753     *
9754     * @see #getRotation()
9755     * @see #getScaleX()
9756     * @see #getScaleY()
9757     * @see #getPivotX()
9758     * @see #getPivotY()
9759     * @return The current transform matrix for the view
9760     */
9761    public Matrix getMatrix() {
9762        ensureTransformationInfo();
9763        final Matrix matrix = mTransformationInfo.mMatrix;
9764        mRenderNode.getMatrix(matrix);
9765        return matrix;
9766    }
9767
9768    /**
9769     * Returns true if the transform matrix is the identity matrix.
9770     * Recomputes the matrix if necessary.
9771     *
9772     * @return True if the transform matrix is the identity matrix, false otherwise.
9773     */
9774    final boolean hasIdentityMatrix() {
9775        return mRenderNode.hasIdentityMatrix();
9776    }
9777
9778    void ensureTransformationInfo() {
9779        if (mTransformationInfo == null) {
9780            mTransformationInfo = new TransformationInfo();
9781        }
9782    }
9783
9784   /**
9785     * Utility method to retrieve the inverse of the current mMatrix property.
9786     * We cache the matrix to avoid recalculating it when transform properties
9787     * have not changed.
9788     *
9789     * @return The inverse of the current matrix of this view.
9790     * @hide
9791     */
9792    public final Matrix getInverseMatrix() {
9793        ensureTransformationInfo();
9794        if (mTransformationInfo.mInverseMatrix == null) {
9795            mTransformationInfo.mInverseMatrix = new Matrix();
9796        }
9797        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9798        mRenderNode.getInverseMatrix(matrix);
9799        return matrix;
9800    }
9801
9802    /**
9803     * Gets the distance along the Z axis from the camera to this view.
9804     *
9805     * @see #setCameraDistance(float)
9806     *
9807     * @return The distance along the Z axis.
9808     */
9809    public float getCameraDistance() {
9810        final float dpi = mResources.getDisplayMetrics().densityDpi;
9811        return -(mRenderNode.getCameraDistance() * dpi);
9812    }
9813
9814    /**
9815     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9816     * views are drawn) from the camera to this view. The camera's distance
9817     * affects 3D transformations, for instance rotations around the X and Y
9818     * axis. If the rotationX or rotationY properties are changed and this view is
9819     * large (more than half the size of the screen), it is recommended to always
9820     * use a camera distance that's greater than the height (X axis rotation) or
9821     * the width (Y axis rotation) of this view.</p>
9822     *
9823     * <p>The distance of the camera from the view plane can have an affect on the
9824     * perspective distortion of the view when it is rotated around the x or y axis.
9825     * For example, a large distance will result in a large viewing angle, and there
9826     * will not be much perspective distortion of the view as it rotates. A short
9827     * distance may cause much more perspective distortion upon rotation, and can
9828     * also result in some drawing artifacts if the rotated view ends up partially
9829     * behind the camera (which is why the recommendation is to use a distance at
9830     * least as far as the size of the view, if the view is to be rotated.)</p>
9831     *
9832     * <p>The distance is expressed in "depth pixels." The default distance depends
9833     * on the screen density. For instance, on a medium density display, the
9834     * default distance is 1280. On a high density display, the default distance
9835     * is 1920.</p>
9836     *
9837     * <p>If you want to specify a distance that leads to visually consistent
9838     * results across various densities, use the following formula:</p>
9839     * <pre>
9840     * float scale = context.getResources().getDisplayMetrics().density;
9841     * view.setCameraDistance(distance * scale);
9842     * </pre>
9843     *
9844     * <p>The density scale factor of a high density display is 1.5,
9845     * and 1920 = 1280 * 1.5.</p>
9846     *
9847     * @param distance The distance in "depth pixels", if negative the opposite
9848     *        value is used
9849     *
9850     * @see #setRotationX(float)
9851     * @see #setRotationY(float)
9852     */
9853    public void setCameraDistance(float distance) {
9854        final float dpi = mResources.getDisplayMetrics().densityDpi;
9855
9856        invalidateViewProperty(true, false);
9857        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9858        invalidateViewProperty(false, false);
9859
9860        invalidateParentIfNeededAndWasQuickRejected();
9861    }
9862
9863    /**
9864     * The degrees that the view is rotated around the pivot point.
9865     *
9866     * @see #setRotation(float)
9867     * @see #getPivotX()
9868     * @see #getPivotY()
9869     *
9870     * @return The degrees of rotation.
9871     */
9872    @ViewDebug.ExportedProperty(category = "drawing")
9873    public float getRotation() {
9874        return mRenderNode.getRotation();
9875    }
9876
9877    /**
9878     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9879     * result in clockwise rotation.
9880     *
9881     * @param rotation The degrees of rotation.
9882     *
9883     * @see #getRotation()
9884     * @see #getPivotX()
9885     * @see #getPivotY()
9886     * @see #setRotationX(float)
9887     * @see #setRotationY(float)
9888     *
9889     * @attr ref android.R.styleable#View_rotation
9890     */
9891    public void setRotation(float rotation) {
9892        if (rotation != getRotation()) {
9893            // Double-invalidation is necessary to capture view's old and new areas
9894            invalidateViewProperty(true, false);
9895            mRenderNode.setRotation(rotation);
9896            invalidateViewProperty(false, true);
9897
9898            invalidateParentIfNeededAndWasQuickRejected();
9899            notifySubtreeAccessibilityStateChangedIfNeeded();
9900        }
9901    }
9902
9903    /**
9904     * The degrees that the view is rotated around the vertical axis through the pivot point.
9905     *
9906     * @see #getPivotX()
9907     * @see #getPivotY()
9908     * @see #setRotationY(float)
9909     *
9910     * @return The degrees of Y rotation.
9911     */
9912    @ViewDebug.ExportedProperty(category = "drawing")
9913    public float getRotationY() {
9914        return mRenderNode.getRotationY();
9915    }
9916
9917    /**
9918     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9919     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9920     * down the y axis.
9921     *
9922     * When rotating large views, it is recommended to adjust the camera distance
9923     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9924     *
9925     * @param rotationY The degrees of Y rotation.
9926     *
9927     * @see #getRotationY()
9928     * @see #getPivotX()
9929     * @see #getPivotY()
9930     * @see #setRotation(float)
9931     * @see #setRotationX(float)
9932     * @see #setCameraDistance(float)
9933     *
9934     * @attr ref android.R.styleable#View_rotationY
9935     */
9936    public void setRotationY(float rotationY) {
9937        if (rotationY != getRotationY()) {
9938            invalidateViewProperty(true, false);
9939            mRenderNode.setRotationY(rotationY);
9940            invalidateViewProperty(false, true);
9941
9942            invalidateParentIfNeededAndWasQuickRejected();
9943            notifySubtreeAccessibilityStateChangedIfNeeded();
9944        }
9945    }
9946
9947    /**
9948     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9949     *
9950     * @see #getPivotX()
9951     * @see #getPivotY()
9952     * @see #setRotationX(float)
9953     *
9954     * @return The degrees of X rotation.
9955     */
9956    @ViewDebug.ExportedProperty(category = "drawing")
9957    public float getRotationX() {
9958        return mRenderNode.getRotationX();
9959    }
9960
9961    /**
9962     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9963     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9964     * x axis.
9965     *
9966     * When rotating large views, it is recommended to adjust the camera distance
9967     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9968     *
9969     * @param rotationX The degrees of X rotation.
9970     *
9971     * @see #getRotationX()
9972     * @see #getPivotX()
9973     * @see #getPivotY()
9974     * @see #setRotation(float)
9975     * @see #setRotationY(float)
9976     * @see #setCameraDistance(float)
9977     *
9978     * @attr ref android.R.styleable#View_rotationX
9979     */
9980    public void setRotationX(float rotationX) {
9981        if (rotationX != getRotationX()) {
9982            invalidateViewProperty(true, false);
9983            mRenderNode.setRotationX(rotationX);
9984            invalidateViewProperty(false, true);
9985
9986            invalidateParentIfNeededAndWasQuickRejected();
9987            notifySubtreeAccessibilityStateChangedIfNeeded();
9988        }
9989    }
9990
9991    /**
9992     * The amount that the view is scaled in x around the pivot point, as a proportion of
9993     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9994     *
9995     * <p>By default, this is 1.0f.
9996     *
9997     * @see #getPivotX()
9998     * @see #getPivotY()
9999     * @return The scaling factor.
10000     */
10001    @ViewDebug.ExportedProperty(category = "drawing")
10002    public float getScaleX() {
10003        return mRenderNode.getScaleX();
10004    }
10005
10006    /**
10007     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10008     * the view's unscaled width. A value of 1 means that no scaling is applied.
10009     *
10010     * @param scaleX The scaling factor.
10011     * @see #getPivotX()
10012     * @see #getPivotY()
10013     *
10014     * @attr ref android.R.styleable#View_scaleX
10015     */
10016    public void setScaleX(float scaleX) {
10017        if (scaleX != getScaleX()) {
10018            invalidateViewProperty(true, false);
10019            mRenderNode.setScaleX(scaleX);
10020            invalidateViewProperty(false, true);
10021
10022            invalidateParentIfNeededAndWasQuickRejected();
10023            notifySubtreeAccessibilityStateChangedIfNeeded();
10024        }
10025    }
10026
10027    /**
10028     * The amount that the view is scaled in y around the pivot point, as a proportion of
10029     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10030     *
10031     * <p>By default, this is 1.0f.
10032     *
10033     * @see #getPivotX()
10034     * @see #getPivotY()
10035     * @return The scaling factor.
10036     */
10037    @ViewDebug.ExportedProperty(category = "drawing")
10038    public float getScaleY() {
10039        return mRenderNode.getScaleY();
10040    }
10041
10042    /**
10043     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10044     * the view's unscaled width. A value of 1 means that no scaling is applied.
10045     *
10046     * @param scaleY The scaling factor.
10047     * @see #getPivotX()
10048     * @see #getPivotY()
10049     *
10050     * @attr ref android.R.styleable#View_scaleY
10051     */
10052    public void setScaleY(float scaleY) {
10053        if (scaleY != getScaleY()) {
10054            invalidateViewProperty(true, false);
10055            mRenderNode.setScaleY(scaleY);
10056            invalidateViewProperty(false, true);
10057
10058            invalidateParentIfNeededAndWasQuickRejected();
10059            notifySubtreeAccessibilityStateChangedIfNeeded();
10060        }
10061    }
10062
10063    /**
10064     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10065     * and {@link #setScaleX(float) scaled}.
10066     *
10067     * @see #getRotation()
10068     * @see #getScaleX()
10069     * @see #getScaleY()
10070     * @see #getPivotY()
10071     * @return The x location of the pivot point.
10072     *
10073     * @attr ref android.R.styleable#View_transformPivotX
10074     */
10075    @ViewDebug.ExportedProperty(category = "drawing")
10076    public float getPivotX() {
10077        return mRenderNode.getPivotX();
10078    }
10079
10080    /**
10081     * Sets the x location of the point around which the view is
10082     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10083     * By default, the pivot point is centered on the object.
10084     * Setting this property disables this behavior and causes the view to use only the
10085     * explicitly set pivotX and pivotY values.
10086     *
10087     * @param pivotX The x location of the pivot point.
10088     * @see #getRotation()
10089     * @see #getScaleX()
10090     * @see #getScaleY()
10091     * @see #getPivotY()
10092     *
10093     * @attr ref android.R.styleable#View_transformPivotX
10094     */
10095    public void setPivotX(float pivotX) {
10096        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10097            invalidateViewProperty(true, false);
10098            mRenderNode.setPivotX(pivotX);
10099            invalidateViewProperty(false, true);
10100
10101            invalidateParentIfNeededAndWasQuickRejected();
10102        }
10103    }
10104
10105    /**
10106     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10107     * and {@link #setScaleY(float) scaled}.
10108     *
10109     * @see #getRotation()
10110     * @see #getScaleX()
10111     * @see #getScaleY()
10112     * @see #getPivotY()
10113     * @return The y location of the pivot point.
10114     *
10115     * @attr ref android.R.styleable#View_transformPivotY
10116     */
10117    @ViewDebug.ExportedProperty(category = "drawing")
10118    public float getPivotY() {
10119        return mRenderNode.getPivotY();
10120    }
10121
10122    /**
10123     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10124     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10125     * Setting this property disables this behavior and causes the view to use only the
10126     * explicitly set pivotX and pivotY values.
10127     *
10128     * @param pivotY The y location of the pivot point.
10129     * @see #getRotation()
10130     * @see #getScaleX()
10131     * @see #getScaleY()
10132     * @see #getPivotY()
10133     *
10134     * @attr ref android.R.styleable#View_transformPivotY
10135     */
10136    public void setPivotY(float pivotY) {
10137        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10138            invalidateViewProperty(true, false);
10139            mRenderNode.setPivotY(pivotY);
10140            invalidateViewProperty(false, true);
10141
10142            invalidateParentIfNeededAndWasQuickRejected();
10143        }
10144    }
10145
10146    /**
10147     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10148     * completely transparent and 1 means the view is completely opaque.
10149     *
10150     * <p>By default this is 1.0f.
10151     * @return The opacity of the view.
10152     */
10153    @ViewDebug.ExportedProperty(category = "drawing")
10154    public float getAlpha() {
10155        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10156    }
10157
10158    /**
10159     * Returns whether this View has content which overlaps.
10160     *
10161     * <p>This function, intended to be overridden by specific View types, is an optimization when
10162     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10163     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10164     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10165     * directly. An example of overlapping rendering is a TextView with a background image, such as
10166     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10167     * ImageView with only the foreground image. The default implementation returns true; subclasses
10168     * should override if they have cases which can be optimized.</p>
10169     *
10170     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10171     * necessitates that a View return true if it uses the methods internally without passing the
10172     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10173     *
10174     * @return true if the content in this view might overlap, false otherwise.
10175     */
10176    public boolean hasOverlappingRendering() {
10177        return true;
10178    }
10179
10180    /**
10181     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10182     * completely transparent and 1 means the view is completely opaque.</p>
10183     *
10184     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10185     * performance implications, especially for large views. It is best to use the alpha property
10186     * sparingly and transiently, as in the case of fading animations.</p>
10187     *
10188     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10189     * strongly recommended for performance reasons to either override
10190     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10191     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10192     *
10193     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10194     * responsible for applying the opacity itself.</p>
10195     *
10196     * <p>Note that if the view is backed by a
10197     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10198     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10199     * 1.0 will supercede the alpha of the layer paint.</p>
10200     *
10201     * @param alpha The opacity of the view.
10202     *
10203     * @see #hasOverlappingRendering()
10204     * @see #setLayerType(int, android.graphics.Paint)
10205     *
10206     * @attr ref android.R.styleable#View_alpha
10207     */
10208    public void setAlpha(float alpha) {
10209        ensureTransformationInfo();
10210        if (mTransformationInfo.mAlpha != alpha) {
10211            mTransformationInfo.mAlpha = alpha;
10212            if (onSetAlpha((int) (alpha * 255))) {
10213                mPrivateFlags |= PFLAG_ALPHA_SET;
10214                // subclass is handling alpha - don't optimize rendering cache invalidation
10215                invalidateParentCaches();
10216                invalidate(true);
10217            } else {
10218                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10219                invalidateViewProperty(true, false);
10220                mRenderNode.setAlpha(getFinalAlpha());
10221                notifyViewAccessibilityStateChangedIfNeeded(
10222                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10223            }
10224        }
10225    }
10226
10227    /**
10228     * Faster version of setAlpha() which performs the same steps except there are
10229     * no calls to invalidate(). The caller of this function should perform proper invalidation
10230     * on the parent and this object. The return value indicates whether the subclass handles
10231     * alpha (the return value for onSetAlpha()).
10232     *
10233     * @param alpha The new value for the alpha property
10234     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10235     *         the new value for the alpha property is different from the old value
10236     */
10237    boolean setAlphaNoInvalidation(float alpha) {
10238        ensureTransformationInfo();
10239        if (mTransformationInfo.mAlpha != alpha) {
10240            mTransformationInfo.mAlpha = alpha;
10241            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10242            if (subclassHandlesAlpha) {
10243                mPrivateFlags |= PFLAG_ALPHA_SET;
10244                return true;
10245            } else {
10246                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10247                mRenderNode.setAlpha(getFinalAlpha());
10248            }
10249        }
10250        return false;
10251    }
10252
10253    /**
10254     * This property is hidden and intended only for use by the Fade transition, which
10255     * animates it to produce a visual translucency that does not side-effect (or get
10256     * affected by) the real alpha property. This value is composited with the other
10257     * alpha value (and the AlphaAnimation value, when that is present) to produce
10258     * a final visual translucency result, which is what is passed into the DisplayList.
10259     *
10260     * @hide
10261     */
10262    public void setTransitionAlpha(float alpha) {
10263        ensureTransformationInfo();
10264        if (mTransformationInfo.mTransitionAlpha != alpha) {
10265            mTransformationInfo.mTransitionAlpha = alpha;
10266            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10267            invalidateViewProperty(true, false);
10268            mRenderNode.setAlpha(getFinalAlpha());
10269        }
10270    }
10271
10272    /**
10273     * Calculates the visual alpha of this view, which is a combination of the actual
10274     * alpha value and the transitionAlpha value (if set).
10275     */
10276    private float getFinalAlpha() {
10277        if (mTransformationInfo != null) {
10278            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10279        }
10280        return 1;
10281    }
10282
10283    /**
10284     * This property is hidden and intended only for use by the Fade transition, which
10285     * animates it to produce a visual translucency that does not side-effect (or get
10286     * affected by) the real alpha property. This value is composited with the other
10287     * alpha value (and the AlphaAnimation value, when that is present) to produce
10288     * a final visual translucency result, which is what is passed into the DisplayList.
10289     *
10290     * @hide
10291     */
10292    @ViewDebug.ExportedProperty(category = "drawing")
10293    public float getTransitionAlpha() {
10294        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10295    }
10296
10297    /**
10298     * Top position of this view relative to its parent.
10299     *
10300     * @return The top of this view, in pixels.
10301     */
10302    @ViewDebug.CapturedViewProperty
10303    public final int getTop() {
10304        return mTop;
10305    }
10306
10307    /**
10308     * Sets the top position of this view relative to its parent. This method is meant to be called
10309     * by the layout system and should not generally be called otherwise, because the property
10310     * may be changed at any time by the layout.
10311     *
10312     * @param top The top of this view, in pixels.
10313     */
10314    public final void setTop(int top) {
10315        if (top != mTop) {
10316            final boolean matrixIsIdentity = hasIdentityMatrix();
10317            if (matrixIsIdentity) {
10318                if (mAttachInfo != null) {
10319                    int minTop;
10320                    int yLoc;
10321                    if (top < mTop) {
10322                        minTop = top;
10323                        yLoc = top - mTop;
10324                    } else {
10325                        minTop = mTop;
10326                        yLoc = 0;
10327                    }
10328                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10329                }
10330            } else {
10331                // Double-invalidation is necessary to capture view's old and new areas
10332                invalidate(true);
10333            }
10334
10335            int width = mRight - mLeft;
10336            int oldHeight = mBottom - mTop;
10337
10338            mTop = top;
10339            mRenderNode.setTop(mTop);
10340
10341            sizeChange(width, mBottom - mTop, width, oldHeight);
10342
10343            if (!matrixIsIdentity) {
10344                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10345                invalidate(true);
10346            }
10347            mBackgroundSizeChanged = true;
10348            invalidateParentIfNeeded();
10349            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10350                // View was rejected last time it was drawn by its parent; this may have changed
10351                invalidateParentIfNeeded();
10352            }
10353        }
10354    }
10355
10356    /**
10357     * Bottom position of this view relative to its parent.
10358     *
10359     * @return The bottom of this view, in pixels.
10360     */
10361    @ViewDebug.CapturedViewProperty
10362    public final int getBottom() {
10363        return mBottom;
10364    }
10365
10366    /**
10367     * True if this view has changed since the last time being drawn.
10368     *
10369     * @return The dirty state of this view.
10370     */
10371    public boolean isDirty() {
10372        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10373    }
10374
10375    /**
10376     * Sets the bottom position of this view relative to its parent. This method is meant to be
10377     * called by the layout system and should not generally be called otherwise, because the
10378     * property may be changed at any time by the layout.
10379     *
10380     * @param bottom The bottom of this view, in pixels.
10381     */
10382    public final void setBottom(int bottom) {
10383        if (bottom != mBottom) {
10384            final boolean matrixIsIdentity = hasIdentityMatrix();
10385            if (matrixIsIdentity) {
10386                if (mAttachInfo != null) {
10387                    int maxBottom;
10388                    if (bottom < mBottom) {
10389                        maxBottom = mBottom;
10390                    } else {
10391                        maxBottom = bottom;
10392                    }
10393                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10394                }
10395            } else {
10396                // Double-invalidation is necessary to capture view's old and new areas
10397                invalidate(true);
10398            }
10399
10400            int width = mRight - mLeft;
10401            int oldHeight = mBottom - mTop;
10402
10403            mBottom = bottom;
10404            mRenderNode.setBottom(mBottom);
10405
10406            sizeChange(width, mBottom - mTop, width, oldHeight);
10407
10408            if (!matrixIsIdentity) {
10409                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10410                invalidate(true);
10411            }
10412            mBackgroundSizeChanged = true;
10413            invalidateParentIfNeeded();
10414            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10415                // View was rejected last time it was drawn by its parent; this may have changed
10416                invalidateParentIfNeeded();
10417            }
10418        }
10419    }
10420
10421    /**
10422     * Left position of this view relative to its parent.
10423     *
10424     * @return The left edge of this view, in pixels.
10425     */
10426    @ViewDebug.CapturedViewProperty
10427    public final int getLeft() {
10428        return mLeft;
10429    }
10430
10431    /**
10432     * Sets the left position of this view relative to its parent. This method is meant to be called
10433     * by the layout system and should not generally be called otherwise, because the property
10434     * may be changed at any time by the layout.
10435     *
10436     * @param left The left of this view, in pixels.
10437     */
10438    public final void setLeft(int left) {
10439        if (left != mLeft) {
10440            final boolean matrixIsIdentity = hasIdentityMatrix();
10441            if (matrixIsIdentity) {
10442                if (mAttachInfo != null) {
10443                    int minLeft;
10444                    int xLoc;
10445                    if (left < mLeft) {
10446                        minLeft = left;
10447                        xLoc = left - mLeft;
10448                    } else {
10449                        minLeft = mLeft;
10450                        xLoc = 0;
10451                    }
10452                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10453                }
10454            } else {
10455                // Double-invalidation is necessary to capture view's old and new areas
10456                invalidate(true);
10457            }
10458
10459            int oldWidth = mRight - mLeft;
10460            int height = mBottom - mTop;
10461
10462            mLeft = left;
10463            mRenderNode.setLeft(left);
10464
10465            sizeChange(mRight - mLeft, height, oldWidth, height);
10466
10467            if (!matrixIsIdentity) {
10468                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10469                invalidate(true);
10470            }
10471            mBackgroundSizeChanged = true;
10472            invalidateParentIfNeeded();
10473            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10474                // View was rejected last time it was drawn by its parent; this may have changed
10475                invalidateParentIfNeeded();
10476            }
10477        }
10478    }
10479
10480    /**
10481     * Right position of this view relative to its parent.
10482     *
10483     * @return The right edge of this view, in pixels.
10484     */
10485    @ViewDebug.CapturedViewProperty
10486    public final int getRight() {
10487        return mRight;
10488    }
10489
10490    /**
10491     * Sets the right position of this view relative to its parent. This method is meant to be called
10492     * by the layout system and should not generally be called otherwise, because the property
10493     * may be changed at any time by the layout.
10494     *
10495     * @param right The right of this view, in pixels.
10496     */
10497    public final void setRight(int right) {
10498        if (right != mRight) {
10499            final boolean matrixIsIdentity = hasIdentityMatrix();
10500            if (matrixIsIdentity) {
10501                if (mAttachInfo != null) {
10502                    int maxRight;
10503                    if (right < mRight) {
10504                        maxRight = mRight;
10505                    } else {
10506                        maxRight = right;
10507                    }
10508                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10509                }
10510            } else {
10511                // Double-invalidation is necessary to capture view's old and new areas
10512                invalidate(true);
10513            }
10514
10515            int oldWidth = mRight - mLeft;
10516            int height = mBottom - mTop;
10517
10518            mRight = right;
10519            mRenderNode.setRight(mRight);
10520
10521            sizeChange(mRight - mLeft, height, oldWidth, height);
10522
10523            if (!matrixIsIdentity) {
10524                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10525                invalidate(true);
10526            }
10527            mBackgroundSizeChanged = true;
10528            invalidateParentIfNeeded();
10529            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10530                // View was rejected last time it was drawn by its parent; this may have changed
10531                invalidateParentIfNeeded();
10532            }
10533        }
10534    }
10535
10536    /**
10537     * The visual x position of this view, in pixels. This is equivalent to the
10538     * {@link #setTranslationX(float) translationX} property plus the current
10539     * {@link #getLeft() left} property.
10540     *
10541     * @return The visual x position of this view, in pixels.
10542     */
10543    @ViewDebug.ExportedProperty(category = "drawing")
10544    public float getX() {
10545        return mLeft + getTranslationX();
10546    }
10547
10548    /**
10549     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10550     * {@link #setTranslationX(float) translationX} property to be the difference between
10551     * the x value passed in and the current {@link #getLeft() left} property.
10552     *
10553     * @param x The visual x position of this view, in pixels.
10554     */
10555    public void setX(float x) {
10556        setTranslationX(x - mLeft);
10557    }
10558
10559    /**
10560     * The visual y position of this view, in pixels. This is equivalent to the
10561     * {@link #setTranslationY(float) translationY} property plus the current
10562     * {@link #getTop() top} property.
10563     *
10564     * @return The visual y position of this view, in pixels.
10565     */
10566    @ViewDebug.ExportedProperty(category = "drawing")
10567    public float getY() {
10568        return mTop + getTranslationY();
10569    }
10570
10571    /**
10572     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10573     * {@link #setTranslationY(float) translationY} property to be the difference between
10574     * the y value passed in and the current {@link #getTop() top} property.
10575     *
10576     * @param y The visual y position of this view, in pixels.
10577     */
10578    public void setY(float y) {
10579        setTranslationY(y - mTop);
10580    }
10581
10582    /**
10583     * The visual z position of this view, in pixels. This is equivalent to the
10584     * {@link #setTranslationZ(float) translationZ} property plus the current
10585     * {@link #getElevation() elevation} property.
10586     *
10587     * @return The visual z position of this view, in pixels.
10588     */
10589    @ViewDebug.ExportedProperty(category = "drawing")
10590    public float getZ() {
10591        return getElevation() + getTranslationZ();
10592    }
10593
10594    /**
10595     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10596     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10597     * the x value passed in and the current {@link #getElevation() elevation} property.
10598     *
10599     * @param z The visual z position of this view, in pixels.
10600     */
10601    public void setZ(float z) {
10602        setTranslationZ(z - getElevation());
10603    }
10604
10605    /**
10606     * The base elevation of this view relative to its parent, in pixels.
10607     *
10608     * @return The base depth position of the view, in pixels.
10609     */
10610    @ViewDebug.ExportedProperty(category = "drawing")
10611    public float getElevation() {
10612        return mRenderNode.getElevation();
10613    }
10614
10615    /**
10616     * Sets the base elevation of this view, in pixels.
10617     *
10618     * @attr ref android.R.styleable#View_elevation
10619     */
10620    public void setElevation(float elevation) {
10621        if (elevation != getElevation()) {
10622            invalidateViewProperty(true, false);
10623            mRenderNode.setElevation(elevation);
10624            invalidateViewProperty(false, true);
10625
10626            invalidateParentIfNeededAndWasQuickRejected();
10627        }
10628    }
10629
10630    /**
10631     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10632     * This position is post-layout, in addition to wherever the object's
10633     * layout placed it.
10634     *
10635     * @return The horizontal position of this view relative to its left position, in pixels.
10636     */
10637    @ViewDebug.ExportedProperty(category = "drawing")
10638    public float getTranslationX() {
10639        return mRenderNode.getTranslationX();
10640    }
10641
10642    /**
10643     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10644     * This effectively positions the object post-layout, in addition to wherever the object's
10645     * layout placed it.
10646     *
10647     * @param translationX The horizontal position of this view relative to its left position,
10648     * in pixels.
10649     *
10650     * @attr ref android.R.styleable#View_translationX
10651     */
10652    public void setTranslationX(float translationX) {
10653        if (translationX != getTranslationX()) {
10654            invalidateViewProperty(true, false);
10655            mRenderNode.setTranslationX(translationX);
10656            invalidateViewProperty(false, true);
10657
10658            invalidateParentIfNeededAndWasQuickRejected();
10659            notifySubtreeAccessibilityStateChangedIfNeeded();
10660        }
10661    }
10662
10663    /**
10664     * The vertical location of this view relative to its {@link #getTop() top} position.
10665     * This position is post-layout, in addition to wherever the object's
10666     * layout placed it.
10667     *
10668     * @return The vertical position of this view relative to its top position,
10669     * in pixels.
10670     */
10671    @ViewDebug.ExportedProperty(category = "drawing")
10672    public float getTranslationY() {
10673        return mRenderNode.getTranslationY();
10674    }
10675
10676    /**
10677     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10678     * This effectively positions the object post-layout, in addition to wherever the object's
10679     * layout placed it.
10680     *
10681     * @param translationY The vertical position of this view relative to its top position,
10682     * in pixels.
10683     *
10684     * @attr ref android.R.styleable#View_translationY
10685     */
10686    public void setTranslationY(float translationY) {
10687        if (translationY != getTranslationY()) {
10688            invalidateViewProperty(true, false);
10689            mRenderNode.setTranslationY(translationY);
10690            invalidateViewProperty(false, true);
10691
10692            invalidateParentIfNeededAndWasQuickRejected();
10693        }
10694    }
10695
10696    /**
10697     * The depth location of this view relative to its {@link #getElevation() elevation}.
10698     *
10699     * @return The depth of this view relative to its elevation.
10700     */
10701    @ViewDebug.ExportedProperty(category = "drawing")
10702    public float getTranslationZ() {
10703        return mRenderNode.getTranslationZ();
10704    }
10705
10706    /**
10707     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10708     *
10709     * @attr ref android.R.styleable#View_translationZ
10710     */
10711    public void setTranslationZ(float translationZ) {
10712        if (translationZ != getTranslationZ()) {
10713            invalidateViewProperty(true, false);
10714            mRenderNode.setTranslationZ(translationZ);
10715            invalidateViewProperty(false, true);
10716
10717            invalidateParentIfNeededAndWasQuickRejected();
10718        }
10719    }
10720
10721    /**
10722     * Returns the current StateListAnimator if exists.
10723     *
10724     * @return StateListAnimator or null if it does not exists
10725     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10726     */
10727    public StateListAnimator getStateListAnimator() {
10728        return mStateListAnimator;
10729    }
10730
10731    /**
10732     * Attaches the provided StateListAnimator to this View.
10733     * <p>
10734     * Any previously attached StateListAnimator will be detached.
10735     *
10736     * @param stateListAnimator The StateListAnimator to update the view
10737     * @see {@link android.animation.StateListAnimator}
10738     */
10739    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10740        if (mStateListAnimator == stateListAnimator) {
10741            return;
10742        }
10743        if (mStateListAnimator != null) {
10744            mStateListAnimator.setTarget(null);
10745        }
10746        mStateListAnimator = stateListAnimator;
10747        if (stateListAnimator != null) {
10748            stateListAnimator.setTarget(this);
10749            if (isAttachedToWindow()) {
10750                stateListAnimator.setState(getDrawableState());
10751            }
10752        }
10753    }
10754
10755    /**
10756     * Deprecated, pending removal
10757     *
10758     * @hide
10759     */
10760    @Deprecated
10761    public void setOutline(@Nullable Outline outline) {}
10762
10763    /**
10764     * Returns whether the Outline should be used to clip the contents of the View.
10765     * <p>
10766     * Note that this flag will only be respected if the View's Outline returns true from
10767     * {@link Outline#canClip()}.
10768     *
10769     * @see #setOutlineProvider(ViewOutlineProvider)
10770     * @see #setClipToOutline(boolean)
10771     */
10772    public final boolean getClipToOutline() {
10773        return mRenderNode.getClipToOutline();
10774    }
10775
10776    /**
10777     * Sets whether the View's Outline should be used to clip the contents of the View.
10778     * <p>
10779     * Note that this flag will only be respected if the View's Outline returns true from
10780     * {@link Outline#canClip()}.
10781     *
10782     * @see #setOutlineProvider(ViewOutlineProvider)
10783     * @see #getClipToOutline()
10784     */
10785    public void setClipToOutline(boolean clipToOutline) {
10786        damageInParent();
10787        if (getClipToOutline() != clipToOutline) {
10788            mRenderNode.setClipToOutline(clipToOutline);
10789        }
10790    }
10791
10792    /**
10793     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10794     * the shape of the shadow it casts, and enables outline clipping.
10795     * <p>
10796     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10797     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10798     * outline provider with this method allows this behavior to be overridden.
10799     * <p>
10800     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10801     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10802     * <p>
10803     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10804     *
10805     * @see #setClipToOutline(boolean)
10806     * @see #getClipToOutline()
10807     * @see #getOutlineProvider()
10808     */
10809    public void setOutlineProvider(ViewOutlineProvider provider) {
10810        mOutlineProvider = provider;
10811        invalidateOutline();
10812    }
10813
10814    /**
10815     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10816     * that defines the shape of the shadow it casts, and enables outline clipping.
10817     *
10818     * @see #setOutlineProvider(ViewOutlineProvider)
10819     */
10820    public ViewOutlineProvider getOutlineProvider() {
10821        return mOutlineProvider;
10822    }
10823
10824    /**
10825     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10826     *
10827     * @see #setOutlineProvider(ViewOutlineProvider)
10828     */
10829    public void invalidateOutline() {
10830        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10831        if (mAttachInfo == null) return;
10832
10833        if (mOutlineProvider == null) {
10834            // no provider, remove outline
10835            mRenderNode.setOutline(null);
10836        } else {
10837            final Outline outline = mAttachInfo.mTmpOutline;
10838            outline.setEmpty();
10839            outline.setAlpha(1.0f);
10840
10841            mOutlineProvider.getOutline(this, outline);
10842            mRenderNode.setOutline(outline);
10843        }
10844
10845        notifySubtreeAccessibilityStateChangedIfNeeded();
10846        invalidateViewProperty(false, false);
10847    }
10848
10849    /** @hide */
10850    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
10851        mRenderNode.setRevealClip(shouldClip, x, y, radius);
10852        invalidateViewProperty(false, false);
10853    }
10854
10855    /**
10856     * Hit rectangle in parent's coordinates
10857     *
10858     * @param outRect The hit rectangle of the view.
10859     */
10860    public void getHitRect(Rect outRect) {
10861        if (hasIdentityMatrix() || mAttachInfo == null) {
10862            outRect.set(mLeft, mTop, mRight, mBottom);
10863        } else {
10864            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10865            tmpRect.set(0, 0, getWidth(), getHeight());
10866            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10867            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10868                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10869        }
10870    }
10871
10872    /**
10873     * Determines whether the given point, in local coordinates is inside the view.
10874     */
10875    /*package*/ final boolean pointInView(float localX, float localY) {
10876        return localX >= 0 && localX < (mRight - mLeft)
10877                && localY >= 0 && localY < (mBottom - mTop);
10878    }
10879
10880    /**
10881     * Utility method to determine whether the given point, in local coordinates,
10882     * is inside the view, where the area of the view is expanded by the slop factor.
10883     * This method is called while processing touch-move events to determine if the event
10884     * is still within the view.
10885     *
10886     * @hide
10887     */
10888    public boolean pointInView(float localX, float localY, float slop) {
10889        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10890                localY < ((mBottom - mTop) + slop);
10891    }
10892
10893    /**
10894     * When a view has focus and the user navigates away from it, the next view is searched for
10895     * starting from the rectangle filled in by this method.
10896     *
10897     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10898     * of the view.  However, if your view maintains some idea of internal selection,
10899     * such as a cursor, or a selected row or column, you should override this method and
10900     * fill in a more specific rectangle.
10901     *
10902     * @param r The rectangle to fill in, in this view's coordinates.
10903     */
10904    public void getFocusedRect(Rect r) {
10905        getDrawingRect(r);
10906    }
10907
10908    /**
10909     * If some part of this view is not clipped by any of its parents, then
10910     * return that area in r in global (root) coordinates. To convert r to local
10911     * coordinates (without taking possible View rotations into account), offset
10912     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10913     * If the view is completely clipped or translated out, return false.
10914     *
10915     * @param r If true is returned, r holds the global coordinates of the
10916     *        visible portion of this view.
10917     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10918     *        between this view and its root. globalOffet may be null.
10919     * @return true if r is non-empty (i.e. part of the view is visible at the
10920     *         root level.
10921     */
10922    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10923        int width = mRight - mLeft;
10924        int height = mBottom - mTop;
10925        if (width > 0 && height > 0) {
10926            r.set(0, 0, width, height);
10927            if (globalOffset != null) {
10928                globalOffset.set(-mScrollX, -mScrollY);
10929            }
10930            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10931        }
10932        return false;
10933    }
10934
10935    public final boolean getGlobalVisibleRect(Rect r) {
10936        return getGlobalVisibleRect(r, null);
10937    }
10938
10939    public final boolean getLocalVisibleRect(Rect r) {
10940        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10941        if (getGlobalVisibleRect(r, offset)) {
10942            r.offset(-offset.x, -offset.y); // make r local
10943            return true;
10944        }
10945        return false;
10946    }
10947
10948    /**
10949     * Offset this view's vertical location by the specified number of pixels.
10950     *
10951     * @param offset the number of pixels to offset the view by
10952     */
10953    public void offsetTopAndBottom(int offset) {
10954        if (offset != 0) {
10955            final boolean matrixIsIdentity = hasIdentityMatrix();
10956            if (matrixIsIdentity) {
10957                if (isHardwareAccelerated()) {
10958                    invalidateViewProperty(false, false);
10959                } else {
10960                    final ViewParent p = mParent;
10961                    if (p != null && mAttachInfo != null) {
10962                        final Rect r = mAttachInfo.mTmpInvalRect;
10963                        int minTop;
10964                        int maxBottom;
10965                        int yLoc;
10966                        if (offset < 0) {
10967                            minTop = mTop + offset;
10968                            maxBottom = mBottom;
10969                            yLoc = offset;
10970                        } else {
10971                            minTop = mTop;
10972                            maxBottom = mBottom + offset;
10973                            yLoc = 0;
10974                        }
10975                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10976                        p.invalidateChild(this, r);
10977                    }
10978                }
10979            } else {
10980                invalidateViewProperty(false, false);
10981            }
10982
10983            mTop += offset;
10984            mBottom += offset;
10985            mRenderNode.offsetTopAndBottom(offset);
10986            if (isHardwareAccelerated()) {
10987                invalidateViewProperty(false, false);
10988            } else {
10989                if (!matrixIsIdentity) {
10990                    invalidateViewProperty(false, true);
10991                }
10992                invalidateParentIfNeeded();
10993            }
10994            notifySubtreeAccessibilityStateChangedIfNeeded();
10995        }
10996    }
10997
10998    /**
10999     * Offset this view's horizontal location by the specified amount of pixels.
11000     *
11001     * @param offset the number of pixels to offset the view by
11002     */
11003    public void offsetLeftAndRight(int offset) {
11004        if (offset != 0) {
11005            final boolean matrixIsIdentity = hasIdentityMatrix();
11006            if (matrixIsIdentity) {
11007                if (isHardwareAccelerated()) {
11008                    invalidateViewProperty(false, false);
11009                } else {
11010                    final ViewParent p = mParent;
11011                    if (p != null && mAttachInfo != null) {
11012                        final Rect r = mAttachInfo.mTmpInvalRect;
11013                        int minLeft;
11014                        int maxRight;
11015                        if (offset < 0) {
11016                            minLeft = mLeft + offset;
11017                            maxRight = mRight;
11018                        } else {
11019                            minLeft = mLeft;
11020                            maxRight = mRight + offset;
11021                        }
11022                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11023                        p.invalidateChild(this, r);
11024                    }
11025                }
11026            } else {
11027                invalidateViewProperty(false, false);
11028            }
11029
11030            mLeft += offset;
11031            mRight += offset;
11032            mRenderNode.offsetLeftAndRight(offset);
11033            if (isHardwareAccelerated()) {
11034                invalidateViewProperty(false, false);
11035            } else {
11036                if (!matrixIsIdentity) {
11037                    invalidateViewProperty(false, true);
11038                }
11039                invalidateParentIfNeeded();
11040            }
11041            notifySubtreeAccessibilityStateChangedIfNeeded();
11042        }
11043    }
11044
11045    /**
11046     * Get the LayoutParams associated with this view. All views should have
11047     * layout parameters. These supply parameters to the <i>parent</i> of this
11048     * view specifying how it should be arranged. There are many subclasses of
11049     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11050     * of ViewGroup that are responsible for arranging their children.
11051     *
11052     * This method may return null if this View is not attached to a parent
11053     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11054     * was not invoked successfully. When a View is attached to a parent
11055     * ViewGroup, this method must not return null.
11056     *
11057     * @return The LayoutParams associated with this view, or null if no
11058     *         parameters have been set yet
11059     */
11060    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11061    public ViewGroup.LayoutParams getLayoutParams() {
11062        return mLayoutParams;
11063    }
11064
11065    /**
11066     * Set the layout parameters associated with this view. These supply
11067     * parameters to the <i>parent</i> of this view specifying how it should be
11068     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11069     * correspond to the different subclasses of ViewGroup that are responsible
11070     * for arranging their children.
11071     *
11072     * @param params The layout parameters for this view, cannot be null
11073     */
11074    public void setLayoutParams(ViewGroup.LayoutParams params) {
11075        if (params == null) {
11076            throw new NullPointerException("Layout parameters cannot be null");
11077        }
11078        mLayoutParams = params;
11079        resolveLayoutParams();
11080        if (mParent instanceof ViewGroup) {
11081            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11082        }
11083        requestLayout();
11084    }
11085
11086    /**
11087     * Resolve the layout parameters depending on the resolved layout direction
11088     *
11089     * @hide
11090     */
11091    public void resolveLayoutParams() {
11092        if (mLayoutParams != null) {
11093            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11094        }
11095    }
11096
11097    /**
11098     * Set the scrolled position of your view. This will cause a call to
11099     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11100     * invalidated.
11101     * @param x the x position to scroll to
11102     * @param y the y position to scroll to
11103     */
11104    public void scrollTo(int x, int y) {
11105        if (mScrollX != x || mScrollY != y) {
11106            int oldX = mScrollX;
11107            int oldY = mScrollY;
11108            mScrollX = x;
11109            mScrollY = y;
11110            invalidateParentCaches();
11111            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11112            if (!awakenScrollBars()) {
11113                postInvalidateOnAnimation();
11114            }
11115        }
11116    }
11117
11118    /**
11119     * Move the scrolled position of your view. This will cause a call to
11120     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11121     * invalidated.
11122     * @param x the amount of pixels to scroll by horizontally
11123     * @param y the amount of pixels to scroll by vertically
11124     */
11125    public void scrollBy(int x, int y) {
11126        scrollTo(mScrollX + x, mScrollY + y);
11127    }
11128
11129    /**
11130     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11131     * animation to fade the scrollbars out after a default delay. If a subclass
11132     * provides animated scrolling, the start delay should equal the duration
11133     * of the scrolling animation.</p>
11134     *
11135     * <p>The animation starts only if at least one of the scrollbars is
11136     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11137     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11138     * this method returns true, and false otherwise. If the animation is
11139     * started, this method calls {@link #invalidate()}; in that case the
11140     * caller should not call {@link #invalidate()}.</p>
11141     *
11142     * <p>This method should be invoked every time a subclass directly updates
11143     * the scroll parameters.</p>
11144     *
11145     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11146     * and {@link #scrollTo(int, int)}.</p>
11147     *
11148     * @return true if the animation is played, false otherwise
11149     *
11150     * @see #awakenScrollBars(int)
11151     * @see #scrollBy(int, int)
11152     * @see #scrollTo(int, int)
11153     * @see #isHorizontalScrollBarEnabled()
11154     * @see #isVerticalScrollBarEnabled()
11155     * @see #setHorizontalScrollBarEnabled(boolean)
11156     * @see #setVerticalScrollBarEnabled(boolean)
11157     */
11158    protected boolean awakenScrollBars() {
11159        return mScrollCache != null &&
11160                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11161    }
11162
11163    /**
11164     * Trigger the scrollbars to draw.
11165     * This method differs from awakenScrollBars() only in its default duration.
11166     * initialAwakenScrollBars() will show the scroll bars for longer than
11167     * usual to give the user more of a chance to notice them.
11168     *
11169     * @return true if the animation is played, false otherwise.
11170     */
11171    private boolean initialAwakenScrollBars() {
11172        return mScrollCache != null &&
11173                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11174    }
11175
11176    /**
11177     * <p>
11178     * Trigger the scrollbars to draw. When invoked this method starts an
11179     * animation to fade the scrollbars out after a fixed delay. If a subclass
11180     * provides animated scrolling, the start delay should equal the duration of
11181     * the scrolling animation.
11182     * </p>
11183     *
11184     * <p>
11185     * The animation starts only if at least one of the scrollbars is enabled,
11186     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11187     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11188     * this method returns true, and false otherwise. If the animation is
11189     * started, this method calls {@link #invalidate()}; in that case the caller
11190     * should not call {@link #invalidate()}.
11191     * </p>
11192     *
11193     * <p>
11194     * This method should be invoked everytime a subclass directly updates the
11195     * scroll parameters.
11196     * </p>
11197     *
11198     * @param startDelay the delay, in milliseconds, after which the animation
11199     *        should start; when the delay is 0, the animation starts
11200     *        immediately
11201     * @return true if the animation is played, false otherwise
11202     *
11203     * @see #scrollBy(int, int)
11204     * @see #scrollTo(int, int)
11205     * @see #isHorizontalScrollBarEnabled()
11206     * @see #isVerticalScrollBarEnabled()
11207     * @see #setHorizontalScrollBarEnabled(boolean)
11208     * @see #setVerticalScrollBarEnabled(boolean)
11209     */
11210    protected boolean awakenScrollBars(int startDelay) {
11211        return awakenScrollBars(startDelay, true);
11212    }
11213
11214    /**
11215     * <p>
11216     * Trigger the scrollbars to draw. When invoked this method starts an
11217     * animation to fade the scrollbars out after a fixed delay. If a subclass
11218     * provides animated scrolling, the start delay should equal the duration of
11219     * the scrolling animation.
11220     * </p>
11221     *
11222     * <p>
11223     * The animation starts only if at least one of the scrollbars is enabled,
11224     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11225     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11226     * this method returns true, and false otherwise. If the animation is
11227     * started, this method calls {@link #invalidate()} if the invalidate parameter
11228     * is set to true; in that case the caller
11229     * should not call {@link #invalidate()}.
11230     * </p>
11231     *
11232     * <p>
11233     * This method should be invoked everytime a subclass directly updates the
11234     * scroll parameters.
11235     * </p>
11236     *
11237     * @param startDelay the delay, in milliseconds, after which the animation
11238     *        should start; when the delay is 0, the animation starts
11239     *        immediately
11240     *
11241     * @param invalidate Wheter this method should call invalidate
11242     *
11243     * @return true if the animation is played, false otherwise
11244     *
11245     * @see #scrollBy(int, int)
11246     * @see #scrollTo(int, int)
11247     * @see #isHorizontalScrollBarEnabled()
11248     * @see #isVerticalScrollBarEnabled()
11249     * @see #setHorizontalScrollBarEnabled(boolean)
11250     * @see #setVerticalScrollBarEnabled(boolean)
11251     */
11252    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11253        final ScrollabilityCache scrollCache = mScrollCache;
11254
11255        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11256            return false;
11257        }
11258
11259        if (scrollCache.scrollBar == null) {
11260            scrollCache.scrollBar = new ScrollBarDrawable();
11261        }
11262
11263        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11264
11265            if (invalidate) {
11266                // Invalidate to show the scrollbars
11267                postInvalidateOnAnimation();
11268            }
11269
11270            if (scrollCache.state == ScrollabilityCache.OFF) {
11271                // FIXME: this is copied from WindowManagerService.
11272                // We should get this value from the system when it
11273                // is possible to do so.
11274                final int KEY_REPEAT_FIRST_DELAY = 750;
11275                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11276            }
11277
11278            // Tell mScrollCache when we should start fading. This may
11279            // extend the fade start time if one was already scheduled
11280            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11281            scrollCache.fadeStartTime = fadeStartTime;
11282            scrollCache.state = ScrollabilityCache.ON;
11283
11284            // Schedule our fader to run, unscheduling any old ones first
11285            if (mAttachInfo != null) {
11286                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11287                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11288            }
11289
11290            return true;
11291        }
11292
11293        return false;
11294    }
11295
11296    /**
11297     * Do not invalidate views which are not visible and which are not running an animation. They
11298     * will not get drawn and they should not set dirty flags as if they will be drawn
11299     */
11300    private boolean skipInvalidate() {
11301        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11302                (!(mParent instanceof ViewGroup) ||
11303                        !((ViewGroup) mParent).isViewTransitioning(this));
11304    }
11305
11306    /**
11307     * Mark the area defined by dirty as needing to be drawn. If the view is
11308     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11309     * point in the future.
11310     * <p>
11311     * This must be called from a UI thread. To call from a non-UI thread, call
11312     * {@link #postInvalidate()}.
11313     * <p>
11314     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11315     * {@code dirty}.
11316     *
11317     * @param dirty the rectangle representing the bounds of the dirty region
11318     */
11319    public void invalidate(Rect dirty) {
11320        final int scrollX = mScrollX;
11321        final int scrollY = mScrollY;
11322        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11323                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11324    }
11325
11326    /**
11327     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11328     * coordinates of the dirty rect are relative to the view. If the view is
11329     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11330     * point in the future.
11331     * <p>
11332     * This must be called from a UI thread. To call from a non-UI thread, call
11333     * {@link #postInvalidate()}.
11334     *
11335     * @param l the left position of the dirty region
11336     * @param t the top position of the dirty region
11337     * @param r the right position of the dirty region
11338     * @param b the bottom position of the dirty region
11339     */
11340    public void invalidate(int l, int t, int r, int b) {
11341        final int scrollX = mScrollX;
11342        final int scrollY = mScrollY;
11343        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11344    }
11345
11346    /**
11347     * Invalidate the whole view. If the view is visible,
11348     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11349     * the future.
11350     * <p>
11351     * This must be called from a UI thread. To call from a non-UI thread, call
11352     * {@link #postInvalidate()}.
11353     */
11354    public void invalidate() {
11355        invalidate(true);
11356    }
11357
11358    /**
11359     * This is where the invalidate() work actually happens. A full invalidate()
11360     * causes the drawing cache to be invalidated, but this function can be
11361     * called with invalidateCache set to false to skip that invalidation step
11362     * for cases that do not need it (for example, a component that remains at
11363     * the same dimensions with the same content).
11364     *
11365     * @param invalidateCache Whether the drawing cache for this view should be
11366     *            invalidated as well. This is usually true for a full
11367     *            invalidate, but may be set to false if the View's contents or
11368     *            dimensions have not changed.
11369     */
11370    void invalidate(boolean invalidateCache) {
11371        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11372    }
11373
11374    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11375            boolean fullInvalidate) {
11376        if (mGhostView != null) {
11377            mGhostView.invalidate(invalidateCache);
11378            return;
11379        }
11380
11381        if (skipInvalidate()) {
11382            return;
11383        }
11384
11385        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11386                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11387                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11388                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11389            if (fullInvalidate) {
11390                mLastIsOpaque = isOpaque();
11391                mPrivateFlags &= ~PFLAG_DRAWN;
11392            }
11393
11394            mPrivateFlags |= PFLAG_DIRTY;
11395
11396            if (invalidateCache) {
11397                mPrivateFlags |= PFLAG_INVALIDATED;
11398                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11399            }
11400
11401            // Propagate the damage rectangle to the parent view.
11402            final AttachInfo ai = mAttachInfo;
11403            final ViewParent p = mParent;
11404            if (p != null && ai != null && l < r && t < b) {
11405                final Rect damage = ai.mTmpInvalRect;
11406                damage.set(l, t, r, b);
11407                p.invalidateChild(this, damage);
11408            }
11409
11410            // Damage the entire projection receiver, if necessary.
11411            if (mBackground != null && mBackground.isProjected()) {
11412                final View receiver = getProjectionReceiver();
11413                if (receiver != null) {
11414                    receiver.damageInParent();
11415                }
11416            }
11417
11418            // Damage the entire IsolatedZVolume receiving this view's shadow.
11419            if (isHardwareAccelerated() && getZ() != 0) {
11420                damageShadowReceiver();
11421            }
11422        }
11423    }
11424
11425    /**
11426     * @return this view's projection receiver, or {@code null} if none exists
11427     */
11428    private View getProjectionReceiver() {
11429        ViewParent p = getParent();
11430        while (p != null && p instanceof View) {
11431            final View v = (View) p;
11432            if (v.isProjectionReceiver()) {
11433                return v;
11434            }
11435            p = p.getParent();
11436        }
11437
11438        return null;
11439    }
11440
11441    /**
11442     * @return whether the view is a projection receiver
11443     */
11444    private boolean isProjectionReceiver() {
11445        return mBackground != null;
11446    }
11447
11448    /**
11449     * Damage area of the screen that can be covered by this View's shadow.
11450     *
11451     * This method will guarantee that any changes to shadows cast by a View
11452     * are damaged on the screen for future redraw.
11453     */
11454    private void damageShadowReceiver() {
11455        final AttachInfo ai = mAttachInfo;
11456        if (ai != null) {
11457            ViewParent p = getParent();
11458            if (p != null && p instanceof ViewGroup) {
11459                final ViewGroup vg = (ViewGroup) p;
11460                vg.damageInParent();
11461            }
11462        }
11463    }
11464
11465    /**
11466     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11467     * set any flags or handle all of the cases handled by the default invalidation methods.
11468     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11469     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11470     * walk up the hierarchy, transforming the dirty rect as necessary.
11471     *
11472     * The method also handles normal invalidation logic if display list properties are not
11473     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11474     * backup approach, to handle these cases used in the various property-setting methods.
11475     *
11476     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11477     * are not being used in this view
11478     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11479     * list properties are not being used in this view
11480     */
11481    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11482        if (!isHardwareAccelerated()
11483                || !mRenderNode.isValid()
11484                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11485            if (invalidateParent) {
11486                invalidateParentCaches();
11487            }
11488            if (forceRedraw) {
11489                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11490            }
11491            invalidate(false);
11492        } else {
11493            damageInParent();
11494        }
11495        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11496            damageShadowReceiver();
11497        }
11498    }
11499
11500    /**
11501     * Tells the parent view to damage this view's bounds.
11502     *
11503     * @hide
11504     */
11505    protected void damageInParent() {
11506        final AttachInfo ai = mAttachInfo;
11507        final ViewParent p = mParent;
11508        if (p != null && ai != null) {
11509            final Rect r = ai.mTmpInvalRect;
11510            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11511            if (mParent instanceof ViewGroup) {
11512                ((ViewGroup) mParent).damageChild(this, r);
11513            } else {
11514                mParent.invalidateChild(this, r);
11515            }
11516        }
11517    }
11518
11519    /**
11520     * Utility method to transform a given Rect by the current matrix of this view.
11521     */
11522    void transformRect(final Rect rect) {
11523        if (!getMatrix().isIdentity()) {
11524            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11525            boundingRect.set(rect);
11526            getMatrix().mapRect(boundingRect);
11527            rect.set((int) Math.floor(boundingRect.left),
11528                    (int) Math.floor(boundingRect.top),
11529                    (int) Math.ceil(boundingRect.right),
11530                    (int) Math.ceil(boundingRect.bottom));
11531        }
11532    }
11533
11534    /**
11535     * Used to indicate that the parent of this view should clear its caches. This functionality
11536     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11537     * which is necessary when various parent-managed properties of the view change, such as
11538     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11539     * clears the parent caches and does not causes an invalidate event.
11540     *
11541     * @hide
11542     */
11543    protected void invalidateParentCaches() {
11544        if (mParent instanceof View) {
11545            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11546        }
11547    }
11548
11549    /**
11550     * Used to indicate that the parent of this view should be invalidated. This functionality
11551     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11552     * which is necessary when various parent-managed properties of the view change, such as
11553     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11554     * an invalidation event to the parent.
11555     *
11556     * @hide
11557     */
11558    protected void invalidateParentIfNeeded() {
11559        if (isHardwareAccelerated() && mParent instanceof View) {
11560            ((View) mParent).invalidate(true);
11561        }
11562    }
11563
11564    /**
11565     * @hide
11566     */
11567    protected void invalidateParentIfNeededAndWasQuickRejected() {
11568        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11569            // View was rejected last time it was drawn by its parent; this may have changed
11570            invalidateParentIfNeeded();
11571        }
11572    }
11573
11574    /**
11575     * Indicates whether this View is opaque. An opaque View guarantees that it will
11576     * draw all the pixels overlapping its bounds using a fully opaque color.
11577     *
11578     * Subclasses of View should override this method whenever possible to indicate
11579     * whether an instance is opaque. Opaque Views are treated in a special way by
11580     * the View hierarchy, possibly allowing it to perform optimizations during
11581     * invalidate/draw passes.
11582     *
11583     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11584     */
11585    @ViewDebug.ExportedProperty(category = "drawing")
11586    public boolean isOpaque() {
11587        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11588                getFinalAlpha() >= 1.0f;
11589    }
11590
11591    /**
11592     * @hide
11593     */
11594    protected void computeOpaqueFlags() {
11595        // Opaque if:
11596        //   - Has a background
11597        //   - Background is opaque
11598        //   - Doesn't have scrollbars or scrollbars overlay
11599
11600        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11601            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11602        } else {
11603            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11604        }
11605
11606        final int flags = mViewFlags;
11607        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11608                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11609                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11610            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11611        } else {
11612            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11613        }
11614    }
11615
11616    /**
11617     * @hide
11618     */
11619    protected boolean hasOpaqueScrollbars() {
11620        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11621    }
11622
11623    /**
11624     * @return A handler associated with the thread running the View. This
11625     * handler can be used to pump events in the UI events queue.
11626     */
11627    public Handler getHandler() {
11628        final AttachInfo attachInfo = mAttachInfo;
11629        if (attachInfo != null) {
11630            return attachInfo.mHandler;
11631        }
11632        return null;
11633    }
11634
11635    /**
11636     * Gets the view root associated with the View.
11637     * @return The view root, or null if none.
11638     * @hide
11639     */
11640    public ViewRootImpl getViewRootImpl() {
11641        if (mAttachInfo != null) {
11642            return mAttachInfo.mViewRootImpl;
11643        }
11644        return null;
11645    }
11646
11647    /**
11648     * @hide
11649     */
11650    public HardwareRenderer getHardwareRenderer() {
11651        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11652    }
11653
11654    /**
11655     * <p>Causes the Runnable to be added to the message queue.
11656     * The runnable will be run on the user interface thread.</p>
11657     *
11658     * @param action The Runnable that will be executed.
11659     *
11660     * @return Returns true if the Runnable was successfully placed in to the
11661     *         message queue.  Returns false on failure, usually because the
11662     *         looper processing the message queue is exiting.
11663     *
11664     * @see #postDelayed
11665     * @see #removeCallbacks
11666     */
11667    public boolean post(Runnable action) {
11668        final AttachInfo attachInfo = mAttachInfo;
11669        if (attachInfo != null) {
11670            return attachInfo.mHandler.post(action);
11671        }
11672        // Assume that post will succeed later
11673        ViewRootImpl.getRunQueue().post(action);
11674        return true;
11675    }
11676
11677    /**
11678     * <p>Causes the Runnable to be added to the message queue, to be run
11679     * after the specified amount of time elapses.
11680     * The runnable will be run on the user interface thread.</p>
11681     *
11682     * @param action The Runnable that will be executed.
11683     * @param delayMillis The delay (in milliseconds) until the Runnable
11684     *        will be executed.
11685     *
11686     * @return true if the Runnable was successfully placed in to the
11687     *         message queue.  Returns false on failure, usually because the
11688     *         looper processing the message queue is exiting.  Note that a
11689     *         result of true does not mean the Runnable will be processed --
11690     *         if the looper is quit before the delivery time of the message
11691     *         occurs then the message will be dropped.
11692     *
11693     * @see #post
11694     * @see #removeCallbacks
11695     */
11696    public boolean postDelayed(Runnable action, long delayMillis) {
11697        final AttachInfo attachInfo = mAttachInfo;
11698        if (attachInfo != null) {
11699            return attachInfo.mHandler.postDelayed(action, delayMillis);
11700        }
11701        // Assume that post will succeed later
11702        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11703        return true;
11704    }
11705
11706    /**
11707     * <p>Causes the Runnable to execute on the next animation time step.
11708     * The runnable will be run on the user interface thread.</p>
11709     *
11710     * @param action The Runnable that will be executed.
11711     *
11712     * @see #postOnAnimationDelayed
11713     * @see #removeCallbacks
11714     */
11715    public void postOnAnimation(Runnable action) {
11716        final AttachInfo attachInfo = mAttachInfo;
11717        if (attachInfo != null) {
11718            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11719                    Choreographer.CALLBACK_ANIMATION, action, null);
11720        } else {
11721            // Assume that post will succeed later
11722            ViewRootImpl.getRunQueue().post(action);
11723        }
11724    }
11725
11726    /**
11727     * <p>Causes the Runnable to execute on the next animation time step,
11728     * after the specified amount of time elapses.
11729     * The runnable will be run on the user interface thread.</p>
11730     *
11731     * @param action The Runnable that will be executed.
11732     * @param delayMillis The delay (in milliseconds) until the Runnable
11733     *        will be executed.
11734     *
11735     * @see #postOnAnimation
11736     * @see #removeCallbacks
11737     */
11738    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11739        final AttachInfo attachInfo = mAttachInfo;
11740        if (attachInfo != null) {
11741            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11742                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11743        } else {
11744            // Assume that post will succeed later
11745            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11746        }
11747    }
11748
11749    /**
11750     * <p>Removes the specified Runnable from the message queue.</p>
11751     *
11752     * @param action The Runnable to remove from the message handling queue
11753     *
11754     * @return true if this view could ask the Handler to remove the Runnable,
11755     *         false otherwise. When the returned value is true, the Runnable
11756     *         may or may not have been actually removed from the message queue
11757     *         (for instance, if the Runnable was not in the queue already.)
11758     *
11759     * @see #post
11760     * @see #postDelayed
11761     * @see #postOnAnimation
11762     * @see #postOnAnimationDelayed
11763     */
11764    public boolean removeCallbacks(Runnable action) {
11765        if (action != null) {
11766            final AttachInfo attachInfo = mAttachInfo;
11767            if (attachInfo != null) {
11768                attachInfo.mHandler.removeCallbacks(action);
11769                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11770                        Choreographer.CALLBACK_ANIMATION, action, null);
11771            }
11772            // Assume that post will succeed later
11773            ViewRootImpl.getRunQueue().removeCallbacks(action);
11774        }
11775        return true;
11776    }
11777
11778    /**
11779     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11780     * Use this to invalidate the View from a non-UI thread.</p>
11781     *
11782     * <p>This method can be invoked from outside of the UI thread
11783     * only when this View is attached to a window.</p>
11784     *
11785     * @see #invalidate()
11786     * @see #postInvalidateDelayed(long)
11787     */
11788    public void postInvalidate() {
11789        postInvalidateDelayed(0);
11790    }
11791
11792    /**
11793     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11794     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11795     *
11796     * <p>This method can be invoked from outside of the UI thread
11797     * only when this View is attached to a window.</p>
11798     *
11799     * @param left The left coordinate of the rectangle to invalidate.
11800     * @param top The top coordinate of the rectangle to invalidate.
11801     * @param right The right coordinate of the rectangle to invalidate.
11802     * @param bottom The bottom coordinate of the rectangle to invalidate.
11803     *
11804     * @see #invalidate(int, int, int, int)
11805     * @see #invalidate(Rect)
11806     * @see #postInvalidateDelayed(long, int, int, int, int)
11807     */
11808    public void postInvalidate(int left, int top, int right, int bottom) {
11809        postInvalidateDelayed(0, left, top, right, bottom);
11810    }
11811
11812    /**
11813     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11814     * loop. Waits for the specified amount of time.</p>
11815     *
11816     * <p>This method can be invoked from outside of the UI thread
11817     * only when this View is attached to a window.</p>
11818     *
11819     * @param delayMilliseconds the duration in milliseconds to delay the
11820     *         invalidation by
11821     *
11822     * @see #invalidate()
11823     * @see #postInvalidate()
11824     */
11825    public void postInvalidateDelayed(long delayMilliseconds) {
11826        // We try only with the AttachInfo because there's no point in invalidating
11827        // if we are not attached to our window
11828        final AttachInfo attachInfo = mAttachInfo;
11829        if (attachInfo != null) {
11830            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11831        }
11832    }
11833
11834    /**
11835     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11836     * through the event 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     * @param left The left coordinate of the rectangle to invalidate.
11844     * @param top The top coordinate of the rectangle to invalidate.
11845     * @param right The right coordinate of the rectangle to invalidate.
11846     * @param bottom The bottom coordinate of the rectangle to invalidate.
11847     *
11848     * @see #invalidate(int, int, int, int)
11849     * @see #invalidate(Rect)
11850     * @see #postInvalidate(int, int, int, int)
11851     */
11852    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11853            int right, int bottom) {
11854
11855        // We try only with the AttachInfo because there's no point in invalidating
11856        // if we are not attached to our window
11857        final AttachInfo attachInfo = mAttachInfo;
11858        if (attachInfo != null) {
11859            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11860            info.target = this;
11861            info.left = left;
11862            info.top = top;
11863            info.right = right;
11864            info.bottom = bottom;
11865
11866            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11867        }
11868    }
11869
11870    /**
11871     * <p>Cause an invalidate to happen on the next animation time step, typically the
11872     * next display frame.</p>
11873     *
11874     * <p>This method can be invoked from outside of the UI thread
11875     * only when this View is attached to a window.</p>
11876     *
11877     * @see #invalidate()
11878     */
11879    public void postInvalidateOnAnimation() {
11880        // We try only with the AttachInfo because there's no point in invalidating
11881        // if we are not attached to our window
11882        final AttachInfo attachInfo = mAttachInfo;
11883        if (attachInfo != null) {
11884            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11885        }
11886    }
11887
11888    /**
11889     * <p>Cause an invalidate of the specified area to happen on the next animation
11890     * time step, typically the next display frame.</p>
11891     *
11892     * <p>This method can be invoked from outside of the UI thread
11893     * only when this View is attached to a window.</p>
11894     *
11895     * @param left The left coordinate of the rectangle to invalidate.
11896     * @param top The top coordinate of the rectangle to invalidate.
11897     * @param right The right coordinate of the rectangle to invalidate.
11898     * @param bottom The bottom coordinate of the rectangle to invalidate.
11899     *
11900     * @see #invalidate(int, int, int, int)
11901     * @see #invalidate(Rect)
11902     */
11903    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11904        // We try only with the AttachInfo because there's no point in invalidating
11905        // if we are not attached to our window
11906        final AttachInfo attachInfo = mAttachInfo;
11907        if (attachInfo != null) {
11908            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11909            info.target = this;
11910            info.left = left;
11911            info.top = top;
11912            info.right = right;
11913            info.bottom = bottom;
11914
11915            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11916        }
11917    }
11918
11919    /**
11920     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11921     * This event is sent at most once every
11922     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11923     */
11924    private void postSendViewScrolledAccessibilityEventCallback() {
11925        if (mSendViewScrolledAccessibilityEvent == null) {
11926            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11927        }
11928        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11929            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11930            postDelayed(mSendViewScrolledAccessibilityEvent,
11931                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11932        }
11933    }
11934
11935    /**
11936     * Called by a parent to request that a child update its values for mScrollX
11937     * and mScrollY if necessary. This will typically be done if the child is
11938     * animating a scroll using a {@link android.widget.Scroller Scroller}
11939     * object.
11940     */
11941    public void computeScroll() {
11942    }
11943
11944    /**
11945     * <p>Indicate whether the horizontal edges are faded when the view is
11946     * scrolled horizontally.</p>
11947     *
11948     * @return true if the horizontal edges should are faded on scroll, false
11949     *         otherwise
11950     *
11951     * @see #setHorizontalFadingEdgeEnabled(boolean)
11952     *
11953     * @attr ref android.R.styleable#View_requiresFadingEdge
11954     */
11955    public boolean isHorizontalFadingEdgeEnabled() {
11956        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11957    }
11958
11959    /**
11960     * <p>Define whether the horizontal edges should be faded when this view
11961     * is scrolled horizontally.</p>
11962     *
11963     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11964     *                                    be faded when the view is scrolled
11965     *                                    horizontally
11966     *
11967     * @see #isHorizontalFadingEdgeEnabled()
11968     *
11969     * @attr ref android.R.styleable#View_requiresFadingEdge
11970     */
11971    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11972        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11973            if (horizontalFadingEdgeEnabled) {
11974                initScrollCache();
11975            }
11976
11977            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11978        }
11979    }
11980
11981    /**
11982     * <p>Indicate whether the vertical edges are faded when the view is
11983     * scrolled horizontally.</p>
11984     *
11985     * @return true if the vertical edges should are faded on scroll, false
11986     *         otherwise
11987     *
11988     * @see #setVerticalFadingEdgeEnabled(boolean)
11989     *
11990     * @attr ref android.R.styleable#View_requiresFadingEdge
11991     */
11992    public boolean isVerticalFadingEdgeEnabled() {
11993        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11994    }
11995
11996    /**
11997     * <p>Define whether the vertical edges should be faded when this view
11998     * is scrolled vertically.</p>
11999     *
12000     * @param verticalFadingEdgeEnabled true if the vertical edges should
12001     *                                  be faded when the view is scrolled
12002     *                                  vertically
12003     *
12004     * @see #isVerticalFadingEdgeEnabled()
12005     *
12006     * @attr ref android.R.styleable#View_requiresFadingEdge
12007     */
12008    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12009        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12010            if (verticalFadingEdgeEnabled) {
12011                initScrollCache();
12012            }
12013
12014            mViewFlags ^= FADING_EDGE_VERTICAL;
12015        }
12016    }
12017
12018    /**
12019     * Returns the strength, or intensity, of the top faded edge. The strength is
12020     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12021     * returns 0.0 or 1.0 but no value in between.
12022     *
12023     * Subclasses should override this method to provide a smoother fade transition
12024     * when scrolling occurs.
12025     *
12026     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12027     */
12028    protected float getTopFadingEdgeStrength() {
12029        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12030    }
12031
12032    /**
12033     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12034     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12035     * returns 0.0 or 1.0 but no value in between.
12036     *
12037     * Subclasses should override this method to provide a smoother fade transition
12038     * when scrolling occurs.
12039     *
12040     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12041     */
12042    protected float getBottomFadingEdgeStrength() {
12043        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12044                computeVerticalScrollRange() ? 1.0f : 0.0f;
12045    }
12046
12047    /**
12048     * Returns the strength, or intensity, of the left faded edge. The strength is
12049     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12050     * returns 0.0 or 1.0 but no value in between.
12051     *
12052     * Subclasses should override this method to provide a smoother fade transition
12053     * when scrolling occurs.
12054     *
12055     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12056     */
12057    protected float getLeftFadingEdgeStrength() {
12058        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12059    }
12060
12061    /**
12062     * Returns the strength, or intensity, of the right faded edge. The strength is
12063     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12064     * returns 0.0 or 1.0 but no value in between.
12065     *
12066     * Subclasses should override this method to provide a smoother fade transition
12067     * when scrolling occurs.
12068     *
12069     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12070     */
12071    protected float getRightFadingEdgeStrength() {
12072        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12073                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12074    }
12075
12076    /**
12077     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12078     * scrollbar is not drawn by default.</p>
12079     *
12080     * @return true if the horizontal scrollbar should be painted, false
12081     *         otherwise
12082     *
12083     * @see #setHorizontalScrollBarEnabled(boolean)
12084     */
12085    public boolean isHorizontalScrollBarEnabled() {
12086        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12087    }
12088
12089    /**
12090     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12091     * scrollbar is not drawn by default.</p>
12092     *
12093     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12094     *                                   be painted
12095     *
12096     * @see #isHorizontalScrollBarEnabled()
12097     */
12098    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12099        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12100            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12101            computeOpaqueFlags();
12102            resolvePadding();
12103        }
12104    }
12105
12106    /**
12107     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12108     * scrollbar is not drawn by default.</p>
12109     *
12110     * @return true if the vertical scrollbar should be painted, false
12111     *         otherwise
12112     *
12113     * @see #setVerticalScrollBarEnabled(boolean)
12114     */
12115    public boolean isVerticalScrollBarEnabled() {
12116        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12117    }
12118
12119    /**
12120     * <p>Define whether the vertical scrollbar should be drawn or not. The
12121     * scrollbar is not drawn by default.</p>
12122     *
12123     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12124     *                                 be painted
12125     *
12126     * @see #isVerticalScrollBarEnabled()
12127     */
12128    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12129        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12130            mViewFlags ^= SCROLLBARS_VERTICAL;
12131            computeOpaqueFlags();
12132            resolvePadding();
12133        }
12134    }
12135
12136    /**
12137     * @hide
12138     */
12139    protected void recomputePadding() {
12140        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12141    }
12142
12143    /**
12144     * Define whether scrollbars will fade when the view is not scrolling.
12145     *
12146     * @param fadeScrollbars wheter to enable fading
12147     *
12148     * @attr ref android.R.styleable#View_fadeScrollbars
12149     */
12150    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12151        initScrollCache();
12152        final ScrollabilityCache scrollabilityCache = mScrollCache;
12153        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12154        if (fadeScrollbars) {
12155            scrollabilityCache.state = ScrollabilityCache.OFF;
12156        } else {
12157            scrollabilityCache.state = ScrollabilityCache.ON;
12158        }
12159    }
12160
12161    /**
12162     *
12163     * Returns true if scrollbars will fade when this view is not scrolling
12164     *
12165     * @return true if scrollbar fading is enabled
12166     *
12167     * @attr ref android.R.styleable#View_fadeScrollbars
12168     */
12169    public boolean isScrollbarFadingEnabled() {
12170        return mScrollCache != null && mScrollCache.fadeScrollBars;
12171    }
12172
12173    /**
12174     *
12175     * Returns the delay before scrollbars fade.
12176     *
12177     * @return the delay before scrollbars fade
12178     *
12179     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12180     */
12181    public int getScrollBarDefaultDelayBeforeFade() {
12182        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12183                mScrollCache.scrollBarDefaultDelayBeforeFade;
12184    }
12185
12186    /**
12187     * Define the delay before scrollbars fade.
12188     *
12189     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12190     *
12191     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12192     */
12193    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12194        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12195    }
12196
12197    /**
12198     *
12199     * Returns the scrollbar fade duration.
12200     *
12201     * @return the scrollbar fade duration
12202     *
12203     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12204     */
12205    public int getScrollBarFadeDuration() {
12206        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12207                mScrollCache.scrollBarFadeDuration;
12208    }
12209
12210    /**
12211     * Define the scrollbar fade duration.
12212     *
12213     * @param scrollBarFadeDuration - the scrollbar fade duration
12214     *
12215     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12216     */
12217    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12218        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12219    }
12220
12221    /**
12222     *
12223     * Returns the scrollbar size.
12224     *
12225     * @return the scrollbar size
12226     *
12227     * @attr ref android.R.styleable#View_scrollbarSize
12228     */
12229    public int getScrollBarSize() {
12230        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12231                mScrollCache.scrollBarSize;
12232    }
12233
12234    /**
12235     * Define the scrollbar size.
12236     *
12237     * @param scrollBarSize - the scrollbar size
12238     *
12239     * @attr ref android.R.styleable#View_scrollbarSize
12240     */
12241    public void setScrollBarSize(int scrollBarSize) {
12242        getScrollCache().scrollBarSize = scrollBarSize;
12243    }
12244
12245    /**
12246     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12247     * inset. When inset, they add to the padding of the view. And the scrollbars
12248     * can be drawn inside the padding area or on the edge of the view. For example,
12249     * if a view has a background drawable and you want to draw the scrollbars
12250     * inside the padding specified by the drawable, you can use
12251     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12252     * appear at the edge of the view, ignoring the padding, then you can use
12253     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12254     * @param style the style of the scrollbars. Should be one of
12255     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12256     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12257     * @see #SCROLLBARS_INSIDE_OVERLAY
12258     * @see #SCROLLBARS_INSIDE_INSET
12259     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12260     * @see #SCROLLBARS_OUTSIDE_INSET
12261     *
12262     * @attr ref android.R.styleable#View_scrollbarStyle
12263     */
12264    public void setScrollBarStyle(@ScrollBarStyle int style) {
12265        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12266            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12267            computeOpaqueFlags();
12268            resolvePadding();
12269        }
12270    }
12271
12272    /**
12273     * <p>Returns the current scrollbar style.</p>
12274     * @return the current scrollbar style
12275     * @see #SCROLLBARS_INSIDE_OVERLAY
12276     * @see #SCROLLBARS_INSIDE_INSET
12277     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12278     * @see #SCROLLBARS_OUTSIDE_INSET
12279     *
12280     * @attr ref android.R.styleable#View_scrollbarStyle
12281     */
12282    @ViewDebug.ExportedProperty(mapping = {
12283            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12284            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12285            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12286            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12287    })
12288    @ScrollBarStyle
12289    public int getScrollBarStyle() {
12290        return mViewFlags & SCROLLBARS_STYLE_MASK;
12291    }
12292
12293    /**
12294     * <p>Compute the horizontal range that the horizontal scrollbar
12295     * represents.</p>
12296     *
12297     * <p>The range is expressed in arbitrary units that must be the same as the
12298     * units used by {@link #computeHorizontalScrollExtent()} and
12299     * {@link #computeHorizontalScrollOffset()}.</p>
12300     *
12301     * <p>The default range is the drawing width of this view.</p>
12302     *
12303     * @return the total horizontal range represented by the horizontal
12304     *         scrollbar
12305     *
12306     * @see #computeHorizontalScrollExtent()
12307     * @see #computeHorizontalScrollOffset()
12308     * @see android.widget.ScrollBarDrawable
12309     */
12310    protected int computeHorizontalScrollRange() {
12311        return getWidth();
12312    }
12313
12314    /**
12315     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12316     * within the horizontal range. This value is used to compute the position
12317     * of the thumb within the scrollbar's track.</p>
12318     *
12319     * <p>The range is expressed in arbitrary units that must be the same as the
12320     * units used by {@link #computeHorizontalScrollRange()} and
12321     * {@link #computeHorizontalScrollExtent()}.</p>
12322     *
12323     * <p>The default offset is the scroll offset of this view.</p>
12324     *
12325     * @return the horizontal offset of the scrollbar's thumb
12326     *
12327     * @see #computeHorizontalScrollRange()
12328     * @see #computeHorizontalScrollExtent()
12329     * @see android.widget.ScrollBarDrawable
12330     */
12331    protected int computeHorizontalScrollOffset() {
12332        return mScrollX;
12333    }
12334
12335    /**
12336     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12337     * within the horizontal range. This value is used to compute the length
12338     * of the thumb within the scrollbar's track.</p>
12339     *
12340     * <p>The range is expressed in arbitrary units that must be the same as the
12341     * units used by {@link #computeHorizontalScrollRange()} and
12342     * {@link #computeHorizontalScrollOffset()}.</p>
12343     *
12344     * <p>The default extent is the drawing width of this view.</p>
12345     *
12346     * @return the horizontal extent of the scrollbar's thumb
12347     *
12348     * @see #computeHorizontalScrollRange()
12349     * @see #computeHorizontalScrollOffset()
12350     * @see android.widget.ScrollBarDrawable
12351     */
12352    protected int computeHorizontalScrollExtent() {
12353        return getWidth();
12354    }
12355
12356    /**
12357     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12358     *
12359     * <p>The range is expressed in arbitrary units that must be the same as the
12360     * units used by {@link #computeVerticalScrollExtent()} and
12361     * {@link #computeVerticalScrollOffset()}.</p>
12362     *
12363     * @return the total vertical range represented by the vertical scrollbar
12364     *
12365     * <p>The default range is the drawing height of this view.</p>
12366     *
12367     * @see #computeVerticalScrollExtent()
12368     * @see #computeVerticalScrollOffset()
12369     * @see android.widget.ScrollBarDrawable
12370     */
12371    protected int computeVerticalScrollRange() {
12372        return getHeight();
12373    }
12374
12375    /**
12376     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12377     * within the horizontal range. This value is used to compute the position
12378     * of the thumb within the scrollbar's track.</p>
12379     *
12380     * <p>The range is expressed in arbitrary units that must be the same as the
12381     * units used by {@link #computeVerticalScrollRange()} and
12382     * {@link #computeVerticalScrollExtent()}.</p>
12383     *
12384     * <p>The default offset is the scroll offset of this view.</p>
12385     *
12386     * @return the vertical offset of the scrollbar's thumb
12387     *
12388     * @see #computeVerticalScrollRange()
12389     * @see #computeVerticalScrollExtent()
12390     * @see android.widget.ScrollBarDrawable
12391     */
12392    protected int computeVerticalScrollOffset() {
12393        return mScrollY;
12394    }
12395
12396    /**
12397     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12398     * within the vertical range. This value is used to compute the length
12399     * of the thumb within the scrollbar's track.</p>
12400     *
12401     * <p>The range is expressed in arbitrary units that must be the same as the
12402     * units used by {@link #computeVerticalScrollRange()} and
12403     * {@link #computeVerticalScrollOffset()}.</p>
12404     *
12405     * <p>The default extent is the drawing height of this view.</p>
12406     *
12407     * @return the vertical extent of the scrollbar's thumb
12408     *
12409     * @see #computeVerticalScrollRange()
12410     * @see #computeVerticalScrollOffset()
12411     * @see android.widget.ScrollBarDrawable
12412     */
12413    protected int computeVerticalScrollExtent() {
12414        return getHeight();
12415    }
12416
12417    /**
12418     * Check if this view can be scrolled horizontally in a certain direction.
12419     *
12420     * @param direction Negative to check scrolling left, positive to check scrolling right.
12421     * @return true if this view can be scrolled in the specified direction, false otherwise.
12422     */
12423    public boolean canScrollHorizontally(int direction) {
12424        final int offset = computeHorizontalScrollOffset();
12425        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12426        if (range == 0) return false;
12427        if (direction < 0) {
12428            return offset > 0;
12429        } else {
12430            return offset < range - 1;
12431        }
12432    }
12433
12434    /**
12435     * Check if this view can be scrolled vertically in a certain direction.
12436     *
12437     * @param direction Negative to check scrolling up, positive to check scrolling down.
12438     * @return true if this view can be scrolled in the specified direction, false otherwise.
12439     */
12440    public boolean canScrollVertically(int direction) {
12441        final int offset = computeVerticalScrollOffset();
12442        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12443        if (range == 0) return false;
12444        if (direction < 0) {
12445            return offset > 0;
12446        } else {
12447            return offset < range - 1;
12448        }
12449    }
12450
12451    /**
12452     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12453     * scrollbars are painted only if they have been awakened first.</p>
12454     *
12455     * @param canvas the canvas on which to draw the scrollbars
12456     *
12457     * @see #awakenScrollBars(int)
12458     */
12459    protected final void onDrawScrollBars(Canvas canvas) {
12460        // scrollbars are drawn only when the animation is running
12461        final ScrollabilityCache cache = mScrollCache;
12462        if (cache != null) {
12463
12464            int state = cache.state;
12465
12466            if (state == ScrollabilityCache.OFF) {
12467                return;
12468            }
12469
12470            boolean invalidate = false;
12471
12472            if (state == ScrollabilityCache.FADING) {
12473                // We're fading -- get our fade interpolation
12474                if (cache.interpolatorValues == null) {
12475                    cache.interpolatorValues = new float[1];
12476                }
12477
12478                float[] values = cache.interpolatorValues;
12479
12480                // Stops the animation if we're done
12481                if (cache.scrollBarInterpolator.timeToValues(values) ==
12482                        Interpolator.Result.FREEZE_END) {
12483                    cache.state = ScrollabilityCache.OFF;
12484                } else {
12485                    cache.scrollBar.setAlpha(Math.round(values[0]));
12486                }
12487
12488                // This will make the scroll bars inval themselves after
12489                // drawing. We only want this when we're fading so that
12490                // we prevent excessive redraws
12491                invalidate = true;
12492            } else {
12493                // We're just on -- but we may have been fading before so
12494                // reset alpha
12495                cache.scrollBar.setAlpha(255);
12496            }
12497
12498
12499            final int viewFlags = mViewFlags;
12500
12501            final boolean drawHorizontalScrollBar =
12502                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12503            final boolean drawVerticalScrollBar =
12504                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12505                && !isVerticalScrollBarHidden();
12506
12507            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12508                final int width = mRight - mLeft;
12509                final int height = mBottom - mTop;
12510
12511                final ScrollBarDrawable scrollBar = cache.scrollBar;
12512
12513                final int scrollX = mScrollX;
12514                final int scrollY = mScrollY;
12515                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12516
12517                int left;
12518                int top;
12519                int right;
12520                int bottom;
12521
12522                if (drawHorizontalScrollBar) {
12523                    int size = scrollBar.getSize(false);
12524                    if (size <= 0) {
12525                        size = cache.scrollBarSize;
12526                    }
12527
12528                    scrollBar.setParameters(computeHorizontalScrollRange(),
12529                                            computeHorizontalScrollOffset(),
12530                                            computeHorizontalScrollExtent(), false);
12531                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12532                            getVerticalScrollbarWidth() : 0;
12533                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12534                    left = scrollX + (mPaddingLeft & inside);
12535                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12536                    bottom = top + size;
12537                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12538                    if (invalidate) {
12539                        invalidate(left, top, right, bottom);
12540                    }
12541                }
12542
12543                if (drawVerticalScrollBar) {
12544                    int size = scrollBar.getSize(true);
12545                    if (size <= 0) {
12546                        size = cache.scrollBarSize;
12547                    }
12548
12549                    scrollBar.setParameters(computeVerticalScrollRange(),
12550                                            computeVerticalScrollOffset(),
12551                                            computeVerticalScrollExtent(), true);
12552                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12553                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12554                        verticalScrollbarPosition = isLayoutRtl() ?
12555                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12556                    }
12557                    switch (verticalScrollbarPosition) {
12558                        default:
12559                        case SCROLLBAR_POSITION_RIGHT:
12560                            left = scrollX + width - size - (mUserPaddingRight & inside);
12561                            break;
12562                        case SCROLLBAR_POSITION_LEFT:
12563                            left = scrollX + (mUserPaddingLeft & inside);
12564                            break;
12565                    }
12566                    top = scrollY + (mPaddingTop & inside);
12567                    right = left + size;
12568                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12569                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12570                    if (invalidate) {
12571                        invalidate(left, top, right, bottom);
12572                    }
12573                }
12574            }
12575        }
12576    }
12577
12578    /**
12579     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12580     * FastScroller is visible.
12581     * @return whether to temporarily hide the vertical scrollbar
12582     * @hide
12583     */
12584    protected boolean isVerticalScrollBarHidden() {
12585        return false;
12586    }
12587
12588    /**
12589     * <p>Draw the horizontal scrollbar if
12590     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12591     *
12592     * @param canvas the canvas on which to draw the scrollbar
12593     * @param scrollBar the scrollbar's drawable
12594     *
12595     * @see #isHorizontalScrollBarEnabled()
12596     * @see #computeHorizontalScrollRange()
12597     * @see #computeHorizontalScrollExtent()
12598     * @see #computeHorizontalScrollOffset()
12599     * @see android.widget.ScrollBarDrawable
12600     * @hide
12601     */
12602    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12603            int l, int t, int r, int b) {
12604        scrollBar.setBounds(l, t, r, b);
12605        scrollBar.draw(canvas);
12606    }
12607
12608    /**
12609     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12610     * returns true.</p>
12611     *
12612     * @param canvas the canvas on which to draw the scrollbar
12613     * @param scrollBar the scrollbar's drawable
12614     *
12615     * @see #isVerticalScrollBarEnabled()
12616     * @see #computeVerticalScrollRange()
12617     * @see #computeVerticalScrollExtent()
12618     * @see #computeVerticalScrollOffset()
12619     * @see android.widget.ScrollBarDrawable
12620     * @hide
12621     */
12622    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12623            int l, int t, int r, int b) {
12624        scrollBar.setBounds(l, t, r, b);
12625        scrollBar.draw(canvas);
12626    }
12627
12628    /**
12629     * Implement this to do your drawing.
12630     *
12631     * @param canvas the canvas on which the background will be drawn
12632     */
12633    protected void onDraw(Canvas canvas) {
12634    }
12635
12636    /*
12637     * Caller is responsible for calling requestLayout if necessary.
12638     * (This allows addViewInLayout to not request a new layout.)
12639     */
12640    void assignParent(ViewParent parent) {
12641        if (mParent == null) {
12642            mParent = parent;
12643        } else if (parent == null) {
12644            mParent = null;
12645        } else {
12646            throw new RuntimeException("view " + this + " being added, but"
12647                    + " it already has a parent");
12648        }
12649    }
12650
12651    /**
12652     * This is called when the view is attached to a window.  At this point it
12653     * has a Surface and will start drawing.  Note that this function is
12654     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12655     * however it may be called any time before the first onDraw -- including
12656     * before or after {@link #onMeasure(int, int)}.
12657     *
12658     * @see #onDetachedFromWindow()
12659     */
12660    protected void onAttachedToWindow() {
12661        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12662            mParent.requestTransparentRegion(this);
12663        }
12664
12665        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12666            initialAwakenScrollBars();
12667            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12668        }
12669
12670        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12671
12672        jumpDrawablesToCurrentState();
12673
12674        resetSubtreeAccessibilityStateChanged();
12675
12676        invalidateOutline();
12677
12678        if (isFocused()) {
12679            InputMethodManager imm = InputMethodManager.peekInstance();
12680            imm.focusIn(this);
12681        }
12682    }
12683
12684    /**
12685     * Resolve all RTL related properties.
12686     *
12687     * @return true if resolution of RTL properties has been done
12688     *
12689     * @hide
12690     */
12691    public boolean resolveRtlPropertiesIfNeeded() {
12692        if (!needRtlPropertiesResolution()) return false;
12693
12694        // Order is important here: LayoutDirection MUST be resolved first
12695        if (!isLayoutDirectionResolved()) {
12696            resolveLayoutDirection();
12697            resolveLayoutParams();
12698        }
12699        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12700        if (!isTextDirectionResolved()) {
12701            resolveTextDirection();
12702        }
12703        if (!isTextAlignmentResolved()) {
12704            resolveTextAlignment();
12705        }
12706        // Should resolve Drawables before Padding because we need the layout direction of the
12707        // Drawable to correctly resolve Padding.
12708        if (!isDrawablesResolved()) {
12709            resolveDrawables();
12710        }
12711        if (!isPaddingResolved()) {
12712            resolvePadding();
12713        }
12714        onRtlPropertiesChanged(getLayoutDirection());
12715        return true;
12716    }
12717
12718    /**
12719     * Reset resolution of all RTL related properties.
12720     *
12721     * @hide
12722     */
12723    public void resetRtlProperties() {
12724        resetResolvedLayoutDirection();
12725        resetResolvedTextDirection();
12726        resetResolvedTextAlignment();
12727        resetResolvedPadding();
12728        resetResolvedDrawables();
12729    }
12730
12731    /**
12732     * @see #onScreenStateChanged(int)
12733     */
12734    void dispatchScreenStateChanged(int screenState) {
12735        onScreenStateChanged(screenState);
12736    }
12737
12738    /**
12739     * This method is called whenever the state of the screen this view is
12740     * attached to changes. A state change will usually occurs when the screen
12741     * turns on or off (whether it happens automatically or the user does it
12742     * manually.)
12743     *
12744     * @param screenState The new state of the screen. Can be either
12745     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12746     */
12747    public void onScreenStateChanged(int screenState) {
12748    }
12749
12750    /**
12751     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12752     */
12753    private boolean hasRtlSupport() {
12754        return mContext.getApplicationInfo().hasRtlSupport();
12755    }
12756
12757    /**
12758     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12759     * RTL not supported)
12760     */
12761    private boolean isRtlCompatibilityMode() {
12762        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12763        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12764    }
12765
12766    /**
12767     * @return true if RTL properties need resolution.
12768     *
12769     */
12770    private boolean needRtlPropertiesResolution() {
12771        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12772    }
12773
12774    /**
12775     * Called when any RTL property (layout direction or text direction or text alignment) has
12776     * been changed.
12777     *
12778     * Subclasses need to override this method to take care of cached information that depends on the
12779     * resolved layout direction, or to inform child views that inherit their layout direction.
12780     *
12781     * The default implementation does nothing.
12782     *
12783     * @param layoutDirection the direction of the layout
12784     *
12785     * @see #LAYOUT_DIRECTION_LTR
12786     * @see #LAYOUT_DIRECTION_RTL
12787     */
12788    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12789    }
12790
12791    /**
12792     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12793     * that the parent directionality can and will be resolved before its children.
12794     *
12795     * @return true if resolution has been done, false otherwise.
12796     *
12797     * @hide
12798     */
12799    public boolean resolveLayoutDirection() {
12800        // Clear any previous layout direction resolution
12801        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12802
12803        if (hasRtlSupport()) {
12804            // Set resolved depending on layout direction
12805            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12806                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12807                case LAYOUT_DIRECTION_INHERIT:
12808                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12809                    // later to get the correct resolved value
12810                    if (!canResolveLayoutDirection()) return false;
12811
12812                    // Parent has not yet resolved, LTR is still the default
12813                    try {
12814                        if (!mParent.isLayoutDirectionResolved()) return false;
12815
12816                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12817                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12818                        }
12819                    } catch (AbstractMethodError e) {
12820                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12821                                " does not fully implement ViewParent", e);
12822                    }
12823                    break;
12824                case LAYOUT_DIRECTION_RTL:
12825                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12826                    break;
12827                case LAYOUT_DIRECTION_LOCALE:
12828                    if((LAYOUT_DIRECTION_RTL ==
12829                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12830                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12831                    }
12832                    break;
12833                default:
12834                    // Nothing to do, LTR by default
12835            }
12836        }
12837
12838        // Set to resolved
12839        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12840        return true;
12841    }
12842
12843    /**
12844     * Check if layout direction resolution can be done.
12845     *
12846     * @return true if layout direction resolution can be done otherwise return false.
12847     */
12848    public boolean canResolveLayoutDirection() {
12849        switch (getRawLayoutDirection()) {
12850            case LAYOUT_DIRECTION_INHERIT:
12851                if (mParent != null) {
12852                    try {
12853                        return mParent.canResolveLayoutDirection();
12854                    } catch (AbstractMethodError e) {
12855                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12856                                " does not fully implement ViewParent", e);
12857                    }
12858                }
12859                return false;
12860
12861            default:
12862                return true;
12863        }
12864    }
12865
12866    /**
12867     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12868     * {@link #onMeasure(int, int)}.
12869     *
12870     * @hide
12871     */
12872    public void resetResolvedLayoutDirection() {
12873        // Reset the current resolved bits
12874        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12875    }
12876
12877    /**
12878     * @return true if the layout direction is inherited.
12879     *
12880     * @hide
12881     */
12882    public boolean isLayoutDirectionInherited() {
12883        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12884    }
12885
12886    /**
12887     * @return true if layout direction has been resolved.
12888     */
12889    public boolean isLayoutDirectionResolved() {
12890        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12891    }
12892
12893    /**
12894     * Return if padding has been resolved
12895     *
12896     * @hide
12897     */
12898    boolean isPaddingResolved() {
12899        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12900    }
12901
12902    /**
12903     * Resolves padding depending on layout direction, if applicable, and
12904     * recomputes internal padding values to adjust for scroll bars.
12905     *
12906     * @hide
12907     */
12908    public void resolvePadding() {
12909        final int resolvedLayoutDirection = getLayoutDirection();
12910
12911        if (!isRtlCompatibilityMode()) {
12912            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12913            // If start / end padding are defined, they will be resolved (hence overriding) to
12914            // left / right or right / left depending on the resolved layout direction.
12915            // If start / end padding are not defined, use the left / right ones.
12916            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12917                Rect padding = sThreadLocal.get();
12918                if (padding == null) {
12919                    padding = new Rect();
12920                    sThreadLocal.set(padding);
12921                }
12922                mBackground.getPadding(padding);
12923                if (!mLeftPaddingDefined) {
12924                    mUserPaddingLeftInitial = padding.left;
12925                }
12926                if (!mRightPaddingDefined) {
12927                    mUserPaddingRightInitial = padding.right;
12928                }
12929            }
12930            switch (resolvedLayoutDirection) {
12931                case LAYOUT_DIRECTION_RTL:
12932                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12933                        mUserPaddingRight = mUserPaddingStart;
12934                    } else {
12935                        mUserPaddingRight = mUserPaddingRightInitial;
12936                    }
12937                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12938                        mUserPaddingLeft = mUserPaddingEnd;
12939                    } else {
12940                        mUserPaddingLeft = mUserPaddingLeftInitial;
12941                    }
12942                    break;
12943                case LAYOUT_DIRECTION_LTR:
12944                default:
12945                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12946                        mUserPaddingLeft = mUserPaddingStart;
12947                    } else {
12948                        mUserPaddingLeft = mUserPaddingLeftInitial;
12949                    }
12950                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12951                        mUserPaddingRight = mUserPaddingEnd;
12952                    } else {
12953                        mUserPaddingRight = mUserPaddingRightInitial;
12954                    }
12955            }
12956
12957            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12958        }
12959
12960        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12961        onRtlPropertiesChanged(resolvedLayoutDirection);
12962
12963        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12964    }
12965
12966    /**
12967     * Reset the resolved layout direction.
12968     *
12969     * @hide
12970     */
12971    public void resetResolvedPadding() {
12972        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12973    }
12974
12975    /**
12976     * This is called when the view is detached from a window.  At this point it
12977     * no longer has a surface for drawing.
12978     *
12979     * @see #onAttachedToWindow()
12980     */
12981    protected void onDetachedFromWindow() {
12982    }
12983
12984    /**
12985     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12986     * after onDetachedFromWindow().
12987     *
12988     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12989     * The super method should be called at the end of the overriden method to ensure
12990     * subclasses are destroyed first
12991     *
12992     * @hide
12993     */
12994    protected void onDetachedFromWindowInternal() {
12995        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12996        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12997
12998        removeUnsetPressCallback();
12999        removeLongPressCallback();
13000        removePerformClickCallback();
13001        removeSendViewScrolledAccessibilityEventCallback();
13002        stopNestedScroll();
13003
13004        destroyDrawingCache();
13005
13006        cleanupDraw();
13007        mCurrentAnimation = null;
13008    }
13009
13010    private void cleanupDraw() {
13011        resetDisplayList();
13012        if (mAttachInfo != null) {
13013            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13014        }
13015    }
13016
13017    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13018    }
13019
13020    /**
13021     * @return The number of times this view has been attached to a window
13022     */
13023    protected int getWindowAttachCount() {
13024        return mWindowAttachCount;
13025    }
13026
13027    /**
13028     * Retrieve a unique token identifying the window this view is attached to.
13029     * @return Return the window's token for use in
13030     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13031     */
13032    public IBinder getWindowToken() {
13033        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13034    }
13035
13036    /**
13037     * Retrieve the {@link WindowId} for the window this view is
13038     * currently attached to.
13039     */
13040    public WindowId getWindowId() {
13041        if (mAttachInfo == null) {
13042            return null;
13043        }
13044        if (mAttachInfo.mWindowId == null) {
13045            try {
13046                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13047                        mAttachInfo.mWindowToken);
13048                mAttachInfo.mWindowId = new WindowId(
13049                        mAttachInfo.mIWindowId);
13050            } catch (RemoteException e) {
13051            }
13052        }
13053        return mAttachInfo.mWindowId;
13054    }
13055
13056    /**
13057     * Retrieve a unique token identifying the top-level "real" window of
13058     * the window that this view is attached to.  That is, this is like
13059     * {@link #getWindowToken}, except if the window this view in is a panel
13060     * window (attached to another containing window), then the token of
13061     * the containing window is returned instead.
13062     *
13063     * @return Returns the associated window token, either
13064     * {@link #getWindowToken()} or the containing window's token.
13065     */
13066    public IBinder getApplicationWindowToken() {
13067        AttachInfo ai = mAttachInfo;
13068        if (ai != null) {
13069            IBinder appWindowToken = ai.mPanelParentWindowToken;
13070            if (appWindowToken == null) {
13071                appWindowToken = ai.mWindowToken;
13072            }
13073            return appWindowToken;
13074        }
13075        return null;
13076    }
13077
13078    /**
13079     * Gets the logical display to which the view's window has been attached.
13080     *
13081     * @return The logical display, or null if the view is not currently attached to a window.
13082     */
13083    public Display getDisplay() {
13084        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13085    }
13086
13087    /**
13088     * Retrieve private session object this view hierarchy is using to
13089     * communicate with the window manager.
13090     * @return the session object to communicate with the window manager
13091     */
13092    /*package*/ IWindowSession getWindowSession() {
13093        return mAttachInfo != null ? mAttachInfo.mSession : null;
13094    }
13095
13096    /**
13097     * @param info the {@link android.view.View.AttachInfo} to associated with
13098     *        this view
13099     */
13100    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13101        //System.out.println("Attached! " + this);
13102        mAttachInfo = info;
13103        if (mOverlay != null) {
13104            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13105        }
13106        mWindowAttachCount++;
13107        // We will need to evaluate the drawable state at least once.
13108        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13109        if (mFloatingTreeObserver != null) {
13110            info.mTreeObserver.merge(mFloatingTreeObserver);
13111            mFloatingTreeObserver = null;
13112        }
13113        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13114            mAttachInfo.mScrollContainers.add(this);
13115            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13116        }
13117        performCollectViewAttributes(mAttachInfo, visibility);
13118        onAttachedToWindow();
13119
13120        ListenerInfo li = mListenerInfo;
13121        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13122                li != null ? li.mOnAttachStateChangeListeners : null;
13123        if (listeners != null && listeners.size() > 0) {
13124            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13125            // perform the dispatching. The iterator is a safe guard against listeners that
13126            // could mutate the list by calling the various add/remove methods. This prevents
13127            // the array from being modified while we iterate it.
13128            for (OnAttachStateChangeListener listener : listeners) {
13129                listener.onViewAttachedToWindow(this);
13130            }
13131        }
13132
13133        int vis = info.mWindowVisibility;
13134        if (vis != GONE) {
13135            onWindowVisibilityChanged(vis);
13136        }
13137        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13138            // If nobody has evaluated the drawable state yet, then do it now.
13139            refreshDrawableState();
13140        }
13141        needGlobalAttributesUpdate(false);
13142    }
13143
13144    void dispatchDetachedFromWindow() {
13145        AttachInfo info = mAttachInfo;
13146        if (info != null) {
13147            int vis = info.mWindowVisibility;
13148            if (vis != GONE) {
13149                onWindowVisibilityChanged(GONE);
13150            }
13151        }
13152
13153        onDetachedFromWindow();
13154        onDetachedFromWindowInternal();
13155
13156        ListenerInfo li = mListenerInfo;
13157        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13158                li != null ? li.mOnAttachStateChangeListeners : null;
13159        if (listeners != null && listeners.size() > 0) {
13160            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13161            // perform the dispatching. The iterator is a safe guard against listeners that
13162            // could mutate the list by calling the various add/remove methods. This prevents
13163            // the array from being modified while we iterate it.
13164            for (OnAttachStateChangeListener listener : listeners) {
13165                listener.onViewDetachedFromWindow(this);
13166            }
13167        }
13168
13169        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13170            mAttachInfo.mScrollContainers.remove(this);
13171            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13172        }
13173
13174        mAttachInfo = null;
13175        if (mOverlay != null) {
13176            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13177        }
13178    }
13179
13180    /**
13181     * Cancel any deferred high-level input events that were previously posted to the event queue.
13182     *
13183     * <p>Many views post high-level events such as click handlers to the event queue
13184     * to run deferred in order to preserve a desired user experience - clearing visible
13185     * pressed states before executing, etc. This method will abort any events of this nature
13186     * that are currently in flight.</p>
13187     *
13188     * <p>Custom views that generate their own high-level deferred input events should override
13189     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13190     *
13191     * <p>This will also cancel pending input events for any child views.</p>
13192     *
13193     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13194     * This will not impact newer events posted after this call that may occur as a result of
13195     * lower-level input events still waiting in the queue. If you are trying to prevent
13196     * double-submitted  events for the duration of some sort of asynchronous transaction
13197     * you should also take other steps to protect against unexpected double inputs e.g. calling
13198     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13199     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13200     */
13201    public final void cancelPendingInputEvents() {
13202        dispatchCancelPendingInputEvents();
13203    }
13204
13205    /**
13206     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13207     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13208     */
13209    void dispatchCancelPendingInputEvents() {
13210        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13211        onCancelPendingInputEvents();
13212        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13213            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13214                    " did not call through to super.onCancelPendingInputEvents()");
13215        }
13216    }
13217
13218    /**
13219     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13220     * a parent view.
13221     *
13222     * <p>This method is responsible for removing any pending high-level input events that were
13223     * posted to the event queue to run later. Custom view classes that post their own deferred
13224     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13225     * {@link android.os.Handler} should override this method, call
13226     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13227     * </p>
13228     */
13229    public void onCancelPendingInputEvents() {
13230        removePerformClickCallback();
13231        cancelLongPress();
13232        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13233    }
13234
13235    /**
13236     * Store this view hierarchy's frozen state into the given container.
13237     *
13238     * @param container The SparseArray in which to save the view's state.
13239     *
13240     * @see #restoreHierarchyState(android.util.SparseArray)
13241     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13242     * @see #onSaveInstanceState()
13243     */
13244    public void saveHierarchyState(SparseArray<Parcelable> container) {
13245        dispatchSaveInstanceState(container);
13246    }
13247
13248    /**
13249     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13250     * this view and its children. May be overridden to modify how freezing happens to a
13251     * view's children; for example, some views may want to not store state for their children.
13252     *
13253     * @param container The SparseArray in which to save the view's state.
13254     *
13255     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13256     * @see #saveHierarchyState(android.util.SparseArray)
13257     * @see #onSaveInstanceState()
13258     */
13259    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13260        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13261            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13262            Parcelable state = onSaveInstanceState();
13263            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13264                throw new IllegalStateException(
13265                        "Derived class did not call super.onSaveInstanceState()");
13266            }
13267            if (state != null) {
13268                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13269                // + ": " + state);
13270                container.put(mID, state);
13271            }
13272        }
13273    }
13274
13275    /**
13276     * Hook allowing a view to generate a representation of its internal state
13277     * that can later be used to create a new instance with that same state.
13278     * This state should only contain information that is not persistent or can
13279     * not be reconstructed later. For example, you will never store your
13280     * current position on screen because that will be computed again when a
13281     * new instance of the view is placed in its view hierarchy.
13282     * <p>
13283     * Some examples of things you may store here: the current cursor position
13284     * in a text view (but usually not the text itself since that is stored in a
13285     * content provider or other persistent storage), the currently selected
13286     * item in a list view.
13287     *
13288     * @return Returns a Parcelable object containing the view's current dynamic
13289     *         state, or null if there is nothing interesting to save. The
13290     *         default implementation returns null.
13291     * @see #onRestoreInstanceState(android.os.Parcelable)
13292     * @see #saveHierarchyState(android.util.SparseArray)
13293     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13294     * @see #setSaveEnabled(boolean)
13295     */
13296    protected Parcelable onSaveInstanceState() {
13297        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13298        return BaseSavedState.EMPTY_STATE;
13299    }
13300
13301    /**
13302     * Restore this view hierarchy's frozen state from the given container.
13303     *
13304     * @param container The SparseArray which holds previously frozen states.
13305     *
13306     * @see #saveHierarchyState(android.util.SparseArray)
13307     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13308     * @see #onRestoreInstanceState(android.os.Parcelable)
13309     */
13310    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13311        dispatchRestoreInstanceState(container);
13312    }
13313
13314    /**
13315     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13316     * state for this view and its children. May be overridden to modify how restoring
13317     * happens to a view's children; for example, some views may want to not store state
13318     * for their children.
13319     *
13320     * @param container The SparseArray which holds previously saved state.
13321     *
13322     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13323     * @see #restoreHierarchyState(android.util.SparseArray)
13324     * @see #onRestoreInstanceState(android.os.Parcelable)
13325     */
13326    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13327        if (mID != NO_ID) {
13328            Parcelable state = container.get(mID);
13329            if (state != null) {
13330                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13331                // + ": " + state);
13332                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13333                onRestoreInstanceState(state);
13334                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13335                    throw new IllegalStateException(
13336                            "Derived class did not call super.onRestoreInstanceState()");
13337                }
13338            }
13339        }
13340    }
13341
13342    /**
13343     * Hook allowing a view to re-apply a representation of its internal state that had previously
13344     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13345     * null state.
13346     *
13347     * @param state The frozen state that had previously been returned by
13348     *        {@link #onSaveInstanceState}.
13349     *
13350     * @see #onSaveInstanceState()
13351     * @see #restoreHierarchyState(android.util.SparseArray)
13352     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13353     */
13354    protected void onRestoreInstanceState(Parcelable state) {
13355        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13356        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13357            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13358                    + "received " + state.getClass().toString() + " instead. This usually happens "
13359                    + "when two views of different type have the same id in the same hierarchy. "
13360                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13361                    + "other views do not use the same id.");
13362        }
13363    }
13364
13365    /**
13366     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13367     *
13368     * @return the drawing start time in milliseconds
13369     */
13370    public long getDrawingTime() {
13371        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13372    }
13373
13374    /**
13375     * <p>Enables or disables the duplication of the parent's state into this view. When
13376     * duplication is enabled, this view gets its drawable state from its parent rather
13377     * than from its own internal properties.</p>
13378     *
13379     * <p>Note: in the current implementation, setting this property to true after the
13380     * view was added to a ViewGroup might have no effect at all. This property should
13381     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13382     *
13383     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13384     * property is enabled, an exception will be thrown.</p>
13385     *
13386     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13387     * parent, these states should not be affected by this method.</p>
13388     *
13389     * @param enabled True to enable duplication of the parent's drawable state, false
13390     *                to disable it.
13391     *
13392     * @see #getDrawableState()
13393     * @see #isDuplicateParentStateEnabled()
13394     */
13395    public void setDuplicateParentStateEnabled(boolean enabled) {
13396        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13397    }
13398
13399    /**
13400     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13401     *
13402     * @return True if this view's drawable state is duplicated from the parent,
13403     *         false otherwise
13404     *
13405     * @see #getDrawableState()
13406     * @see #setDuplicateParentStateEnabled(boolean)
13407     */
13408    public boolean isDuplicateParentStateEnabled() {
13409        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13410    }
13411
13412    /**
13413     * <p>Specifies the type of layer backing this view. The layer can be
13414     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13415     * {@link #LAYER_TYPE_HARDWARE}.</p>
13416     *
13417     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13418     * instance that controls how the layer is composed on screen. The following
13419     * properties of the paint are taken into account when composing the layer:</p>
13420     * <ul>
13421     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13422     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13423     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13424     * </ul>
13425     *
13426     * <p>If this view has an alpha value set to < 1.0 by calling
13427     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13428     * by this view's alpha value.</p>
13429     *
13430     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13431     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13432     * for more information on when and how to use layers.</p>
13433     *
13434     * @param layerType The type of layer to use with this view, must be one of
13435     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13436     *        {@link #LAYER_TYPE_HARDWARE}
13437     * @param paint The paint used to compose the layer. This argument is optional
13438     *        and can be null. It is ignored when the layer type is
13439     *        {@link #LAYER_TYPE_NONE}
13440     *
13441     * @see #getLayerType()
13442     * @see #LAYER_TYPE_NONE
13443     * @see #LAYER_TYPE_SOFTWARE
13444     * @see #LAYER_TYPE_HARDWARE
13445     * @see #setAlpha(float)
13446     *
13447     * @attr ref android.R.styleable#View_layerType
13448     */
13449    public void setLayerType(int layerType, Paint paint) {
13450        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13451            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13452                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13453        }
13454
13455        boolean typeChanged = mRenderNode.setLayerType(layerType);
13456
13457        if (!typeChanged) {
13458            setLayerPaint(paint);
13459            return;
13460        }
13461
13462        // Destroy any previous software drawing cache if needed
13463        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13464            destroyDrawingCache();
13465        }
13466
13467        mLayerType = layerType;
13468        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13469        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13470        mRenderNode.setLayerPaint(mLayerPaint);
13471
13472        // draw() behaves differently if we are on a layer, so we need to
13473        // invalidate() here
13474        invalidateParentCaches();
13475        invalidate(true);
13476    }
13477
13478    /**
13479     * Updates the {@link Paint} object used with the current layer (used only if the current
13480     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13481     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13482     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13483     * ensure that the view gets redrawn immediately.
13484     *
13485     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13486     * instance that controls how the layer is composed on screen. The following
13487     * properties of the paint are taken into account when composing the layer:</p>
13488     * <ul>
13489     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13490     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13491     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13492     * </ul>
13493     *
13494     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13495     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13496     *
13497     * @param paint The paint used to compose the layer. This argument is optional
13498     *        and can be null. It is ignored when the layer type is
13499     *        {@link #LAYER_TYPE_NONE}
13500     *
13501     * @see #setLayerType(int, android.graphics.Paint)
13502     */
13503    public void setLayerPaint(Paint paint) {
13504        int layerType = getLayerType();
13505        if (layerType != LAYER_TYPE_NONE) {
13506            mLayerPaint = paint == null ? new Paint() : paint;
13507            if (layerType == LAYER_TYPE_HARDWARE) {
13508                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13509                    invalidateViewProperty(false, false);
13510                }
13511            } else {
13512                invalidate();
13513            }
13514        }
13515    }
13516
13517    /**
13518     * Indicates whether this view has a static layer. A view with layer type
13519     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13520     * dynamic.
13521     */
13522    boolean hasStaticLayer() {
13523        return true;
13524    }
13525
13526    /**
13527     * Indicates what type of layer is currently associated with this view. By default
13528     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13529     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13530     * for more information on the different types of layers.
13531     *
13532     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13533     *         {@link #LAYER_TYPE_HARDWARE}
13534     *
13535     * @see #setLayerType(int, android.graphics.Paint)
13536     * @see #buildLayer()
13537     * @see #LAYER_TYPE_NONE
13538     * @see #LAYER_TYPE_SOFTWARE
13539     * @see #LAYER_TYPE_HARDWARE
13540     */
13541    public int getLayerType() {
13542        return mLayerType;
13543    }
13544
13545    /**
13546     * Forces this view's layer to be created and this view to be rendered
13547     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13548     * invoking this method will have no effect.
13549     *
13550     * This method can for instance be used to render a view into its layer before
13551     * starting an animation. If this view is complex, rendering into the layer
13552     * before starting the animation will avoid skipping frames.
13553     *
13554     * @throws IllegalStateException If this view is not attached to a window
13555     *
13556     * @see #setLayerType(int, android.graphics.Paint)
13557     */
13558    public void buildLayer() {
13559        if (mLayerType == LAYER_TYPE_NONE) return;
13560
13561        final AttachInfo attachInfo = mAttachInfo;
13562        if (attachInfo == null) {
13563            throw new IllegalStateException("This view must be attached to a window first");
13564        }
13565
13566        if (getWidth() == 0 || getHeight() == 0) {
13567            return;
13568        }
13569
13570        switch (mLayerType) {
13571            case LAYER_TYPE_HARDWARE:
13572                // The only part of a hardware layer we can build in response to
13573                // this call is to ensure the display list is up to date.
13574                // The actual rendering of the display list into the layer must
13575                // be done at playback time
13576                updateDisplayListIfDirty();
13577                break;
13578            case LAYER_TYPE_SOFTWARE:
13579                buildDrawingCache(true);
13580                break;
13581        }
13582    }
13583
13584    /**
13585     * If this View draws with a HardwareLayer, returns it.
13586     * Otherwise returns null
13587     *
13588     * TODO: Only TextureView uses this, can we eliminate it?
13589     */
13590    HardwareLayer getHardwareLayer() {
13591        return null;
13592    }
13593
13594    /**
13595     * Destroys all hardware rendering resources. This method is invoked
13596     * when the system needs to reclaim resources. Upon execution of this
13597     * method, you should free any OpenGL resources created by the view.
13598     *
13599     * Note: you <strong>must</strong> call
13600     * <code>super.destroyHardwareResources()</code> when overriding
13601     * this method.
13602     *
13603     * @hide
13604     */
13605    protected void destroyHardwareResources() {
13606        // Although the Layer will be destroyed by RenderNode, we want to release
13607        // the staging display list, which is also a signal to RenderNode that it's
13608        // safe to free its copy of the display list as it knows that we will
13609        // push an updated DisplayList if we try to draw again
13610        resetDisplayList();
13611    }
13612
13613    /**
13614     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13615     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13616     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13617     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13618     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13619     * null.</p>
13620     *
13621     * <p>Enabling the drawing cache is similar to
13622     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13623     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13624     * drawing cache has no effect on rendering because the system uses a different mechanism
13625     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13626     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13627     * for information on how to enable software and hardware layers.</p>
13628     *
13629     * <p>This API can be used to manually generate
13630     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13631     * {@link #getDrawingCache()}.</p>
13632     *
13633     * @param enabled true to enable the drawing cache, false otherwise
13634     *
13635     * @see #isDrawingCacheEnabled()
13636     * @see #getDrawingCache()
13637     * @see #buildDrawingCache()
13638     * @see #setLayerType(int, android.graphics.Paint)
13639     */
13640    public void setDrawingCacheEnabled(boolean enabled) {
13641        mCachingFailed = false;
13642        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13643    }
13644
13645    /**
13646     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13647     *
13648     * @return true if the drawing cache is enabled
13649     *
13650     * @see #setDrawingCacheEnabled(boolean)
13651     * @see #getDrawingCache()
13652     */
13653    @ViewDebug.ExportedProperty(category = "drawing")
13654    public boolean isDrawingCacheEnabled() {
13655        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13656    }
13657
13658    /**
13659     * Debugging utility which recursively outputs the dirty state of a view and its
13660     * descendants.
13661     *
13662     * @hide
13663     */
13664    @SuppressWarnings({"UnusedDeclaration"})
13665    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13666        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13667                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13668                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13669                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13670        if (clear) {
13671            mPrivateFlags &= clearMask;
13672        }
13673        if (this instanceof ViewGroup) {
13674            ViewGroup parent = (ViewGroup) this;
13675            final int count = parent.getChildCount();
13676            for (int i = 0; i < count; i++) {
13677                final View child = parent.getChildAt(i);
13678                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13679            }
13680        }
13681    }
13682
13683    /**
13684     * This method is used by ViewGroup to cause its children to restore or recreate their
13685     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13686     * to recreate its own display list, which would happen if it went through the normal
13687     * draw/dispatchDraw mechanisms.
13688     *
13689     * @hide
13690     */
13691    protected void dispatchGetDisplayList() {}
13692
13693    /**
13694     * A view that is not attached or hardware accelerated cannot create a display list.
13695     * This method checks these conditions and returns the appropriate result.
13696     *
13697     * @return true if view has the ability to create a display list, false otherwise.
13698     *
13699     * @hide
13700     */
13701    public boolean canHaveDisplayList() {
13702        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13703    }
13704
13705    private void updateDisplayListIfDirty() {
13706        final RenderNode renderNode = mRenderNode;
13707        if (!canHaveDisplayList()) {
13708            // can't populate RenderNode, don't try
13709            return;
13710        }
13711
13712        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13713                || !renderNode.isValid()
13714                || (mRecreateDisplayList)) {
13715            // Don't need to recreate the display list, just need to tell our
13716            // children to restore/recreate theirs
13717            if (renderNode.isValid()
13718                    && !mRecreateDisplayList) {
13719                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13720                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13721                dispatchGetDisplayList();
13722
13723                return; // no work needed
13724            }
13725
13726            // If we got here, we're recreating it. Mark it as such to ensure that
13727            // we copy in child display lists into ours in drawChild()
13728            mRecreateDisplayList = true;
13729
13730            int width = mRight - mLeft;
13731            int height = mBottom - mTop;
13732            int layerType = getLayerType();
13733
13734            final HardwareCanvas canvas = renderNode.start(width, height);
13735            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13736
13737            try {
13738                final HardwareLayer layer = getHardwareLayer();
13739                if (layer != null && layer.isValid()) {
13740                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13741                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13742                    buildDrawingCache(true);
13743                    Bitmap cache = getDrawingCache(true);
13744                    if (cache != null) {
13745                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13746                    }
13747                } else {
13748                    computeScroll();
13749
13750                    canvas.translate(-mScrollX, -mScrollY);
13751                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13752                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13753
13754                    // Fast path for layouts with no backgrounds
13755                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13756                        dispatchDraw(canvas);
13757                        if (mOverlay != null && !mOverlay.isEmpty()) {
13758                            mOverlay.getOverlayView().draw(canvas);
13759                        }
13760                    } else {
13761                        draw(canvas);
13762                    }
13763                }
13764            } finally {
13765                renderNode.end(canvas);
13766                setDisplayListProperties(renderNode);
13767            }
13768        } else {
13769            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13770            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13771        }
13772    }
13773
13774    /**
13775     * Returns a RenderNode with View draw content recorded, which can be
13776     * used to draw this view again without executing its draw method.
13777     *
13778     * @return A RenderNode ready to replay, or null if caching is not enabled.
13779     *
13780     * @hide
13781     */
13782    public RenderNode getDisplayList() {
13783        updateDisplayListIfDirty();
13784        return mRenderNode;
13785    }
13786
13787    private void resetDisplayList() {
13788        if (mRenderNode.isValid()) {
13789            mRenderNode.destroyDisplayListData();
13790        }
13791
13792        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13793            mBackgroundRenderNode.destroyDisplayListData();
13794        }
13795    }
13796
13797    /**
13798     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13799     *
13800     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13801     *
13802     * @see #getDrawingCache(boolean)
13803     */
13804    public Bitmap getDrawingCache() {
13805        return getDrawingCache(false);
13806    }
13807
13808    /**
13809     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13810     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13811     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13812     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13813     * request the drawing cache by calling this method and draw it on screen if the
13814     * returned bitmap is not null.</p>
13815     *
13816     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13817     * this method will create a bitmap of the same size as this view. Because this bitmap
13818     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13819     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13820     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13821     * size than the view. This implies that your application must be able to handle this
13822     * size.</p>
13823     *
13824     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13825     *        the current density of the screen when the application is in compatibility
13826     *        mode.
13827     *
13828     * @return A bitmap representing this view or null if cache is disabled.
13829     *
13830     * @see #setDrawingCacheEnabled(boolean)
13831     * @see #isDrawingCacheEnabled()
13832     * @see #buildDrawingCache(boolean)
13833     * @see #destroyDrawingCache()
13834     */
13835    public Bitmap getDrawingCache(boolean autoScale) {
13836        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13837            return null;
13838        }
13839        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13840            buildDrawingCache(autoScale);
13841        }
13842        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13843    }
13844
13845    /**
13846     * <p>Frees the resources used by the drawing cache. If you call
13847     * {@link #buildDrawingCache()} manually without calling
13848     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13849     * should cleanup the cache with this method afterwards.</p>
13850     *
13851     * @see #setDrawingCacheEnabled(boolean)
13852     * @see #buildDrawingCache()
13853     * @see #getDrawingCache()
13854     */
13855    public void destroyDrawingCache() {
13856        if (mDrawingCache != null) {
13857            mDrawingCache.recycle();
13858            mDrawingCache = null;
13859        }
13860        if (mUnscaledDrawingCache != null) {
13861            mUnscaledDrawingCache.recycle();
13862            mUnscaledDrawingCache = null;
13863        }
13864    }
13865
13866    /**
13867     * Setting a solid background color for the drawing cache's bitmaps will improve
13868     * performance and memory usage. Note, though that this should only be used if this
13869     * view will always be drawn on top of a solid color.
13870     *
13871     * @param color The background color to use for the drawing cache's bitmap
13872     *
13873     * @see #setDrawingCacheEnabled(boolean)
13874     * @see #buildDrawingCache()
13875     * @see #getDrawingCache()
13876     */
13877    public void setDrawingCacheBackgroundColor(int color) {
13878        if (color != mDrawingCacheBackgroundColor) {
13879            mDrawingCacheBackgroundColor = color;
13880            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13881        }
13882    }
13883
13884    /**
13885     * @see #setDrawingCacheBackgroundColor(int)
13886     *
13887     * @return The background color to used for the drawing cache's bitmap
13888     */
13889    public int getDrawingCacheBackgroundColor() {
13890        return mDrawingCacheBackgroundColor;
13891    }
13892
13893    /**
13894     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13895     *
13896     * @see #buildDrawingCache(boolean)
13897     */
13898    public void buildDrawingCache() {
13899        buildDrawingCache(false);
13900    }
13901
13902    /**
13903     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13904     *
13905     * <p>If you call {@link #buildDrawingCache()} manually without calling
13906     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13907     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13908     *
13909     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13910     * this method will create a bitmap of the same size as this view. Because this bitmap
13911     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13912     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13913     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13914     * size than the view. This implies that your application must be able to handle this
13915     * size.</p>
13916     *
13917     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13918     * you do not need the drawing cache bitmap, calling this method will increase memory
13919     * usage and cause the view to be rendered in software once, thus negatively impacting
13920     * performance.</p>
13921     *
13922     * @see #getDrawingCache()
13923     * @see #destroyDrawingCache()
13924     */
13925    public void buildDrawingCache(boolean autoScale) {
13926        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13927                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13928            mCachingFailed = false;
13929
13930            int width = mRight - mLeft;
13931            int height = mBottom - mTop;
13932
13933            final AttachInfo attachInfo = mAttachInfo;
13934            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13935
13936            if (autoScale && scalingRequired) {
13937                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13938                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13939            }
13940
13941            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13942            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13943            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13944
13945            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13946            final long drawingCacheSize =
13947                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13948            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13949                if (width > 0 && height > 0) {
13950                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13951                            + projectedBitmapSize + " bytes, only "
13952                            + drawingCacheSize + " available");
13953                }
13954                destroyDrawingCache();
13955                mCachingFailed = true;
13956                return;
13957            }
13958
13959            boolean clear = true;
13960            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13961
13962            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13963                Bitmap.Config quality;
13964                if (!opaque) {
13965                    // Never pick ARGB_4444 because it looks awful
13966                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13967                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13968                        case DRAWING_CACHE_QUALITY_AUTO:
13969                        case DRAWING_CACHE_QUALITY_LOW:
13970                        case DRAWING_CACHE_QUALITY_HIGH:
13971                        default:
13972                            quality = Bitmap.Config.ARGB_8888;
13973                            break;
13974                    }
13975                } else {
13976                    // Optimization for translucent windows
13977                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13978                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13979                }
13980
13981                // Try to cleanup memory
13982                if (bitmap != null) bitmap.recycle();
13983
13984                try {
13985                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13986                            width, height, quality);
13987                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13988                    if (autoScale) {
13989                        mDrawingCache = bitmap;
13990                    } else {
13991                        mUnscaledDrawingCache = bitmap;
13992                    }
13993                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13994                } catch (OutOfMemoryError e) {
13995                    // If there is not enough memory to create the bitmap cache, just
13996                    // ignore the issue as bitmap caches are not required to draw the
13997                    // view hierarchy
13998                    if (autoScale) {
13999                        mDrawingCache = null;
14000                    } else {
14001                        mUnscaledDrawingCache = null;
14002                    }
14003                    mCachingFailed = true;
14004                    return;
14005                }
14006
14007                clear = drawingCacheBackgroundColor != 0;
14008            }
14009
14010            Canvas canvas;
14011            if (attachInfo != null) {
14012                canvas = attachInfo.mCanvas;
14013                if (canvas == null) {
14014                    canvas = new Canvas();
14015                }
14016                canvas.setBitmap(bitmap);
14017                // Temporarily clobber the cached Canvas in case one of our children
14018                // is also using a drawing cache. Without this, the children would
14019                // steal the canvas by attaching their own bitmap to it and bad, bad
14020                // thing would happen (invisible views, corrupted drawings, etc.)
14021                attachInfo.mCanvas = null;
14022            } else {
14023                // This case should hopefully never or seldom happen
14024                canvas = new Canvas(bitmap);
14025            }
14026
14027            if (clear) {
14028                bitmap.eraseColor(drawingCacheBackgroundColor);
14029            }
14030
14031            computeScroll();
14032            final int restoreCount = canvas.save();
14033
14034            if (autoScale && scalingRequired) {
14035                final float scale = attachInfo.mApplicationScale;
14036                canvas.scale(scale, scale);
14037            }
14038
14039            canvas.translate(-mScrollX, -mScrollY);
14040
14041            mPrivateFlags |= PFLAG_DRAWN;
14042            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14043                    mLayerType != LAYER_TYPE_NONE) {
14044                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14045            }
14046
14047            // Fast path for layouts with no backgrounds
14048            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14049                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14050                dispatchDraw(canvas);
14051                if (mOverlay != null && !mOverlay.isEmpty()) {
14052                    mOverlay.getOverlayView().draw(canvas);
14053                }
14054            } else {
14055                draw(canvas);
14056            }
14057
14058            canvas.restoreToCount(restoreCount);
14059            canvas.setBitmap(null);
14060
14061            if (attachInfo != null) {
14062                // Restore the cached Canvas for our siblings
14063                attachInfo.mCanvas = canvas;
14064            }
14065        }
14066    }
14067
14068    /**
14069     * Create a snapshot of the view into a bitmap.  We should probably make
14070     * some form of this public, but should think about the API.
14071     */
14072    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14073        int width = mRight - mLeft;
14074        int height = mBottom - mTop;
14075
14076        final AttachInfo attachInfo = mAttachInfo;
14077        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14078        width = (int) ((width * scale) + 0.5f);
14079        height = (int) ((height * scale) + 0.5f);
14080
14081        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14082                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14083        if (bitmap == null) {
14084            throw new OutOfMemoryError();
14085        }
14086
14087        Resources resources = getResources();
14088        if (resources != null) {
14089            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14090        }
14091
14092        Canvas canvas;
14093        if (attachInfo != null) {
14094            canvas = attachInfo.mCanvas;
14095            if (canvas == null) {
14096                canvas = new Canvas();
14097            }
14098            canvas.setBitmap(bitmap);
14099            // Temporarily clobber the cached Canvas in case one of our children
14100            // is also using a drawing cache. Without this, the children would
14101            // steal the canvas by attaching their own bitmap to it and bad, bad
14102            // things would happen (invisible views, corrupted drawings, etc.)
14103            attachInfo.mCanvas = null;
14104        } else {
14105            // This case should hopefully never or seldom happen
14106            canvas = new Canvas(bitmap);
14107        }
14108
14109        if ((backgroundColor & 0xff000000) != 0) {
14110            bitmap.eraseColor(backgroundColor);
14111        }
14112
14113        computeScroll();
14114        final int restoreCount = canvas.save();
14115        canvas.scale(scale, scale);
14116        canvas.translate(-mScrollX, -mScrollY);
14117
14118        // Temporarily remove the dirty mask
14119        int flags = mPrivateFlags;
14120        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14121
14122        // Fast path for layouts with no backgrounds
14123        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14124            dispatchDraw(canvas);
14125            if (mOverlay != null && !mOverlay.isEmpty()) {
14126                mOverlay.getOverlayView().draw(canvas);
14127            }
14128        } else {
14129            draw(canvas);
14130        }
14131
14132        mPrivateFlags = flags;
14133
14134        canvas.restoreToCount(restoreCount);
14135        canvas.setBitmap(null);
14136
14137        if (attachInfo != null) {
14138            // Restore the cached Canvas for our siblings
14139            attachInfo.mCanvas = canvas;
14140        }
14141
14142        return bitmap;
14143    }
14144
14145    /**
14146     * Indicates whether this View is currently in edit mode. A View is usually
14147     * in edit mode when displayed within a developer tool. For instance, if
14148     * this View is being drawn by a visual user interface builder, this method
14149     * should return true.
14150     *
14151     * Subclasses should check the return value of this method to provide
14152     * different behaviors if their normal behavior might interfere with the
14153     * host environment. For instance: the class spawns a thread in its
14154     * constructor, the drawing code relies on device-specific features, etc.
14155     *
14156     * This method is usually checked in the drawing code of custom widgets.
14157     *
14158     * @return True if this View is in edit mode, false otherwise.
14159     */
14160    public boolean isInEditMode() {
14161        return false;
14162    }
14163
14164    /**
14165     * If the View draws content inside its padding and enables fading edges,
14166     * it needs to support padding offsets. Padding offsets are added to the
14167     * fading edges to extend the length of the fade so that it covers pixels
14168     * drawn inside the padding.
14169     *
14170     * Subclasses of this class should override this method if they need
14171     * to draw content inside the padding.
14172     *
14173     * @return True if padding offset must be applied, false otherwise.
14174     *
14175     * @see #getLeftPaddingOffset()
14176     * @see #getRightPaddingOffset()
14177     * @see #getTopPaddingOffset()
14178     * @see #getBottomPaddingOffset()
14179     *
14180     * @since CURRENT
14181     */
14182    protected boolean isPaddingOffsetRequired() {
14183        return false;
14184    }
14185
14186    /**
14187     * Amount by which to extend the left fading region. Called only when
14188     * {@link #isPaddingOffsetRequired()} returns true.
14189     *
14190     * @return The left padding offset in pixels.
14191     *
14192     * @see #isPaddingOffsetRequired()
14193     *
14194     * @since CURRENT
14195     */
14196    protected int getLeftPaddingOffset() {
14197        return 0;
14198    }
14199
14200    /**
14201     * Amount by which to extend the right fading region. Called only when
14202     * {@link #isPaddingOffsetRequired()} returns true.
14203     *
14204     * @return The right padding offset in pixels.
14205     *
14206     * @see #isPaddingOffsetRequired()
14207     *
14208     * @since CURRENT
14209     */
14210    protected int getRightPaddingOffset() {
14211        return 0;
14212    }
14213
14214    /**
14215     * Amount by which to extend the top fading region. Called only when
14216     * {@link #isPaddingOffsetRequired()} returns true.
14217     *
14218     * @return The top padding offset in pixels.
14219     *
14220     * @see #isPaddingOffsetRequired()
14221     *
14222     * @since CURRENT
14223     */
14224    protected int getTopPaddingOffset() {
14225        return 0;
14226    }
14227
14228    /**
14229     * Amount by which to extend the bottom fading region. Called only when
14230     * {@link #isPaddingOffsetRequired()} returns true.
14231     *
14232     * @return The bottom padding offset in pixels.
14233     *
14234     * @see #isPaddingOffsetRequired()
14235     *
14236     * @since CURRENT
14237     */
14238    protected int getBottomPaddingOffset() {
14239        return 0;
14240    }
14241
14242    /**
14243     * @hide
14244     * @param offsetRequired
14245     */
14246    protected int getFadeTop(boolean offsetRequired) {
14247        int top = mPaddingTop;
14248        if (offsetRequired) top += getTopPaddingOffset();
14249        return top;
14250    }
14251
14252    /**
14253     * @hide
14254     * @param offsetRequired
14255     */
14256    protected int getFadeHeight(boolean offsetRequired) {
14257        int padding = mPaddingTop;
14258        if (offsetRequired) padding += getTopPaddingOffset();
14259        return mBottom - mTop - mPaddingBottom - padding;
14260    }
14261
14262    /**
14263     * <p>Indicates whether this view is attached to a hardware accelerated
14264     * window or not.</p>
14265     *
14266     * <p>Even if this method returns true, it does not mean that every call
14267     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14268     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14269     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14270     * window is hardware accelerated,
14271     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14272     * return false, and this method will return true.</p>
14273     *
14274     * @return True if the view is attached to a window and the window is
14275     *         hardware accelerated; false in any other case.
14276     */
14277    @ViewDebug.ExportedProperty(category = "drawing")
14278    public boolean isHardwareAccelerated() {
14279        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14280    }
14281
14282    /**
14283     * Sets a rectangular area on this view to which the view will be clipped
14284     * when it is drawn. Setting the value to null will remove the clip bounds
14285     * and the view will draw normally, using its full bounds.
14286     *
14287     * @param clipBounds The rectangular area, in the local coordinates of
14288     * this view, to which future drawing operations will be clipped.
14289     */
14290    public void setClipBounds(Rect clipBounds) {
14291        if (clipBounds != null) {
14292            if (clipBounds.equals(mClipBounds)) {
14293                return;
14294            }
14295            if (mClipBounds == null) {
14296                invalidate();
14297                mClipBounds = new Rect(clipBounds);
14298            } else {
14299                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14300                        Math.min(mClipBounds.top, clipBounds.top),
14301                        Math.max(mClipBounds.right, clipBounds.right),
14302                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14303                mClipBounds.set(clipBounds);
14304            }
14305        } else {
14306            if (mClipBounds != null) {
14307                invalidate();
14308                mClipBounds = null;
14309            }
14310        }
14311        mRenderNode.setClipBounds(mClipBounds);
14312    }
14313
14314    /**
14315     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14316     *
14317     * @return A copy of the current clip bounds if clip bounds are set,
14318     * otherwise null.
14319     */
14320    public Rect getClipBounds() {
14321        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14322    }
14323
14324    /**
14325     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14326     * case of an active Animation being run on the view.
14327     */
14328    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14329            Animation a, boolean scalingRequired) {
14330        Transformation invalidationTransform;
14331        final int flags = parent.mGroupFlags;
14332        final boolean initialized = a.isInitialized();
14333        if (!initialized) {
14334            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14335            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14336            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14337            onAnimationStart();
14338        }
14339
14340        final Transformation t = parent.getChildTransformation();
14341        boolean more = a.getTransformation(drawingTime, t, 1f);
14342        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14343            if (parent.mInvalidationTransformation == null) {
14344                parent.mInvalidationTransformation = new Transformation();
14345            }
14346            invalidationTransform = parent.mInvalidationTransformation;
14347            a.getTransformation(drawingTime, invalidationTransform, 1f);
14348        } else {
14349            invalidationTransform = t;
14350        }
14351
14352        if (more) {
14353            if (!a.willChangeBounds()) {
14354                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14355                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14356                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14357                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14358                    // The child need to draw an animation, potentially offscreen, so
14359                    // make sure we do not cancel invalidate requests
14360                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14361                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14362                }
14363            } else {
14364                if (parent.mInvalidateRegion == null) {
14365                    parent.mInvalidateRegion = new RectF();
14366                }
14367                final RectF region = parent.mInvalidateRegion;
14368                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14369                        invalidationTransform);
14370
14371                // The child need to draw an animation, potentially offscreen, so
14372                // make sure we do not cancel invalidate requests
14373                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14374
14375                final int left = mLeft + (int) region.left;
14376                final int top = mTop + (int) region.top;
14377                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14378                        top + (int) (region.height() + .5f));
14379            }
14380        }
14381        return more;
14382    }
14383
14384    /**
14385     * This method is called by getDisplayList() when a display list is recorded for a View.
14386     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14387     */
14388    void setDisplayListProperties(RenderNode renderNode) {
14389        if (renderNode != null) {
14390            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14391            if (mParent instanceof ViewGroup) {
14392                renderNode.setClipToBounds(
14393                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14394            }
14395            float alpha = 1;
14396            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14397                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14398                ViewGroup parentVG = (ViewGroup) mParent;
14399                final Transformation t = parentVG.getChildTransformation();
14400                if (parentVG.getChildStaticTransformation(this, t)) {
14401                    final int transformType = t.getTransformationType();
14402                    if (transformType != Transformation.TYPE_IDENTITY) {
14403                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14404                            alpha = t.getAlpha();
14405                        }
14406                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14407                            renderNode.setStaticMatrix(t.getMatrix());
14408                        }
14409                    }
14410                }
14411            }
14412            if (mTransformationInfo != null) {
14413                alpha *= getFinalAlpha();
14414                if (alpha < 1) {
14415                    final int multipliedAlpha = (int) (255 * alpha);
14416                    if (onSetAlpha(multipliedAlpha)) {
14417                        alpha = 1;
14418                    }
14419                }
14420                renderNode.setAlpha(alpha);
14421            } else if (alpha < 1) {
14422                renderNode.setAlpha(alpha);
14423            }
14424        }
14425    }
14426
14427    /**
14428     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14429     * This draw() method is an implementation detail and is not intended to be overridden or
14430     * to be called from anywhere else other than ViewGroup.drawChild().
14431     */
14432    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14433        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14434        boolean more = false;
14435        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14436        final int flags = parent.mGroupFlags;
14437
14438        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14439            parent.getChildTransformation().clear();
14440            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14441        }
14442
14443        Transformation transformToApply = null;
14444        boolean concatMatrix = false;
14445
14446        boolean scalingRequired = false;
14447        boolean caching;
14448        int layerType = getLayerType();
14449
14450        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14451        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14452                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14453            caching = true;
14454            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14455            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14456        } else {
14457            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14458        }
14459
14460        final Animation a = getAnimation();
14461        if (a != null) {
14462            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14463            concatMatrix = a.willChangeTransformationMatrix();
14464            if (concatMatrix) {
14465                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14466            }
14467            transformToApply = parent.getChildTransformation();
14468        } else {
14469            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14470                // No longer animating: clear out old animation matrix
14471                mRenderNode.setAnimationMatrix(null);
14472                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14473            }
14474            if (!usingRenderNodeProperties &&
14475                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14476                final Transformation t = parent.getChildTransformation();
14477                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14478                if (hasTransform) {
14479                    final int transformType = t.getTransformationType();
14480                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14481                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14482                }
14483            }
14484        }
14485
14486        concatMatrix |= !childHasIdentityMatrix;
14487
14488        // Sets the flag as early as possible to allow draw() implementations
14489        // to call invalidate() successfully when doing animations
14490        mPrivateFlags |= PFLAG_DRAWN;
14491
14492        if (!concatMatrix &&
14493                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14494                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14495                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14496                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14497            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14498            return more;
14499        }
14500        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14501
14502        if (hardwareAccelerated) {
14503            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14504            // retain the flag's value temporarily in the mRecreateDisplayList flag
14505            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14506            mPrivateFlags &= ~PFLAG_INVALIDATED;
14507        }
14508
14509        RenderNode renderNode = null;
14510        Bitmap cache = null;
14511        boolean hasDisplayList = false;
14512        if (caching) {
14513            if (!hardwareAccelerated) {
14514                if (layerType != LAYER_TYPE_NONE) {
14515                    layerType = LAYER_TYPE_SOFTWARE;
14516                    buildDrawingCache(true);
14517                }
14518                cache = getDrawingCache(true);
14519            } else {
14520                switch (layerType) {
14521                    case LAYER_TYPE_SOFTWARE:
14522                        if (usingRenderNodeProperties) {
14523                            hasDisplayList = canHaveDisplayList();
14524                        } else {
14525                            buildDrawingCache(true);
14526                            cache = getDrawingCache(true);
14527                        }
14528                        break;
14529                    case LAYER_TYPE_HARDWARE:
14530                        if (usingRenderNodeProperties) {
14531                            hasDisplayList = canHaveDisplayList();
14532                        }
14533                        break;
14534                    case LAYER_TYPE_NONE:
14535                        // Delay getting the display list until animation-driven alpha values are
14536                        // set up and possibly passed on to the view
14537                        hasDisplayList = canHaveDisplayList();
14538                        break;
14539                }
14540            }
14541        }
14542        usingRenderNodeProperties &= hasDisplayList;
14543        if (usingRenderNodeProperties) {
14544            renderNode = getDisplayList();
14545            if (!renderNode.isValid()) {
14546                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14547                // to getDisplayList(), the display list will be marked invalid and we should not
14548                // try to use it again.
14549                renderNode = null;
14550                hasDisplayList = false;
14551                usingRenderNodeProperties = false;
14552            }
14553        }
14554
14555        int sx = 0;
14556        int sy = 0;
14557        if (!hasDisplayList) {
14558            computeScroll();
14559            sx = mScrollX;
14560            sy = mScrollY;
14561        }
14562
14563        final boolean hasNoCache = cache == null || hasDisplayList;
14564        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14565                layerType != LAYER_TYPE_HARDWARE;
14566
14567        int restoreTo = -1;
14568        if (!usingRenderNodeProperties || transformToApply != null) {
14569            restoreTo = canvas.save();
14570        }
14571        if (offsetForScroll) {
14572            canvas.translate(mLeft - sx, mTop - sy);
14573        } else {
14574            if (!usingRenderNodeProperties) {
14575                canvas.translate(mLeft, mTop);
14576            }
14577            if (scalingRequired) {
14578                if (usingRenderNodeProperties) {
14579                    // TODO: Might not need this if we put everything inside the DL
14580                    restoreTo = canvas.save();
14581                }
14582                // mAttachInfo cannot be null, otherwise scalingRequired == false
14583                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14584                canvas.scale(scale, scale);
14585            }
14586        }
14587
14588        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14589        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14590                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14591            if (transformToApply != null || !childHasIdentityMatrix) {
14592                int transX = 0;
14593                int transY = 0;
14594
14595                if (offsetForScroll) {
14596                    transX = -sx;
14597                    transY = -sy;
14598                }
14599
14600                if (transformToApply != null) {
14601                    if (concatMatrix) {
14602                        if (usingRenderNodeProperties) {
14603                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14604                        } else {
14605                            // Undo the scroll translation, apply the transformation matrix,
14606                            // then redo the scroll translate to get the correct result.
14607                            canvas.translate(-transX, -transY);
14608                            canvas.concat(transformToApply.getMatrix());
14609                            canvas.translate(transX, transY);
14610                        }
14611                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14612                    }
14613
14614                    float transformAlpha = transformToApply.getAlpha();
14615                    if (transformAlpha < 1) {
14616                        alpha *= transformAlpha;
14617                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14618                    }
14619                }
14620
14621                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14622                    canvas.translate(-transX, -transY);
14623                    canvas.concat(getMatrix());
14624                    canvas.translate(transX, transY);
14625                }
14626            }
14627
14628            // Deal with alpha if it is or used to be <1
14629            if (alpha < 1 ||
14630                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14631                if (alpha < 1) {
14632                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14633                } else {
14634                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14635                }
14636                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14637                if (hasNoCache) {
14638                    final int multipliedAlpha = (int) (255 * alpha);
14639                    if (!onSetAlpha(multipliedAlpha)) {
14640                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14641                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14642                                layerType != LAYER_TYPE_NONE) {
14643                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14644                        }
14645                        if (usingRenderNodeProperties) {
14646                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14647                        } else  if (layerType == LAYER_TYPE_NONE) {
14648                            final int scrollX = hasDisplayList ? 0 : sx;
14649                            final int scrollY = hasDisplayList ? 0 : sy;
14650                            canvas.saveLayerAlpha(scrollX, scrollY,
14651                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14652                                    multipliedAlpha, layerFlags);
14653                        }
14654                    } else {
14655                        // Alpha is handled by the child directly, clobber the layer's alpha
14656                        mPrivateFlags |= PFLAG_ALPHA_SET;
14657                    }
14658                }
14659            }
14660        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14661            onSetAlpha(255);
14662            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14663        }
14664
14665        if (!usingRenderNodeProperties) {
14666            // apply clips directly, since RenderNode won't do it for this draw
14667            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14668                    && cache == null) {
14669                if (offsetForScroll) {
14670                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14671                } else {
14672                    if (!scalingRequired || cache == null) {
14673                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14674                    } else {
14675                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14676                    }
14677                }
14678            }
14679
14680            if (mClipBounds != null) {
14681                // clip bounds ignore scroll
14682                canvas.clipRect(mClipBounds);
14683            }
14684        }
14685
14686
14687
14688        if (!usingRenderNodeProperties && hasDisplayList) {
14689            renderNode = getDisplayList();
14690            if (!renderNode.isValid()) {
14691                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14692                // to getDisplayList(), the display list will be marked invalid and we should not
14693                // try to use it again.
14694                renderNode = null;
14695                hasDisplayList = false;
14696            }
14697        }
14698
14699        if (hasNoCache) {
14700            boolean layerRendered = false;
14701            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14702                final HardwareLayer layer = getHardwareLayer();
14703                if (layer != null && layer.isValid()) {
14704                    mLayerPaint.setAlpha((int) (alpha * 255));
14705                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14706                    layerRendered = true;
14707                } else {
14708                    final int scrollX = hasDisplayList ? 0 : sx;
14709                    final int scrollY = hasDisplayList ? 0 : sy;
14710                    canvas.saveLayer(scrollX, scrollY,
14711                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14712                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14713                }
14714            }
14715
14716            if (!layerRendered) {
14717                if (!hasDisplayList) {
14718                    // Fast path for layouts with no backgrounds
14719                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14720                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14721                        dispatchDraw(canvas);
14722                    } else {
14723                        draw(canvas);
14724                    }
14725                } else {
14726                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14727                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14728                }
14729            }
14730        } else if (cache != null) {
14731            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14732            Paint cachePaint;
14733
14734            if (layerType == LAYER_TYPE_NONE) {
14735                cachePaint = parent.mCachePaint;
14736                if (cachePaint == null) {
14737                    cachePaint = new Paint();
14738                    cachePaint.setDither(false);
14739                    parent.mCachePaint = cachePaint;
14740                }
14741                if (alpha < 1) {
14742                    cachePaint.setAlpha((int) (alpha * 255));
14743                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14744                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14745                    cachePaint.setAlpha(255);
14746                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14747                }
14748            } else {
14749                cachePaint = mLayerPaint;
14750                cachePaint.setAlpha((int) (alpha * 255));
14751            }
14752            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14753        }
14754
14755        if (restoreTo >= 0) {
14756            canvas.restoreToCount(restoreTo);
14757        }
14758
14759        if (a != null && !more) {
14760            if (!hardwareAccelerated && !a.getFillAfter()) {
14761                onSetAlpha(255);
14762            }
14763            parent.finishAnimatingView(this, a);
14764        }
14765
14766        if (more && hardwareAccelerated) {
14767            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14768                // alpha animations should cause the child to recreate its display list
14769                invalidate(true);
14770            }
14771        }
14772
14773        mRecreateDisplayList = false;
14774
14775        return more;
14776    }
14777
14778    /**
14779     * Manually render this view (and all of its children) to the given Canvas.
14780     * The view must have already done a full layout before this function is
14781     * called.  When implementing a view, implement
14782     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14783     * If you do need to override this method, call the superclass version.
14784     *
14785     * @param canvas The Canvas to which the View is rendered.
14786     */
14787    public void draw(Canvas canvas) {
14788        final int privateFlags = mPrivateFlags;
14789        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14790                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14791        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14792
14793        /*
14794         * Draw traversal performs several drawing steps which must be executed
14795         * in the appropriate order:
14796         *
14797         *      1. Draw the background
14798         *      2. If necessary, save the canvas' layers to prepare for fading
14799         *      3. Draw view's content
14800         *      4. Draw children
14801         *      5. If necessary, draw the fading edges and restore layers
14802         *      6. Draw decorations (scrollbars for instance)
14803         */
14804
14805        // Step 1, draw the background, if needed
14806        int saveCount;
14807
14808        if (!dirtyOpaque) {
14809            drawBackground(canvas);
14810        }
14811
14812        // skip step 2 & 5 if possible (common case)
14813        final int viewFlags = mViewFlags;
14814        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14815        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14816        if (!verticalEdges && !horizontalEdges) {
14817            // Step 3, draw the content
14818            if (!dirtyOpaque) onDraw(canvas);
14819
14820            // Step 4, draw the children
14821            dispatchDraw(canvas);
14822
14823            // Step 6, draw decorations (scrollbars)
14824            onDrawScrollBars(canvas);
14825
14826            if (mOverlay != null && !mOverlay.isEmpty()) {
14827                mOverlay.getOverlayView().dispatchDraw(canvas);
14828            }
14829
14830            // we're done...
14831            return;
14832        }
14833
14834        /*
14835         * Here we do the full fledged routine...
14836         * (this is an uncommon case where speed matters less,
14837         * this is why we repeat some of the tests that have been
14838         * done above)
14839         */
14840
14841        boolean drawTop = false;
14842        boolean drawBottom = false;
14843        boolean drawLeft = false;
14844        boolean drawRight = false;
14845
14846        float topFadeStrength = 0.0f;
14847        float bottomFadeStrength = 0.0f;
14848        float leftFadeStrength = 0.0f;
14849        float rightFadeStrength = 0.0f;
14850
14851        // Step 2, save the canvas' layers
14852        int paddingLeft = mPaddingLeft;
14853
14854        final boolean offsetRequired = isPaddingOffsetRequired();
14855        if (offsetRequired) {
14856            paddingLeft += getLeftPaddingOffset();
14857        }
14858
14859        int left = mScrollX + paddingLeft;
14860        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14861        int top = mScrollY + getFadeTop(offsetRequired);
14862        int bottom = top + getFadeHeight(offsetRequired);
14863
14864        if (offsetRequired) {
14865            right += getRightPaddingOffset();
14866            bottom += getBottomPaddingOffset();
14867        }
14868
14869        final ScrollabilityCache scrollabilityCache = mScrollCache;
14870        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14871        int length = (int) fadeHeight;
14872
14873        // clip the fade length if top and bottom fades overlap
14874        // overlapping fades produce odd-looking artifacts
14875        if (verticalEdges && (top + length > bottom - length)) {
14876            length = (bottom - top) / 2;
14877        }
14878
14879        // also clip horizontal fades if necessary
14880        if (horizontalEdges && (left + length > right - length)) {
14881            length = (right - left) / 2;
14882        }
14883
14884        if (verticalEdges) {
14885            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14886            drawTop = topFadeStrength * fadeHeight > 1.0f;
14887            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14888            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14889        }
14890
14891        if (horizontalEdges) {
14892            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14893            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14894            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14895            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14896        }
14897
14898        saveCount = canvas.getSaveCount();
14899
14900        int solidColor = getSolidColor();
14901        if (solidColor == 0) {
14902            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14903
14904            if (drawTop) {
14905                canvas.saveLayer(left, top, right, top + length, null, flags);
14906            }
14907
14908            if (drawBottom) {
14909                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14910            }
14911
14912            if (drawLeft) {
14913                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14914            }
14915
14916            if (drawRight) {
14917                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14918            }
14919        } else {
14920            scrollabilityCache.setFadeColor(solidColor);
14921        }
14922
14923        // Step 3, draw the content
14924        if (!dirtyOpaque) onDraw(canvas);
14925
14926        // Step 4, draw the children
14927        dispatchDraw(canvas);
14928
14929        // Step 5, draw the fade effect and restore layers
14930        final Paint p = scrollabilityCache.paint;
14931        final Matrix matrix = scrollabilityCache.matrix;
14932        final Shader fade = scrollabilityCache.shader;
14933
14934        if (drawTop) {
14935            matrix.setScale(1, fadeHeight * topFadeStrength);
14936            matrix.postTranslate(left, top);
14937            fade.setLocalMatrix(matrix);
14938            p.setShader(fade);
14939            canvas.drawRect(left, top, right, top + length, p);
14940        }
14941
14942        if (drawBottom) {
14943            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14944            matrix.postRotate(180);
14945            matrix.postTranslate(left, bottom);
14946            fade.setLocalMatrix(matrix);
14947            p.setShader(fade);
14948            canvas.drawRect(left, bottom - length, right, bottom, p);
14949        }
14950
14951        if (drawLeft) {
14952            matrix.setScale(1, fadeHeight * leftFadeStrength);
14953            matrix.postRotate(-90);
14954            matrix.postTranslate(left, top);
14955            fade.setLocalMatrix(matrix);
14956            p.setShader(fade);
14957            canvas.drawRect(left, top, left + length, bottom, p);
14958        }
14959
14960        if (drawRight) {
14961            matrix.setScale(1, fadeHeight * rightFadeStrength);
14962            matrix.postRotate(90);
14963            matrix.postTranslate(right, top);
14964            fade.setLocalMatrix(matrix);
14965            p.setShader(fade);
14966            canvas.drawRect(right - length, top, right, bottom, p);
14967        }
14968
14969        canvas.restoreToCount(saveCount);
14970
14971        // Step 6, draw decorations (scrollbars)
14972        onDrawScrollBars(canvas);
14973
14974        if (mOverlay != null && !mOverlay.isEmpty()) {
14975            mOverlay.getOverlayView().dispatchDraw(canvas);
14976        }
14977    }
14978
14979    /**
14980     * Draws the background onto the specified canvas.
14981     *
14982     * @param canvas Canvas on which to draw the background
14983     */
14984    private void drawBackground(Canvas canvas) {
14985        final Drawable background = mBackground;
14986        if (background == null) {
14987            return;
14988        }
14989
14990        if (mBackgroundSizeChanged) {
14991            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14992            mBackgroundSizeChanged = false;
14993            invalidateOutline();
14994        }
14995
14996        // Attempt to use a display list if requested.
14997        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14998                && mAttachInfo.mHardwareRenderer != null) {
14999            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15000
15001            final RenderNode displayList = mBackgroundRenderNode;
15002            if (displayList != null && displayList.isValid()) {
15003                setBackgroundDisplayListProperties(displayList);
15004                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15005                return;
15006            }
15007        }
15008
15009        final int scrollX = mScrollX;
15010        final int scrollY = mScrollY;
15011        if ((scrollX | scrollY) == 0) {
15012            background.draw(canvas);
15013        } else {
15014            canvas.translate(scrollX, scrollY);
15015            background.draw(canvas);
15016            canvas.translate(-scrollX, -scrollY);
15017        }
15018    }
15019
15020    /**
15021     * Set up background drawable display list properties.
15022     *
15023     * @param displayList Valid display list for the background drawable
15024     */
15025    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15026        displayList.setTranslationX(mScrollX);
15027        displayList.setTranslationY(mScrollY);
15028    }
15029
15030    /**
15031     * Creates a new display list or updates the existing display list for the
15032     * specified Drawable.
15033     *
15034     * @param drawable Drawable for which to create a display list
15035     * @param renderNode Existing RenderNode, or {@code null}
15036     * @return A valid display list for the specified drawable
15037     */
15038    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15039        if (renderNode == null) {
15040            renderNode = RenderNode.create(drawable.getClass().getName());
15041        }
15042
15043        final Rect bounds = drawable.getBounds();
15044        final int width = bounds.width();
15045        final int height = bounds.height();
15046        final HardwareCanvas canvas = renderNode.start(width, height);
15047        try {
15048            drawable.draw(canvas);
15049        } finally {
15050            renderNode.end(canvas);
15051        }
15052
15053        // Set up drawable properties that are view-independent.
15054        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15055        renderNode.setProjectBackwards(drawable.isProjected());
15056        renderNode.setProjectionReceiver(true);
15057        renderNode.setClipToBounds(false);
15058        return renderNode;
15059    }
15060
15061    /**
15062     * Returns the overlay for this view, creating it if it does not yet exist.
15063     * Adding drawables to the overlay will cause them to be displayed whenever
15064     * the view itself is redrawn. Objects in the overlay should be actively
15065     * managed: remove them when they should not be displayed anymore. The
15066     * overlay will always have the same size as its host view.
15067     *
15068     * <p>Note: Overlays do not currently work correctly with {@link
15069     * SurfaceView} or {@link TextureView}; contents in overlays for these
15070     * types of views may not display correctly.</p>
15071     *
15072     * @return The ViewOverlay object for this view.
15073     * @see ViewOverlay
15074     */
15075    public ViewOverlay getOverlay() {
15076        if (mOverlay == null) {
15077            mOverlay = new ViewOverlay(mContext, this);
15078        }
15079        return mOverlay;
15080    }
15081
15082    /**
15083     * Override this if your view is known to always be drawn on top of a solid color background,
15084     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15085     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15086     * should be set to 0xFF.
15087     *
15088     * @see #setVerticalFadingEdgeEnabled(boolean)
15089     * @see #setHorizontalFadingEdgeEnabled(boolean)
15090     *
15091     * @return The known solid color background for this view, or 0 if the color may vary
15092     */
15093    @ViewDebug.ExportedProperty(category = "drawing")
15094    public int getSolidColor() {
15095        return 0;
15096    }
15097
15098    /**
15099     * Build a human readable string representation of the specified view flags.
15100     *
15101     * @param flags the view flags to convert to a string
15102     * @return a String representing the supplied flags
15103     */
15104    private static String printFlags(int flags) {
15105        String output = "";
15106        int numFlags = 0;
15107        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15108            output += "TAKES_FOCUS";
15109            numFlags++;
15110        }
15111
15112        switch (flags & VISIBILITY_MASK) {
15113        case INVISIBLE:
15114            if (numFlags > 0) {
15115                output += " ";
15116            }
15117            output += "INVISIBLE";
15118            // USELESS HERE numFlags++;
15119            break;
15120        case GONE:
15121            if (numFlags > 0) {
15122                output += " ";
15123            }
15124            output += "GONE";
15125            // USELESS HERE numFlags++;
15126            break;
15127        default:
15128            break;
15129        }
15130        return output;
15131    }
15132
15133    /**
15134     * Build a human readable string representation of the specified private
15135     * view flags.
15136     *
15137     * @param privateFlags the private view flags to convert to a string
15138     * @return a String representing the supplied flags
15139     */
15140    private static String printPrivateFlags(int privateFlags) {
15141        String output = "";
15142        int numFlags = 0;
15143
15144        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15145            output += "WANTS_FOCUS";
15146            numFlags++;
15147        }
15148
15149        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15150            if (numFlags > 0) {
15151                output += " ";
15152            }
15153            output += "FOCUSED";
15154            numFlags++;
15155        }
15156
15157        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15158            if (numFlags > 0) {
15159                output += " ";
15160            }
15161            output += "SELECTED";
15162            numFlags++;
15163        }
15164
15165        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15166            if (numFlags > 0) {
15167                output += " ";
15168            }
15169            output += "IS_ROOT_NAMESPACE";
15170            numFlags++;
15171        }
15172
15173        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15174            if (numFlags > 0) {
15175                output += " ";
15176            }
15177            output += "HAS_BOUNDS";
15178            numFlags++;
15179        }
15180
15181        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15182            if (numFlags > 0) {
15183                output += " ";
15184            }
15185            output += "DRAWN";
15186            // USELESS HERE numFlags++;
15187        }
15188        return output;
15189    }
15190
15191    /**
15192     * <p>Indicates whether or not this view's layout will be requested during
15193     * the next hierarchy layout pass.</p>
15194     *
15195     * @return true if the layout will be forced during next layout pass
15196     */
15197    public boolean isLayoutRequested() {
15198        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15199    }
15200
15201    /**
15202     * Return true if o is a ViewGroup that is laying out using optical bounds.
15203     * @hide
15204     */
15205    public static boolean isLayoutModeOptical(Object o) {
15206        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15207    }
15208
15209    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15210        Insets parentInsets = mParent instanceof View ?
15211                ((View) mParent).getOpticalInsets() : Insets.NONE;
15212        Insets childInsets = getOpticalInsets();
15213        return setFrame(
15214                left   + parentInsets.left - childInsets.left,
15215                top    + parentInsets.top  - childInsets.top,
15216                right  + parentInsets.left + childInsets.right,
15217                bottom + parentInsets.top  + childInsets.bottom);
15218    }
15219
15220    /**
15221     * Assign a size and position to a view and all of its
15222     * descendants
15223     *
15224     * <p>This is the second phase of the layout mechanism.
15225     * (The first is measuring). In this phase, each parent calls
15226     * layout on all of its children to position them.
15227     * This is typically done using the child measurements
15228     * that were stored in the measure pass().</p>
15229     *
15230     * <p>Derived classes should not override this method.
15231     * Derived classes with children should override
15232     * onLayout. In that method, they should
15233     * call layout on each of their children.</p>
15234     *
15235     * @param l Left position, relative to parent
15236     * @param t Top position, relative to parent
15237     * @param r Right position, relative to parent
15238     * @param b Bottom position, relative to parent
15239     */
15240    @SuppressWarnings({"unchecked"})
15241    public void layout(int l, int t, int r, int b) {
15242        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15243            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15244            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15245        }
15246
15247        int oldL = mLeft;
15248        int oldT = mTop;
15249        int oldB = mBottom;
15250        int oldR = mRight;
15251
15252        boolean changed = isLayoutModeOptical(mParent) ?
15253                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15254
15255        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15256            onLayout(changed, l, t, r, b);
15257            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15258
15259            ListenerInfo li = mListenerInfo;
15260            if (li != null && li.mOnLayoutChangeListeners != null) {
15261                ArrayList<OnLayoutChangeListener> listenersCopy =
15262                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15263                int numListeners = listenersCopy.size();
15264                for (int i = 0; i < numListeners; ++i) {
15265                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15266                }
15267            }
15268        }
15269
15270        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15271        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15272    }
15273
15274    /**
15275     * Called from layout when this view should
15276     * assign a size and position to each of its children.
15277     *
15278     * Derived classes with children should override
15279     * this method and call layout on each of
15280     * their children.
15281     * @param changed This is a new size or position for this view
15282     * @param left Left position, relative to parent
15283     * @param top Top position, relative to parent
15284     * @param right Right position, relative to parent
15285     * @param bottom Bottom position, relative to parent
15286     */
15287    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15288    }
15289
15290    /**
15291     * Assign a size and position to this view.
15292     *
15293     * This is called from layout.
15294     *
15295     * @param left Left position, relative to parent
15296     * @param top Top position, relative to parent
15297     * @param right Right position, relative to parent
15298     * @param bottom Bottom position, relative to parent
15299     * @return true if the new size and position are different than the
15300     *         previous ones
15301     * {@hide}
15302     */
15303    protected boolean setFrame(int left, int top, int right, int bottom) {
15304        boolean changed = false;
15305
15306        if (DBG) {
15307            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15308                    + right + "," + bottom + ")");
15309        }
15310
15311        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15312            changed = true;
15313
15314            // Remember our drawn bit
15315            int drawn = mPrivateFlags & PFLAG_DRAWN;
15316
15317            int oldWidth = mRight - mLeft;
15318            int oldHeight = mBottom - mTop;
15319            int newWidth = right - left;
15320            int newHeight = bottom - top;
15321            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15322
15323            // Invalidate our old position
15324            invalidate(sizeChanged);
15325
15326            mLeft = left;
15327            mTop = top;
15328            mRight = right;
15329            mBottom = bottom;
15330            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15331
15332            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15333
15334
15335            if (sizeChanged) {
15336                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15337            }
15338
15339            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15340                // If we are visible, force the DRAWN bit to on so that
15341                // this invalidate will go through (at least to our parent).
15342                // This is because someone may have invalidated this view
15343                // before this call to setFrame came in, thereby clearing
15344                // the DRAWN bit.
15345                mPrivateFlags |= PFLAG_DRAWN;
15346                invalidate(sizeChanged);
15347                // parent display list may need to be recreated based on a change in the bounds
15348                // of any child
15349                invalidateParentCaches();
15350            }
15351
15352            // Reset drawn bit to original value (invalidate turns it off)
15353            mPrivateFlags |= drawn;
15354
15355            mBackgroundSizeChanged = true;
15356
15357            notifySubtreeAccessibilityStateChangedIfNeeded();
15358        }
15359        return changed;
15360    }
15361
15362    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15363        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15364        if (mOverlay != null) {
15365            mOverlay.getOverlayView().setRight(newWidth);
15366            mOverlay.getOverlayView().setBottom(newHeight);
15367        }
15368        invalidateOutline();
15369    }
15370
15371    /**
15372     * Finalize inflating a view from XML.  This is called as the last phase
15373     * of inflation, after all child views have been added.
15374     *
15375     * <p>Even if the subclass overrides onFinishInflate, they should always be
15376     * sure to call the super method, so that we get called.
15377     */
15378    protected void onFinishInflate() {
15379    }
15380
15381    /**
15382     * Returns the resources associated with this view.
15383     *
15384     * @return Resources object.
15385     */
15386    public Resources getResources() {
15387        return mResources;
15388    }
15389
15390    /**
15391     * Invalidates the specified Drawable.
15392     *
15393     * @param drawable the drawable to invalidate
15394     */
15395    @Override
15396    public void invalidateDrawable(@NonNull Drawable drawable) {
15397        if (verifyDrawable(drawable)) {
15398            final Rect dirty = drawable.getDirtyBounds();
15399            final int scrollX = mScrollX;
15400            final int scrollY = mScrollY;
15401
15402            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15403                    dirty.right + scrollX, dirty.bottom + scrollY);
15404
15405            invalidateOutline();
15406        }
15407    }
15408
15409    /**
15410     * Schedules an action on a drawable to occur at a specified time.
15411     *
15412     * @param who the recipient of the action
15413     * @param what the action to run on the drawable
15414     * @param when the time at which the action must occur. Uses the
15415     *        {@link SystemClock#uptimeMillis} timebase.
15416     */
15417    @Override
15418    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15419        if (verifyDrawable(who) && what != null) {
15420            final long delay = when - SystemClock.uptimeMillis();
15421            if (mAttachInfo != null) {
15422                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15423                        Choreographer.CALLBACK_ANIMATION, what, who,
15424                        Choreographer.subtractFrameDelay(delay));
15425            } else {
15426                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15427            }
15428        }
15429    }
15430
15431    /**
15432     * Cancels a scheduled action on a drawable.
15433     *
15434     * @param who the recipient of the action
15435     * @param what the action to cancel
15436     */
15437    @Override
15438    public void unscheduleDrawable(Drawable who, Runnable what) {
15439        if (verifyDrawable(who) && what != null) {
15440            if (mAttachInfo != null) {
15441                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15442                        Choreographer.CALLBACK_ANIMATION, what, who);
15443            }
15444            ViewRootImpl.getRunQueue().removeCallbacks(what);
15445        }
15446    }
15447
15448    /**
15449     * Unschedule any events associated with the given Drawable.  This can be
15450     * used when selecting a new Drawable into a view, so that the previous
15451     * one is completely unscheduled.
15452     *
15453     * @param who The Drawable to unschedule.
15454     *
15455     * @see #drawableStateChanged
15456     */
15457    public void unscheduleDrawable(Drawable who) {
15458        if (mAttachInfo != null && who != null) {
15459            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15460                    Choreographer.CALLBACK_ANIMATION, null, who);
15461        }
15462    }
15463
15464    /**
15465     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15466     * that the View directionality can and will be resolved before its Drawables.
15467     *
15468     * Will call {@link View#onResolveDrawables} when resolution is done.
15469     *
15470     * @hide
15471     */
15472    protected void resolveDrawables() {
15473        // Drawables resolution may need to happen before resolving the layout direction (which is
15474        // done only during the measure() call).
15475        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15476        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15477        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15478        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15479        // direction to be resolved as its resolved value will be the same as its raw value.
15480        if (!isLayoutDirectionResolved() &&
15481                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15482            return;
15483        }
15484
15485        final int layoutDirection = isLayoutDirectionResolved() ?
15486                getLayoutDirection() : getRawLayoutDirection();
15487
15488        if (mBackground != null) {
15489            mBackground.setLayoutDirection(layoutDirection);
15490        }
15491        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15492        onResolveDrawables(layoutDirection);
15493    }
15494
15495    /**
15496     * Called when layout direction has been resolved.
15497     *
15498     * The default implementation does nothing.
15499     *
15500     * @param layoutDirection The resolved layout direction.
15501     *
15502     * @see #LAYOUT_DIRECTION_LTR
15503     * @see #LAYOUT_DIRECTION_RTL
15504     *
15505     * @hide
15506     */
15507    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15508    }
15509
15510    /**
15511     * @hide
15512     */
15513    protected void resetResolvedDrawables() {
15514        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15515    }
15516
15517    private boolean isDrawablesResolved() {
15518        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15519    }
15520
15521    /**
15522     * If your view subclass is displaying its own Drawable objects, it should
15523     * override this function and return true for any Drawable it is
15524     * displaying.  This allows animations for those drawables to be
15525     * scheduled.
15526     *
15527     * <p>Be sure to call through to the super class when overriding this
15528     * function.
15529     *
15530     * @param who The Drawable to verify.  Return true if it is one you are
15531     *            displaying, else return the result of calling through to the
15532     *            super class.
15533     *
15534     * @return boolean If true than the Drawable is being displayed in the
15535     *         view; else false and it is not allowed to animate.
15536     *
15537     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15538     * @see #drawableStateChanged()
15539     */
15540    protected boolean verifyDrawable(Drawable who) {
15541        return who == mBackground;
15542    }
15543
15544    /**
15545     * This function is called whenever the state of the view changes in such
15546     * a way that it impacts the state of drawables being shown.
15547     * <p>
15548     * If the View has a StateListAnimator, it will also be called to run necessary state
15549     * change animations.
15550     * <p>
15551     * Be sure to call through to the superclass when overriding this function.
15552     *
15553     * @see Drawable#setState(int[])
15554     */
15555    protected void drawableStateChanged() {
15556        final Drawable d = mBackground;
15557        if (d != null && d.isStateful()) {
15558            d.setState(getDrawableState());
15559        }
15560
15561        if (mStateListAnimator != null) {
15562            mStateListAnimator.setState(getDrawableState());
15563        }
15564    }
15565
15566    /**
15567     * This function is called whenever the view hotspot changes and needs to
15568     * be propagated to drawables managed by the view.
15569     * <p>
15570     * Be sure to call through to the superclass when overriding this function.
15571     *
15572     * @param x hotspot x coordinate
15573     * @param y hotspot y coordinate
15574     */
15575    public void drawableHotspotChanged(float x, float y) {
15576        if (mBackground != null) {
15577            mBackground.setHotspot(x, y);
15578        }
15579    }
15580
15581    /**
15582     * Call this to force a view to update its drawable state. This will cause
15583     * drawableStateChanged to be called on this view. Views that are interested
15584     * in the new state should call getDrawableState.
15585     *
15586     * @see #drawableStateChanged
15587     * @see #getDrawableState
15588     */
15589    public void refreshDrawableState() {
15590        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15591        drawableStateChanged();
15592
15593        ViewParent parent = mParent;
15594        if (parent != null) {
15595            parent.childDrawableStateChanged(this);
15596        }
15597    }
15598
15599    /**
15600     * Return an array of resource IDs of the drawable states representing the
15601     * current state of the view.
15602     *
15603     * @return The current drawable state
15604     *
15605     * @see Drawable#setState(int[])
15606     * @see #drawableStateChanged()
15607     * @see #onCreateDrawableState(int)
15608     */
15609    public final int[] getDrawableState() {
15610        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15611            return mDrawableState;
15612        } else {
15613            mDrawableState = onCreateDrawableState(0);
15614            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15615            return mDrawableState;
15616        }
15617    }
15618
15619    /**
15620     * Generate the new {@link android.graphics.drawable.Drawable} state for
15621     * this view. This is called by the view
15622     * system when the cached Drawable state is determined to be invalid.  To
15623     * retrieve the current state, you should use {@link #getDrawableState}.
15624     *
15625     * @param extraSpace if non-zero, this is the number of extra entries you
15626     * would like in the returned array in which you can place your own
15627     * states.
15628     *
15629     * @return Returns an array holding the current {@link Drawable} state of
15630     * the view.
15631     *
15632     * @see #mergeDrawableStates(int[], int[])
15633     */
15634    protected int[] onCreateDrawableState(int extraSpace) {
15635        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15636                mParent instanceof View) {
15637            return ((View) mParent).onCreateDrawableState(extraSpace);
15638        }
15639
15640        int[] drawableState;
15641
15642        int privateFlags = mPrivateFlags;
15643
15644        int viewStateIndex = 0;
15645        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15646        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15647        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15648        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15649        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15650        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15651        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15652                HardwareRenderer.isAvailable()) {
15653            // This is set if HW acceleration is requested, even if the current
15654            // process doesn't allow it.  This is just to allow app preview
15655            // windows to better match their app.
15656            viewStateIndex |= VIEW_STATE_ACCELERATED;
15657        }
15658        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15659
15660        final int privateFlags2 = mPrivateFlags2;
15661        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15662        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15663
15664        drawableState = VIEW_STATE_SETS[viewStateIndex];
15665
15666        //noinspection ConstantIfStatement
15667        if (false) {
15668            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15669            Log.i("View", toString()
15670                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15671                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15672                    + " fo=" + hasFocus()
15673                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15674                    + " wf=" + hasWindowFocus()
15675                    + ": " + Arrays.toString(drawableState));
15676        }
15677
15678        if (extraSpace == 0) {
15679            return drawableState;
15680        }
15681
15682        final int[] fullState;
15683        if (drawableState != null) {
15684            fullState = new int[drawableState.length + extraSpace];
15685            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15686        } else {
15687            fullState = new int[extraSpace];
15688        }
15689
15690        return fullState;
15691    }
15692
15693    /**
15694     * Merge your own state values in <var>additionalState</var> into the base
15695     * state values <var>baseState</var> that were returned by
15696     * {@link #onCreateDrawableState(int)}.
15697     *
15698     * @param baseState The base state values returned by
15699     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15700     * own additional state values.
15701     *
15702     * @param additionalState The additional state values you would like
15703     * added to <var>baseState</var>; this array is not modified.
15704     *
15705     * @return As a convenience, the <var>baseState</var> array you originally
15706     * passed into the function is returned.
15707     *
15708     * @see #onCreateDrawableState(int)
15709     */
15710    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15711        final int N = baseState.length;
15712        int i = N - 1;
15713        while (i >= 0 && baseState[i] == 0) {
15714            i--;
15715        }
15716        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15717        return baseState;
15718    }
15719
15720    /**
15721     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15722     * on all Drawable objects associated with this view.
15723     * <p>
15724     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15725     * attached to this view.
15726     */
15727    public void jumpDrawablesToCurrentState() {
15728        if (mBackground != null) {
15729            mBackground.jumpToCurrentState();
15730        }
15731        if (mStateListAnimator != null) {
15732            mStateListAnimator.jumpToCurrentState();
15733        }
15734    }
15735
15736    /**
15737     * Sets the background color for this view.
15738     * @param color the color of the background
15739     */
15740    @RemotableViewMethod
15741    public void setBackgroundColor(int color) {
15742        if (mBackground instanceof ColorDrawable) {
15743            ((ColorDrawable) mBackground.mutate()).setColor(color);
15744            computeOpaqueFlags();
15745            mBackgroundResource = 0;
15746        } else {
15747            setBackground(new ColorDrawable(color));
15748        }
15749    }
15750
15751    /**
15752     * Set the background to a given resource. The resource should refer to
15753     * a Drawable object or 0 to remove the background.
15754     * @param resid The identifier of the resource.
15755     *
15756     * @attr ref android.R.styleable#View_background
15757     */
15758    @RemotableViewMethod
15759    public void setBackgroundResource(int resid) {
15760        if (resid != 0 && resid == mBackgroundResource) {
15761            return;
15762        }
15763
15764        Drawable d = null;
15765        if (resid != 0) {
15766            d = mContext.getDrawable(resid);
15767        }
15768        setBackground(d);
15769
15770        mBackgroundResource = resid;
15771    }
15772
15773    /**
15774     * Set the background to a given Drawable, or remove the background. If the
15775     * background has padding, this View's padding is set to the background's
15776     * padding. However, when a background is removed, this View's padding isn't
15777     * touched. If setting the padding is desired, please use
15778     * {@link #setPadding(int, int, int, int)}.
15779     *
15780     * @param background The Drawable to use as the background, or null to remove the
15781     *        background
15782     */
15783    public void setBackground(Drawable background) {
15784        //noinspection deprecation
15785        setBackgroundDrawable(background);
15786    }
15787
15788    /**
15789     * @deprecated use {@link #setBackground(Drawable)} instead
15790     */
15791    @Deprecated
15792    public void setBackgroundDrawable(Drawable background) {
15793        computeOpaqueFlags();
15794
15795        if (background == mBackground) {
15796            return;
15797        }
15798
15799        boolean requestLayout = false;
15800
15801        mBackgroundResource = 0;
15802
15803        /*
15804         * Regardless of whether we're setting a new background or not, we want
15805         * to clear the previous drawable.
15806         */
15807        if (mBackground != null) {
15808            mBackground.setCallback(null);
15809            unscheduleDrawable(mBackground);
15810        }
15811
15812        if (background != null) {
15813            Rect padding = sThreadLocal.get();
15814            if (padding == null) {
15815                padding = new Rect();
15816                sThreadLocal.set(padding);
15817            }
15818            resetResolvedDrawables();
15819            background.setLayoutDirection(getLayoutDirection());
15820            if (background.getPadding(padding)) {
15821                resetResolvedPadding();
15822                switch (background.getLayoutDirection()) {
15823                    case LAYOUT_DIRECTION_RTL:
15824                        mUserPaddingLeftInitial = padding.right;
15825                        mUserPaddingRightInitial = padding.left;
15826                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15827                        break;
15828                    case LAYOUT_DIRECTION_LTR:
15829                    default:
15830                        mUserPaddingLeftInitial = padding.left;
15831                        mUserPaddingRightInitial = padding.right;
15832                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15833                }
15834                mLeftPaddingDefined = false;
15835                mRightPaddingDefined = false;
15836            }
15837
15838            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15839            // if it has a different minimum size, we should layout again
15840            if (mBackground == null
15841                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15842                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15843                requestLayout = true;
15844            }
15845
15846            background.setCallback(this);
15847            if (background.isStateful()) {
15848                background.setState(getDrawableState());
15849            }
15850            background.setVisible(getVisibility() == VISIBLE, false);
15851            mBackground = background;
15852
15853            applyBackgroundTint();
15854
15855            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15856                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15857                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15858                requestLayout = true;
15859            }
15860        } else {
15861            /* Remove the background */
15862            mBackground = null;
15863
15864            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15865                /*
15866                 * This view ONLY drew the background before and we're removing
15867                 * the background, so now it won't draw anything
15868                 * (hence we SKIP_DRAW)
15869                 */
15870                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15871                mPrivateFlags |= PFLAG_SKIP_DRAW;
15872            }
15873
15874            /*
15875             * When the background is set, we try to apply its padding to this
15876             * View. When the background is removed, we don't touch this View's
15877             * padding. This is noted in the Javadocs. Hence, we don't need to
15878             * requestLayout(), the invalidate() below is sufficient.
15879             */
15880
15881            // The old background's minimum size could have affected this
15882            // View's layout, so let's requestLayout
15883            requestLayout = true;
15884        }
15885
15886        computeOpaqueFlags();
15887
15888        if (requestLayout) {
15889            requestLayout();
15890        }
15891
15892        mBackgroundSizeChanged = true;
15893        invalidate(true);
15894    }
15895
15896    /**
15897     * Gets the background drawable
15898     *
15899     * @return The drawable used as the background for this view, if any.
15900     *
15901     * @see #setBackground(Drawable)
15902     *
15903     * @attr ref android.R.styleable#View_background
15904     */
15905    public Drawable getBackground() {
15906        return mBackground;
15907    }
15908
15909    /**
15910     * Applies a tint to the background drawable. Does not modify the current tint
15911     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15912     * <p>
15913     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15914     * mutate the drawable and apply the specified tint and tint mode using
15915     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15916     *
15917     * @param tint the tint to apply, may be {@code null} to clear tint
15918     *
15919     * @attr ref android.R.styleable#View_backgroundTint
15920     * @see #getBackgroundTint()
15921     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15922     */
15923    public void setBackgroundTint(@Nullable ColorStateList tint) {
15924        mBackgroundTint = tint;
15925        mHasBackgroundTint = true;
15926
15927        applyBackgroundTint();
15928    }
15929
15930    /**
15931     * @return the tint applied to the background drawable
15932     * @attr ref android.R.styleable#View_backgroundTint
15933     * @see #setBackgroundTint(ColorStateList)
15934     */
15935    @Nullable
15936    public ColorStateList getBackgroundTint() {
15937        return mBackgroundTint;
15938    }
15939
15940    /**
15941     * Specifies the blending mode used to apply the tint specified by
15942     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15943     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15944     *
15945     * @param tintMode the blending mode used to apply the tint, may be
15946     *                 {@code null} to clear tint
15947     * @attr ref android.R.styleable#View_backgroundTintMode
15948     * @see #getBackgroundTintMode()
15949     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15950     */
15951    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15952        mBackgroundTintMode = tintMode;
15953
15954        applyBackgroundTint();
15955    }
15956
15957    /**
15958     * @return the blending mode used to apply the tint to the background drawable
15959     * @attr ref android.R.styleable#View_backgroundTintMode
15960     * @see #setBackgroundTintMode(PorterDuff.Mode)
15961     */
15962    @Nullable
15963    public PorterDuff.Mode getBackgroundTintMode() {
15964        return mBackgroundTintMode;
15965    }
15966
15967    private void applyBackgroundTint() {
15968        if (mBackground != null && mHasBackgroundTint) {
15969            mBackground = mBackground.mutate();
15970            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15971        }
15972    }
15973
15974    /**
15975     * Sets the padding. The view may add on the space required to display
15976     * the scrollbars, depending on the style and visibility of the scrollbars.
15977     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15978     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15979     * from the values set in this call.
15980     *
15981     * @attr ref android.R.styleable#View_padding
15982     * @attr ref android.R.styleable#View_paddingBottom
15983     * @attr ref android.R.styleable#View_paddingLeft
15984     * @attr ref android.R.styleable#View_paddingRight
15985     * @attr ref android.R.styleable#View_paddingTop
15986     * @param left the left padding in pixels
15987     * @param top the top padding in pixels
15988     * @param right the right padding in pixels
15989     * @param bottom the bottom padding in pixels
15990     */
15991    public void setPadding(int left, int top, int right, int bottom) {
15992        resetResolvedPadding();
15993
15994        mUserPaddingStart = UNDEFINED_PADDING;
15995        mUserPaddingEnd = UNDEFINED_PADDING;
15996
15997        mUserPaddingLeftInitial = left;
15998        mUserPaddingRightInitial = right;
15999
16000        mLeftPaddingDefined = true;
16001        mRightPaddingDefined = true;
16002
16003        internalSetPadding(left, top, right, bottom);
16004    }
16005
16006    /**
16007     * @hide
16008     */
16009    protected void internalSetPadding(int left, int top, int right, int bottom) {
16010        mUserPaddingLeft = left;
16011        mUserPaddingRight = right;
16012        mUserPaddingBottom = bottom;
16013
16014        final int viewFlags = mViewFlags;
16015        boolean changed = false;
16016
16017        // Common case is there are no scroll bars.
16018        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16019            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16020                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16021                        ? 0 : getVerticalScrollbarWidth();
16022                switch (mVerticalScrollbarPosition) {
16023                    case SCROLLBAR_POSITION_DEFAULT:
16024                        if (isLayoutRtl()) {
16025                            left += offset;
16026                        } else {
16027                            right += offset;
16028                        }
16029                        break;
16030                    case SCROLLBAR_POSITION_RIGHT:
16031                        right += offset;
16032                        break;
16033                    case SCROLLBAR_POSITION_LEFT:
16034                        left += offset;
16035                        break;
16036                }
16037            }
16038            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16039                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16040                        ? 0 : getHorizontalScrollbarHeight();
16041            }
16042        }
16043
16044        if (mPaddingLeft != left) {
16045            changed = true;
16046            mPaddingLeft = left;
16047        }
16048        if (mPaddingTop != top) {
16049            changed = true;
16050            mPaddingTop = top;
16051        }
16052        if (mPaddingRight != right) {
16053            changed = true;
16054            mPaddingRight = right;
16055        }
16056        if (mPaddingBottom != bottom) {
16057            changed = true;
16058            mPaddingBottom = bottom;
16059        }
16060
16061        if (changed) {
16062            requestLayout();
16063        }
16064    }
16065
16066    /**
16067     * Sets the relative padding. The view may add on the space required to display
16068     * the scrollbars, depending on the style and visibility of the scrollbars.
16069     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16070     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16071     * from the values set in this call.
16072     *
16073     * @attr ref android.R.styleable#View_padding
16074     * @attr ref android.R.styleable#View_paddingBottom
16075     * @attr ref android.R.styleable#View_paddingStart
16076     * @attr ref android.R.styleable#View_paddingEnd
16077     * @attr ref android.R.styleable#View_paddingTop
16078     * @param start the start padding in pixels
16079     * @param top the top padding in pixels
16080     * @param end the end padding in pixels
16081     * @param bottom the bottom padding in pixels
16082     */
16083    public void setPaddingRelative(int start, int top, int end, int bottom) {
16084        resetResolvedPadding();
16085
16086        mUserPaddingStart = start;
16087        mUserPaddingEnd = end;
16088        mLeftPaddingDefined = true;
16089        mRightPaddingDefined = true;
16090
16091        switch(getLayoutDirection()) {
16092            case LAYOUT_DIRECTION_RTL:
16093                mUserPaddingLeftInitial = end;
16094                mUserPaddingRightInitial = start;
16095                internalSetPadding(end, top, start, bottom);
16096                break;
16097            case LAYOUT_DIRECTION_LTR:
16098            default:
16099                mUserPaddingLeftInitial = start;
16100                mUserPaddingRightInitial = end;
16101                internalSetPadding(start, top, end, bottom);
16102        }
16103    }
16104
16105    /**
16106     * Returns the top padding of this view.
16107     *
16108     * @return the top padding in pixels
16109     */
16110    public int getPaddingTop() {
16111        return mPaddingTop;
16112    }
16113
16114    /**
16115     * Returns the bottom padding of this view. If there are inset and enabled
16116     * scrollbars, this value may include the space required to display the
16117     * scrollbars as well.
16118     *
16119     * @return the bottom padding in pixels
16120     */
16121    public int getPaddingBottom() {
16122        return mPaddingBottom;
16123    }
16124
16125    /**
16126     * Returns the left padding of this view. If there are inset and enabled
16127     * scrollbars, this value may include the space required to display the
16128     * scrollbars as well.
16129     *
16130     * @return the left padding in pixels
16131     */
16132    public int getPaddingLeft() {
16133        if (!isPaddingResolved()) {
16134            resolvePadding();
16135        }
16136        return mPaddingLeft;
16137    }
16138
16139    /**
16140     * Returns the start padding of this view depending on its resolved layout direction.
16141     * If there are inset and enabled scrollbars, this value may include the space
16142     * required to display the scrollbars as well.
16143     *
16144     * @return the start padding in pixels
16145     */
16146    public int getPaddingStart() {
16147        if (!isPaddingResolved()) {
16148            resolvePadding();
16149        }
16150        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16151                mPaddingRight : mPaddingLeft;
16152    }
16153
16154    /**
16155     * Returns the right padding of this view. If there are inset and enabled
16156     * scrollbars, this value may include the space required to display the
16157     * scrollbars as well.
16158     *
16159     * @return the right padding in pixels
16160     */
16161    public int getPaddingRight() {
16162        if (!isPaddingResolved()) {
16163            resolvePadding();
16164        }
16165        return mPaddingRight;
16166    }
16167
16168    /**
16169     * Returns the end padding of this view depending on its resolved layout direction.
16170     * If there are inset and enabled scrollbars, this value may include the space
16171     * required to display the scrollbars as well.
16172     *
16173     * @return the end padding in pixels
16174     */
16175    public int getPaddingEnd() {
16176        if (!isPaddingResolved()) {
16177            resolvePadding();
16178        }
16179        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16180                mPaddingLeft : mPaddingRight;
16181    }
16182
16183    /**
16184     * Return if the padding as been set thru relative values
16185     * {@link #setPaddingRelative(int, int, int, int)} or thru
16186     * @attr ref android.R.styleable#View_paddingStart or
16187     * @attr ref android.R.styleable#View_paddingEnd
16188     *
16189     * @return true if the padding is relative or false if it is not.
16190     */
16191    public boolean isPaddingRelative() {
16192        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16193    }
16194
16195    Insets computeOpticalInsets() {
16196        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16197    }
16198
16199    /**
16200     * @hide
16201     */
16202    public void resetPaddingToInitialValues() {
16203        if (isRtlCompatibilityMode()) {
16204            mPaddingLeft = mUserPaddingLeftInitial;
16205            mPaddingRight = mUserPaddingRightInitial;
16206            return;
16207        }
16208        if (isLayoutRtl()) {
16209            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16210            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16211        } else {
16212            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16213            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16214        }
16215    }
16216
16217    /**
16218     * @hide
16219     */
16220    public Insets getOpticalInsets() {
16221        if (mLayoutInsets == null) {
16222            mLayoutInsets = computeOpticalInsets();
16223        }
16224        return mLayoutInsets;
16225    }
16226
16227    /**
16228     * Set this view's optical insets.
16229     *
16230     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16231     * property. Views that compute their own optical insets should call it as part of measurement.
16232     * This method does not request layout. If you are setting optical insets outside of
16233     * measure/layout itself you will want to call requestLayout() yourself.
16234     * </p>
16235     * @hide
16236     */
16237    public void setOpticalInsets(Insets insets) {
16238        mLayoutInsets = insets;
16239    }
16240
16241    /**
16242     * Changes the selection state of this view. A view can be selected or not.
16243     * Note that selection is not the same as focus. Views are typically
16244     * selected in the context of an AdapterView like ListView or GridView;
16245     * the selected view is the view that is highlighted.
16246     *
16247     * @param selected true if the view must be selected, false otherwise
16248     */
16249    public void setSelected(boolean selected) {
16250        //noinspection DoubleNegation
16251        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16252            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16253            if (!selected) resetPressedState();
16254            invalidate(true);
16255            refreshDrawableState();
16256            dispatchSetSelected(selected);
16257            notifyViewAccessibilityStateChangedIfNeeded(
16258                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16259        }
16260    }
16261
16262    /**
16263     * Dispatch setSelected to all of this View's children.
16264     *
16265     * @see #setSelected(boolean)
16266     *
16267     * @param selected The new selected state
16268     */
16269    protected void dispatchSetSelected(boolean selected) {
16270    }
16271
16272    /**
16273     * Indicates the selection state of this view.
16274     *
16275     * @return true if the view is selected, false otherwise
16276     */
16277    @ViewDebug.ExportedProperty
16278    public boolean isSelected() {
16279        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16280    }
16281
16282    /**
16283     * Changes the activated state of this view. A view can be activated or not.
16284     * Note that activation is not the same as selection.  Selection is
16285     * a transient property, representing the view (hierarchy) the user is
16286     * currently interacting with.  Activation is a longer-term state that the
16287     * user can move views in and out of.  For example, in a list view with
16288     * single or multiple selection enabled, the views in the current selection
16289     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16290     * here.)  The activated state is propagated down to children of the view it
16291     * is set on.
16292     *
16293     * @param activated true if the view must be activated, false otherwise
16294     */
16295    public void setActivated(boolean activated) {
16296        //noinspection DoubleNegation
16297        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16298            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16299            invalidate(true);
16300            refreshDrawableState();
16301            dispatchSetActivated(activated);
16302        }
16303    }
16304
16305    /**
16306     * Dispatch setActivated to all of this View's children.
16307     *
16308     * @see #setActivated(boolean)
16309     *
16310     * @param activated The new activated state
16311     */
16312    protected void dispatchSetActivated(boolean activated) {
16313    }
16314
16315    /**
16316     * Indicates the activation state of this view.
16317     *
16318     * @return true if the view is activated, false otherwise
16319     */
16320    @ViewDebug.ExportedProperty
16321    public boolean isActivated() {
16322        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16323    }
16324
16325    /**
16326     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16327     * observer can be used to get notifications when global events, like
16328     * layout, happen.
16329     *
16330     * The returned ViewTreeObserver observer is not guaranteed to remain
16331     * valid for the lifetime of this View. If the caller of this method keeps
16332     * a long-lived reference to ViewTreeObserver, it should always check for
16333     * the return value of {@link ViewTreeObserver#isAlive()}.
16334     *
16335     * @return The ViewTreeObserver for this view's hierarchy.
16336     */
16337    public ViewTreeObserver getViewTreeObserver() {
16338        if (mAttachInfo != null) {
16339            return mAttachInfo.mTreeObserver;
16340        }
16341        if (mFloatingTreeObserver == null) {
16342            mFloatingTreeObserver = new ViewTreeObserver();
16343        }
16344        return mFloatingTreeObserver;
16345    }
16346
16347    /**
16348     * <p>Finds the topmost view in the current view hierarchy.</p>
16349     *
16350     * @return the topmost view containing this view
16351     */
16352    public View getRootView() {
16353        if (mAttachInfo != null) {
16354            final View v = mAttachInfo.mRootView;
16355            if (v != null) {
16356                return v;
16357            }
16358        }
16359
16360        View parent = this;
16361
16362        while (parent.mParent != null && parent.mParent instanceof View) {
16363            parent = (View) parent.mParent;
16364        }
16365
16366        return parent;
16367    }
16368
16369    /**
16370     * Transforms a motion event from view-local coordinates to on-screen
16371     * coordinates.
16372     *
16373     * @param ev the view-local motion event
16374     * @return false if the transformation could not be applied
16375     * @hide
16376     */
16377    public boolean toGlobalMotionEvent(MotionEvent ev) {
16378        final AttachInfo info = mAttachInfo;
16379        if (info == null) {
16380            return false;
16381        }
16382
16383        final Matrix m = info.mTmpMatrix;
16384        m.set(Matrix.IDENTITY_MATRIX);
16385        transformMatrixToGlobal(m);
16386        ev.transform(m);
16387        return true;
16388    }
16389
16390    /**
16391     * Transforms a motion event from on-screen coordinates to view-local
16392     * coordinates.
16393     *
16394     * @param ev the on-screen motion event
16395     * @return false if the transformation could not be applied
16396     * @hide
16397     */
16398    public boolean toLocalMotionEvent(MotionEvent ev) {
16399        final AttachInfo info = mAttachInfo;
16400        if (info == null) {
16401            return false;
16402        }
16403
16404        final Matrix m = info.mTmpMatrix;
16405        m.set(Matrix.IDENTITY_MATRIX);
16406        transformMatrixToLocal(m);
16407        ev.transform(m);
16408        return true;
16409    }
16410
16411    /**
16412     * Modifies the input matrix such that it maps view-local coordinates to
16413     * on-screen coordinates.
16414     *
16415     * @param m input matrix to modify
16416     * @hide
16417     */
16418    public void transformMatrixToGlobal(Matrix m) {
16419        final ViewParent parent = mParent;
16420        if (parent instanceof View) {
16421            final View vp = (View) parent;
16422            vp.transformMatrixToGlobal(m);
16423            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16424        } else if (parent instanceof ViewRootImpl) {
16425            final ViewRootImpl vr = (ViewRootImpl) parent;
16426            vr.transformMatrixToGlobal(m);
16427            m.preTranslate(0, -vr.mCurScrollY);
16428        }
16429
16430        m.preTranslate(mLeft, mTop);
16431
16432        if (!hasIdentityMatrix()) {
16433            m.preConcat(getMatrix());
16434        }
16435    }
16436
16437    /**
16438     * Modifies the input matrix such that it maps on-screen coordinates to
16439     * view-local coordinates.
16440     *
16441     * @param m input matrix to modify
16442     * @hide
16443     */
16444    public void transformMatrixToLocal(Matrix m) {
16445        final ViewParent parent = mParent;
16446        if (parent instanceof View) {
16447            final View vp = (View) parent;
16448            vp.transformMatrixToLocal(m);
16449            m.postTranslate(vp.mScrollX, vp.mScrollY);
16450        } else if (parent instanceof ViewRootImpl) {
16451            final ViewRootImpl vr = (ViewRootImpl) parent;
16452            vr.transformMatrixToLocal(m);
16453            m.postTranslate(0, vr.mCurScrollY);
16454        }
16455
16456        m.postTranslate(-mLeft, -mTop);
16457
16458        if (!hasIdentityMatrix()) {
16459            m.postConcat(getInverseMatrix());
16460        }
16461    }
16462
16463    /**
16464     * @hide
16465     */
16466    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16467            @ViewDebug.IntToString(from = 0, to = "x"),
16468            @ViewDebug.IntToString(from = 1, to = "y")
16469    })
16470    public int[] getLocationOnScreen() {
16471        int[] location = new int[2];
16472        getLocationOnScreen(location);
16473        return location;
16474    }
16475
16476    /**
16477     * <p>Computes the coordinates of this view on the screen. The argument
16478     * must be an array of two integers. After the method returns, the array
16479     * contains the x and y location in that order.</p>
16480     *
16481     * @param location an array of two integers in which to hold the coordinates
16482     */
16483    public void getLocationOnScreen(int[] location) {
16484        getLocationInWindow(location);
16485
16486        final AttachInfo info = mAttachInfo;
16487        if (info != null) {
16488            location[0] += info.mWindowLeft;
16489            location[1] += info.mWindowTop;
16490        }
16491    }
16492
16493    /**
16494     * <p>Computes the coordinates of this view in its window. The argument
16495     * must be an array of two integers. After the method returns, the array
16496     * contains the x and y location in that order.</p>
16497     *
16498     * @param location an array of two integers in which to hold the coordinates
16499     */
16500    public void getLocationInWindow(int[] location) {
16501        if (location == null || location.length < 2) {
16502            throw new IllegalArgumentException("location must be an array of two integers");
16503        }
16504
16505        if (mAttachInfo == null) {
16506            // When the view is not attached to a window, this method does not make sense
16507            location[0] = location[1] = 0;
16508            return;
16509        }
16510
16511        float[] position = mAttachInfo.mTmpTransformLocation;
16512        position[0] = position[1] = 0.0f;
16513
16514        if (!hasIdentityMatrix()) {
16515            getMatrix().mapPoints(position);
16516        }
16517
16518        position[0] += mLeft;
16519        position[1] += mTop;
16520
16521        ViewParent viewParent = mParent;
16522        while (viewParent instanceof View) {
16523            final View view = (View) viewParent;
16524
16525            position[0] -= view.mScrollX;
16526            position[1] -= view.mScrollY;
16527
16528            if (!view.hasIdentityMatrix()) {
16529                view.getMatrix().mapPoints(position);
16530            }
16531
16532            position[0] += view.mLeft;
16533            position[1] += view.mTop;
16534
16535            viewParent = view.mParent;
16536         }
16537
16538        if (viewParent instanceof ViewRootImpl) {
16539            // *cough*
16540            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16541            position[1] -= vr.mCurScrollY;
16542        }
16543
16544        location[0] = (int) (position[0] + 0.5f);
16545        location[1] = (int) (position[1] + 0.5f);
16546    }
16547
16548    /**
16549     * {@hide}
16550     * @param id the id of the view to be found
16551     * @return the view of the specified id, null if cannot be found
16552     */
16553    protected View findViewTraversal(int id) {
16554        if (id == mID) {
16555            return this;
16556        }
16557        return null;
16558    }
16559
16560    /**
16561     * {@hide}
16562     * @param tag the tag of the view to be found
16563     * @return the view of specified tag, null if cannot be found
16564     */
16565    protected View findViewWithTagTraversal(Object tag) {
16566        if (tag != null && tag.equals(mTag)) {
16567            return this;
16568        }
16569        return null;
16570    }
16571
16572    /**
16573     * {@hide}
16574     * @param predicate The predicate to evaluate.
16575     * @param childToSkip If not null, ignores this child during the recursive traversal.
16576     * @return The first view that matches the predicate or null.
16577     */
16578    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16579        if (predicate.apply(this)) {
16580            return this;
16581        }
16582        return null;
16583    }
16584
16585    /**
16586     * Look for a child view with the given id.  If this view has the given
16587     * id, return this view.
16588     *
16589     * @param id The id to search for.
16590     * @return The view that has the given id in the hierarchy or null
16591     */
16592    public final View findViewById(int id) {
16593        if (id < 0) {
16594            return null;
16595        }
16596        return findViewTraversal(id);
16597    }
16598
16599    /**
16600     * Finds a view by its unuque and stable accessibility id.
16601     *
16602     * @param accessibilityId The searched accessibility id.
16603     * @return The found view.
16604     */
16605    final View findViewByAccessibilityId(int accessibilityId) {
16606        if (accessibilityId < 0) {
16607            return null;
16608        }
16609        return findViewByAccessibilityIdTraversal(accessibilityId);
16610    }
16611
16612    /**
16613     * Performs the traversal to find a view by its unuque and stable accessibility id.
16614     *
16615     * <strong>Note:</strong>This method does not stop at the root namespace
16616     * boundary since the user can touch the screen at an arbitrary location
16617     * potentially crossing the root namespace bounday which will send an
16618     * accessibility event to accessibility services and they should be able
16619     * to obtain the event source. Also accessibility ids are guaranteed to be
16620     * unique in the window.
16621     *
16622     * @param accessibilityId The accessibility id.
16623     * @return The found view.
16624     *
16625     * @hide
16626     */
16627    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16628        if (getAccessibilityViewId() == accessibilityId) {
16629            return this;
16630        }
16631        return null;
16632    }
16633
16634    /**
16635     * Look for a child view with the given tag.  If this view has the given
16636     * tag, return this view.
16637     *
16638     * @param tag The tag to search for, using "tag.equals(getTag())".
16639     * @return The View that has the given tag in the hierarchy or null
16640     */
16641    public final View findViewWithTag(Object tag) {
16642        if (tag == null) {
16643            return null;
16644        }
16645        return findViewWithTagTraversal(tag);
16646    }
16647
16648    /**
16649     * {@hide}
16650     * Look for a child view that matches the specified predicate.
16651     * If this view matches the predicate, return this view.
16652     *
16653     * @param predicate The predicate to evaluate.
16654     * @return The first view that matches the predicate or null.
16655     */
16656    public final View findViewByPredicate(Predicate<View> predicate) {
16657        return findViewByPredicateTraversal(predicate, null);
16658    }
16659
16660    /**
16661     * {@hide}
16662     * Look for a child view that matches the specified predicate,
16663     * starting with the specified view and its descendents and then
16664     * recusively searching the ancestors and siblings of that view
16665     * until this view is reached.
16666     *
16667     * This method is useful in cases where the predicate does not match
16668     * a single unique view (perhaps multiple views use the same id)
16669     * and we are trying to find the view that is "closest" in scope to the
16670     * starting view.
16671     *
16672     * @param start The view to start from.
16673     * @param predicate The predicate to evaluate.
16674     * @return The first view that matches the predicate or null.
16675     */
16676    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16677        View childToSkip = null;
16678        for (;;) {
16679            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16680            if (view != null || start == this) {
16681                return view;
16682            }
16683
16684            ViewParent parent = start.getParent();
16685            if (parent == null || !(parent instanceof View)) {
16686                return null;
16687            }
16688
16689            childToSkip = start;
16690            start = (View) parent;
16691        }
16692    }
16693
16694    /**
16695     * Sets the identifier for this view. The identifier does not have to be
16696     * unique in this view's hierarchy. The identifier should be a positive
16697     * number.
16698     *
16699     * @see #NO_ID
16700     * @see #getId()
16701     * @see #findViewById(int)
16702     *
16703     * @param id a number used to identify the view
16704     *
16705     * @attr ref android.R.styleable#View_id
16706     */
16707    public void setId(int id) {
16708        mID = id;
16709        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16710            mID = generateViewId();
16711        }
16712    }
16713
16714    /**
16715     * {@hide}
16716     *
16717     * @param isRoot true if the view belongs to the root namespace, false
16718     *        otherwise
16719     */
16720    public void setIsRootNamespace(boolean isRoot) {
16721        if (isRoot) {
16722            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16723        } else {
16724            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16725        }
16726    }
16727
16728    /**
16729     * {@hide}
16730     *
16731     * @return true if the view belongs to the root namespace, false otherwise
16732     */
16733    public boolean isRootNamespace() {
16734        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16735    }
16736
16737    /**
16738     * Returns this view's identifier.
16739     *
16740     * @return a positive integer used to identify the view or {@link #NO_ID}
16741     *         if the view has no ID
16742     *
16743     * @see #setId(int)
16744     * @see #findViewById(int)
16745     * @attr ref android.R.styleable#View_id
16746     */
16747    @ViewDebug.CapturedViewProperty
16748    public int getId() {
16749        return mID;
16750    }
16751
16752    /**
16753     * Returns this view's tag.
16754     *
16755     * @return the Object stored in this view as a tag, or {@code null} if not
16756     *         set
16757     *
16758     * @see #setTag(Object)
16759     * @see #getTag(int)
16760     */
16761    @ViewDebug.ExportedProperty
16762    public Object getTag() {
16763        return mTag;
16764    }
16765
16766    /**
16767     * Sets the tag associated with this view. A tag can be used to mark
16768     * a view in its hierarchy and does not have to be unique within the
16769     * hierarchy. Tags can also be used to store data within a view without
16770     * resorting to another data structure.
16771     *
16772     * @param tag an Object to tag the view with
16773     *
16774     * @see #getTag()
16775     * @see #setTag(int, Object)
16776     */
16777    public void setTag(final Object tag) {
16778        mTag = tag;
16779    }
16780
16781    /**
16782     * Returns the tag associated with this view and the specified key.
16783     *
16784     * @param key The key identifying the tag
16785     *
16786     * @return the Object stored in this view as a tag, or {@code null} if not
16787     *         set
16788     *
16789     * @see #setTag(int, Object)
16790     * @see #getTag()
16791     */
16792    public Object getTag(int key) {
16793        if (mKeyedTags != null) return mKeyedTags.get(key);
16794        return null;
16795    }
16796
16797    /**
16798     * Sets a tag associated with this view and a key. A tag can be used
16799     * to mark a view in its hierarchy and does not have to be unique within
16800     * the hierarchy. Tags can also be used to store data within a view
16801     * without resorting to another data structure.
16802     *
16803     * The specified key should be an id declared in the resources of the
16804     * application to ensure it is unique (see the <a
16805     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16806     * Keys identified as belonging to
16807     * the Android framework or not associated with any package will cause
16808     * an {@link IllegalArgumentException} to be thrown.
16809     *
16810     * @param key The key identifying the tag
16811     * @param tag An Object to tag the view with
16812     *
16813     * @throws IllegalArgumentException If they specified key is not valid
16814     *
16815     * @see #setTag(Object)
16816     * @see #getTag(int)
16817     */
16818    public void setTag(int key, final Object tag) {
16819        // If the package id is 0x00 or 0x01, it's either an undefined package
16820        // or a framework id
16821        if ((key >>> 24) < 2) {
16822            throw new IllegalArgumentException("The key must be an application-specific "
16823                    + "resource id.");
16824        }
16825
16826        setKeyedTag(key, tag);
16827    }
16828
16829    /**
16830     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16831     * framework id.
16832     *
16833     * @hide
16834     */
16835    public void setTagInternal(int key, Object tag) {
16836        if ((key >>> 24) != 0x1) {
16837            throw new IllegalArgumentException("The key must be a framework-specific "
16838                    + "resource id.");
16839        }
16840
16841        setKeyedTag(key, tag);
16842    }
16843
16844    private void setKeyedTag(int key, Object tag) {
16845        if (mKeyedTags == null) {
16846            mKeyedTags = new SparseArray<Object>(2);
16847        }
16848
16849        mKeyedTags.put(key, tag);
16850    }
16851
16852    /**
16853     * Prints information about this view in the log output, with the tag
16854     * {@link #VIEW_LOG_TAG}.
16855     *
16856     * @hide
16857     */
16858    public void debug() {
16859        debug(0);
16860    }
16861
16862    /**
16863     * Prints information about this view in the log output, with the tag
16864     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16865     * indentation defined by the <code>depth</code>.
16866     *
16867     * @param depth the indentation level
16868     *
16869     * @hide
16870     */
16871    protected void debug(int depth) {
16872        String output = debugIndent(depth - 1);
16873
16874        output += "+ " + this;
16875        int id = getId();
16876        if (id != -1) {
16877            output += " (id=" + id + ")";
16878        }
16879        Object tag = getTag();
16880        if (tag != null) {
16881            output += " (tag=" + tag + ")";
16882        }
16883        Log.d(VIEW_LOG_TAG, output);
16884
16885        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16886            output = debugIndent(depth) + " FOCUSED";
16887            Log.d(VIEW_LOG_TAG, output);
16888        }
16889
16890        output = debugIndent(depth);
16891        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16892                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16893                + "} ";
16894        Log.d(VIEW_LOG_TAG, output);
16895
16896        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16897                || mPaddingBottom != 0) {
16898            output = debugIndent(depth);
16899            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16900                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16901            Log.d(VIEW_LOG_TAG, output);
16902        }
16903
16904        output = debugIndent(depth);
16905        output += "mMeasureWidth=" + mMeasuredWidth +
16906                " mMeasureHeight=" + mMeasuredHeight;
16907        Log.d(VIEW_LOG_TAG, output);
16908
16909        output = debugIndent(depth);
16910        if (mLayoutParams == null) {
16911            output += "BAD! no layout params";
16912        } else {
16913            output = mLayoutParams.debug(output);
16914        }
16915        Log.d(VIEW_LOG_TAG, output);
16916
16917        output = debugIndent(depth);
16918        output += "flags={";
16919        output += View.printFlags(mViewFlags);
16920        output += "}";
16921        Log.d(VIEW_LOG_TAG, output);
16922
16923        output = debugIndent(depth);
16924        output += "privateFlags={";
16925        output += View.printPrivateFlags(mPrivateFlags);
16926        output += "}";
16927        Log.d(VIEW_LOG_TAG, output);
16928    }
16929
16930    /**
16931     * Creates a string of whitespaces used for indentation.
16932     *
16933     * @param depth the indentation level
16934     * @return a String containing (depth * 2 + 3) * 2 white spaces
16935     *
16936     * @hide
16937     */
16938    protected static String debugIndent(int depth) {
16939        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16940        for (int i = 0; i < (depth * 2) + 3; i++) {
16941            spaces.append(' ').append(' ');
16942        }
16943        return spaces.toString();
16944    }
16945
16946    /**
16947     * <p>Return the offset of the widget's text baseline from the widget's top
16948     * boundary. If this widget does not support baseline alignment, this
16949     * method returns -1. </p>
16950     *
16951     * @return the offset of the baseline within the widget's bounds or -1
16952     *         if baseline alignment is not supported
16953     */
16954    @ViewDebug.ExportedProperty(category = "layout")
16955    public int getBaseline() {
16956        return -1;
16957    }
16958
16959    /**
16960     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16961     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16962     * a layout pass.
16963     *
16964     * @return whether the view hierarchy is currently undergoing a layout pass
16965     */
16966    public boolean isInLayout() {
16967        ViewRootImpl viewRoot = getViewRootImpl();
16968        return (viewRoot != null && viewRoot.isInLayout());
16969    }
16970
16971    /**
16972     * Call this when something has changed which has invalidated the
16973     * layout of this view. This will schedule a layout pass of the view
16974     * tree. This should not be called while the view hierarchy is currently in a layout
16975     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16976     * end of the current layout pass (and then layout will run again) or after the current
16977     * frame is drawn and the next layout occurs.
16978     *
16979     * <p>Subclasses which override this method should call the superclass method to
16980     * handle possible request-during-layout errors correctly.</p>
16981     */
16982    public void requestLayout() {
16983        if (mMeasureCache != null) mMeasureCache.clear();
16984
16985        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16986            // Only trigger request-during-layout logic if this is the view requesting it,
16987            // not the views in its parent hierarchy
16988            ViewRootImpl viewRoot = getViewRootImpl();
16989            if (viewRoot != null && viewRoot.isInLayout()) {
16990                if (!viewRoot.requestLayoutDuringLayout(this)) {
16991                    return;
16992                }
16993            }
16994            mAttachInfo.mViewRequestingLayout = this;
16995        }
16996
16997        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16998        mPrivateFlags |= PFLAG_INVALIDATED;
16999
17000        if (mParent != null && !mParent.isLayoutRequested()) {
17001            mParent.requestLayout();
17002        }
17003        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17004            mAttachInfo.mViewRequestingLayout = null;
17005        }
17006    }
17007
17008    /**
17009     * Forces this view to be laid out during the next layout pass.
17010     * This method does not call requestLayout() or forceLayout()
17011     * on the parent.
17012     */
17013    public void forceLayout() {
17014        if (mMeasureCache != null) mMeasureCache.clear();
17015
17016        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17017        mPrivateFlags |= PFLAG_INVALIDATED;
17018    }
17019
17020    /**
17021     * <p>
17022     * This is called to find out how big a view should be. The parent
17023     * supplies constraint information in the width and height parameters.
17024     * </p>
17025     *
17026     * <p>
17027     * The actual measurement work of a view is performed in
17028     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17029     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17030     * </p>
17031     *
17032     *
17033     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17034     *        parent
17035     * @param heightMeasureSpec Vertical space requirements as imposed by the
17036     *        parent
17037     *
17038     * @see #onMeasure(int, int)
17039     */
17040    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17041        boolean optical = isLayoutModeOptical(this);
17042        if (optical != isLayoutModeOptical(mParent)) {
17043            Insets insets = getOpticalInsets();
17044            int oWidth  = insets.left + insets.right;
17045            int oHeight = insets.top  + insets.bottom;
17046            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17047            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17048        }
17049
17050        // Suppress sign extension for the low bytes
17051        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17052        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17053
17054        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17055                widthMeasureSpec != mOldWidthMeasureSpec ||
17056                heightMeasureSpec != mOldHeightMeasureSpec) {
17057
17058            // first clears the measured dimension flag
17059            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17060
17061            resolveRtlPropertiesIfNeeded();
17062
17063            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17064                    mMeasureCache.indexOfKey(key);
17065            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17066                // measure ourselves, this should set the measured dimension flag back
17067                onMeasure(widthMeasureSpec, heightMeasureSpec);
17068                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17069            } else {
17070                long value = mMeasureCache.valueAt(cacheIndex);
17071                // Casting a long to int drops the high 32 bits, no mask needed
17072                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17073                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17074            }
17075
17076            // flag not set, setMeasuredDimension() was not invoked, we raise
17077            // an exception to warn the developer
17078            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17079                throw new IllegalStateException("onMeasure() did not set the"
17080                        + " measured dimension by calling"
17081                        + " setMeasuredDimension()");
17082            }
17083
17084            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17085        }
17086
17087        mOldWidthMeasureSpec = widthMeasureSpec;
17088        mOldHeightMeasureSpec = heightMeasureSpec;
17089
17090        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17091                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17092    }
17093
17094    /**
17095     * <p>
17096     * Measure the view and its content to determine the measured width and the
17097     * measured height. This method is invoked by {@link #measure(int, int)} and
17098     * should be overriden by subclasses to provide accurate and efficient
17099     * measurement of their contents.
17100     * </p>
17101     *
17102     * <p>
17103     * <strong>CONTRACT:</strong> When overriding this method, you
17104     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17105     * measured width and height of this view. Failure to do so will trigger an
17106     * <code>IllegalStateException</code>, thrown by
17107     * {@link #measure(int, int)}. Calling the superclass'
17108     * {@link #onMeasure(int, int)} is a valid use.
17109     * </p>
17110     *
17111     * <p>
17112     * The base class implementation of measure defaults to the background size,
17113     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17114     * override {@link #onMeasure(int, int)} to provide better measurements of
17115     * their content.
17116     * </p>
17117     *
17118     * <p>
17119     * If this method is overridden, it is the subclass's responsibility to make
17120     * sure the measured height and width are at least the view's minimum height
17121     * and width ({@link #getSuggestedMinimumHeight()} and
17122     * {@link #getSuggestedMinimumWidth()}).
17123     * </p>
17124     *
17125     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17126     *                         The requirements are encoded with
17127     *                         {@link android.view.View.MeasureSpec}.
17128     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17129     *                         The requirements are encoded with
17130     *                         {@link android.view.View.MeasureSpec}.
17131     *
17132     * @see #getMeasuredWidth()
17133     * @see #getMeasuredHeight()
17134     * @see #setMeasuredDimension(int, int)
17135     * @see #getSuggestedMinimumHeight()
17136     * @see #getSuggestedMinimumWidth()
17137     * @see android.view.View.MeasureSpec#getMode(int)
17138     * @see android.view.View.MeasureSpec#getSize(int)
17139     */
17140    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17141        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17142                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17143    }
17144
17145    /**
17146     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17147     * measured width and measured height. Failing to do so will trigger an
17148     * exception at measurement time.</p>
17149     *
17150     * @param measuredWidth The measured width of this view.  May be a complex
17151     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17152     * {@link #MEASURED_STATE_TOO_SMALL}.
17153     * @param measuredHeight The measured height of this view.  May be a complex
17154     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17155     * {@link #MEASURED_STATE_TOO_SMALL}.
17156     */
17157    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17158        boolean optical = isLayoutModeOptical(this);
17159        if (optical != isLayoutModeOptical(mParent)) {
17160            Insets insets = getOpticalInsets();
17161            int opticalWidth  = insets.left + insets.right;
17162            int opticalHeight = insets.top  + insets.bottom;
17163
17164            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17165            measuredHeight += optical ? opticalHeight : -opticalHeight;
17166        }
17167        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17168    }
17169
17170    /**
17171     * Sets the measured dimension without extra processing for things like optical bounds.
17172     * Useful for reapplying consistent values that have already been cooked with adjustments
17173     * for optical bounds, etc. such as those from the measurement cache.
17174     *
17175     * @param measuredWidth The measured width of this view.  May be a complex
17176     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17177     * {@link #MEASURED_STATE_TOO_SMALL}.
17178     * @param measuredHeight The measured height of this view.  May be a complex
17179     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17180     * {@link #MEASURED_STATE_TOO_SMALL}.
17181     */
17182    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17183        mMeasuredWidth = measuredWidth;
17184        mMeasuredHeight = measuredHeight;
17185
17186        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17187    }
17188
17189    /**
17190     * Merge two states as returned by {@link #getMeasuredState()}.
17191     * @param curState The current state as returned from a view or the result
17192     * of combining multiple views.
17193     * @param newState The new view state to combine.
17194     * @return Returns a new integer reflecting the combination of the two
17195     * states.
17196     */
17197    public static int combineMeasuredStates(int curState, int newState) {
17198        return curState | newState;
17199    }
17200
17201    /**
17202     * Version of {@link #resolveSizeAndState(int, int, int)}
17203     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17204     */
17205    public static int resolveSize(int size, int measureSpec) {
17206        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17207    }
17208
17209    /**
17210     * Utility to reconcile a desired size and state, with constraints imposed
17211     * by a MeasureSpec.  Will take the desired size, unless a different size
17212     * is imposed by the constraints.  The returned value is a compound integer,
17213     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17214     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17215     * size is smaller than the size the view wants to be.
17216     *
17217     * @param size How big the view wants to be
17218     * @param measureSpec Constraints imposed by the parent
17219     * @return Size information bit mask as defined by
17220     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17221     */
17222    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17223        int result = size;
17224        int specMode = MeasureSpec.getMode(measureSpec);
17225        int specSize =  MeasureSpec.getSize(measureSpec);
17226        switch (specMode) {
17227        case MeasureSpec.UNSPECIFIED:
17228            result = size;
17229            break;
17230        case MeasureSpec.AT_MOST:
17231            if (specSize < size) {
17232                result = specSize | MEASURED_STATE_TOO_SMALL;
17233            } else {
17234                result = size;
17235            }
17236            break;
17237        case MeasureSpec.EXACTLY:
17238            result = specSize;
17239            break;
17240        }
17241        return result | (childMeasuredState&MEASURED_STATE_MASK);
17242    }
17243
17244    /**
17245     * Utility to return a default size. Uses the supplied size if the
17246     * MeasureSpec imposed no constraints. Will get larger if allowed
17247     * by the MeasureSpec.
17248     *
17249     * @param size Default size for this view
17250     * @param measureSpec Constraints imposed by the parent
17251     * @return The size this view should be.
17252     */
17253    public static int getDefaultSize(int size, int measureSpec) {
17254        int result = size;
17255        int specMode = MeasureSpec.getMode(measureSpec);
17256        int specSize = MeasureSpec.getSize(measureSpec);
17257
17258        switch (specMode) {
17259        case MeasureSpec.UNSPECIFIED:
17260            result = size;
17261            break;
17262        case MeasureSpec.AT_MOST:
17263        case MeasureSpec.EXACTLY:
17264            result = specSize;
17265            break;
17266        }
17267        return result;
17268    }
17269
17270    /**
17271     * Returns the suggested minimum height that the view should use. This
17272     * returns the maximum of the view's minimum height
17273     * and the background's minimum height
17274     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17275     * <p>
17276     * When being used in {@link #onMeasure(int, int)}, the caller should still
17277     * ensure the returned height is within the requirements of the parent.
17278     *
17279     * @return The suggested minimum height of the view.
17280     */
17281    protected int getSuggestedMinimumHeight() {
17282        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17283
17284    }
17285
17286    /**
17287     * Returns the suggested minimum width that the view should use. This
17288     * returns the maximum of the view's minimum width)
17289     * and the background's minimum width
17290     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17291     * <p>
17292     * When being used in {@link #onMeasure(int, int)}, the caller should still
17293     * ensure the returned width is within the requirements of the parent.
17294     *
17295     * @return The suggested minimum width of the view.
17296     */
17297    protected int getSuggestedMinimumWidth() {
17298        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17299    }
17300
17301    /**
17302     * Returns the minimum height of the view.
17303     *
17304     * @return the minimum height the view will try to be.
17305     *
17306     * @see #setMinimumHeight(int)
17307     *
17308     * @attr ref android.R.styleable#View_minHeight
17309     */
17310    public int getMinimumHeight() {
17311        return mMinHeight;
17312    }
17313
17314    /**
17315     * Sets the minimum height of the view. It is not guaranteed the view will
17316     * be able to achieve this minimum height (for example, if its parent layout
17317     * constrains it with less available height).
17318     *
17319     * @param minHeight The minimum height the view will try to be.
17320     *
17321     * @see #getMinimumHeight()
17322     *
17323     * @attr ref android.R.styleable#View_minHeight
17324     */
17325    public void setMinimumHeight(int minHeight) {
17326        mMinHeight = minHeight;
17327        requestLayout();
17328    }
17329
17330    /**
17331     * Returns the minimum width of the view.
17332     *
17333     * @return the minimum width the view will try to be.
17334     *
17335     * @see #setMinimumWidth(int)
17336     *
17337     * @attr ref android.R.styleable#View_minWidth
17338     */
17339    public int getMinimumWidth() {
17340        return mMinWidth;
17341    }
17342
17343    /**
17344     * Sets the minimum width of the view. It is not guaranteed the view will
17345     * be able to achieve this minimum width (for example, if its parent layout
17346     * constrains it with less available width).
17347     *
17348     * @param minWidth The minimum width the view will try to be.
17349     *
17350     * @see #getMinimumWidth()
17351     *
17352     * @attr ref android.R.styleable#View_minWidth
17353     */
17354    public void setMinimumWidth(int minWidth) {
17355        mMinWidth = minWidth;
17356        requestLayout();
17357
17358    }
17359
17360    /**
17361     * Get the animation currently associated with this view.
17362     *
17363     * @return The animation that is currently playing or
17364     *         scheduled to play for this view.
17365     */
17366    public Animation getAnimation() {
17367        return mCurrentAnimation;
17368    }
17369
17370    /**
17371     * Start the specified animation now.
17372     *
17373     * @param animation the animation to start now
17374     */
17375    public void startAnimation(Animation animation) {
17376        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17377        setAnimation(animation);
17378        invalidateParentCaches();
17379        invalidate(true);
17380    }
17381
17382    /**
17383     * Cancels any animations for this view.
17384     */
17385    public void clearAnimation() {
17386        if (mCurrentAnimation != null) {
17387            mCurrentAnimation.detach();
17388        }
17389        mCurrentAnimation = null;
17390        invalidateParentIfNeeded();
17391    }
17392
17393    /**
17394     * Sets the next animation to play for this view.
17395     * If you want the animation to play immediately, use
17396     * {@link #startAnimation(android.view.animation.Animation)} instead.
17397     * This method provides allows fine-grained
17398     * control over the start time and invalidation, but you
17399     * must make sure that 1) the animation has a start time set, and
17400     * 2) the view's parent (which controls animations on its children)
17401     * will be invalidated when the animation is supposed to
17402     * start.
17403     *
17404     * @param animation The next animation, or null.
17405     */
17406    public void setAnimation(Animation animation) {
17407        mCurrentAnimation = animation;
17408
17409        if (animation != null) {
17410            // If the screen is off assume the animation start time is now instead of
17411            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17412            // would cause the animation to start when the screen turns back on
17413            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17414                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17415                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17416            }
17417            animation.reset();
17418        }
17419    }
17420
17421    /**
17422     * Invoked by a parent ViewGroup to notify the start of the animation
17423     * currently associated with this view. If you override this method,
17424     * always call super.onAnimationStart();
17425     *
17426     * @see #setAnimation(android.view.animation.Animation)
17427     * @see #getAnimation()
17428     */
17429    protected void onAnimationStart() {
17430        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17431    }
17432
17433    /**
17434     * Invoked by a parent ViewGroup to notify the end of the animation
17435     * currently associated with this view. If you override this method,
17436     * always call super.onAnimationEnd();
17437     *
17438     * @see #setAnimation(android.view.animation.Animation)
17439     * @see #getAnimation()
17440     */
17441    protected void onAnimationEnd() {
17442        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17443    }
17444
17445    /**
17446     * Invoked if there is a Transform that involves alpha. Subclass that can
17447     * draw themselves with the specified alpha should return true, and then
17448     * respect that alpha when their onDraw() is called. If this returns false
17449     * then the view may be redirected to draw into an offscreen buffer to
17450     * fulfill the request, which will look fine, but may be slower than if the
17451     * subclass handles it internally. The default implementation returns false.
17452     *
17453     * @param alpha The alpha (0..255) to apply to the view's drawing
17454     * @return true if the view can draw with the specified alpha.
17455     */
17456    protected boolean onSetAlpha(int alpha) {
17457        return false;
17458    }
17459
17460    /**
17461     * This is used by the RootView to perform an optimization when
17462     * the view hierarchy contains one or several SurfaceView.
17463     * SurfaceView is always considered transparent, but its children are not,
17464     * therefore all View objects remove themselves from the global transparent
17465     * region (passed as a parameter to this function).
17466     *
17467     * @param region The transparent region for this ViewAncestor (window).
17468     *
17469     * @return Returns true if the effective visibility of the view at this
17470     * point is opaque, regardless of the transparent region; returns false
17471     * if it is possible for underlying windows to be seen behind the view.
17472     *
17473     * {@hide}
17474     */
17475    public boolean gatherTransparentRegion(Region region) {
17476        final AttachInfo attachInfo = mAttachInfo;
17477        if (region != null && attachInfo != null) {
17478            final int pflags = mPrivateFlags;
17479            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17480                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17481                // remove it from the transparent region.
17482                final int[] location = attachInfo.mTransparentLocation;
17483                getLocationInWindow(location);
17484                region.op(location[0], location[1], location[0] + mRight - mLeft,
17485                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17486            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17487                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17488                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17489                // exists, so we remove the background drawable's non-transparent
17490                // parts from this transparent region.
17491                applyDrawableToTransparentRegion(mBackground, region);
17492            }
17493        }
17494        return true;
17495    }
17496
17497    /**
17498     * Play a sound effect for this view.
17499     *
17500     * <p>The framework will play sound effects for some built in actions, such as
17501     * clicking, but you may wish to play these effects in your widget,
17502     * for instance, for internal navigation.
17503     *
17504     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17505     * {@link #isSoundEffectsEnabled()} is true.
17506     *
17507     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17508     */
17509    public void playSoundEffect(int soundConstant) {
17510        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17511            return;
17512        }
17513        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17514    }
17515
17516    /**
17517     * BZZZTT!!1!
17518     *
17519     * <p>Provide haptic feedback to the user for this view.
17520     *
17521     * <p>The framework will provide haptic feedback for some built in actions,
17522     * such as long presses, but you may wish to provide feedback for your
17523     * own widget.
17524     *
17525     * <p>The feedback will only be performed if
17526     * {@link #isHapticFeedbackEnabled()} is true.
17527     *
17528     * @param feedbackConstant One of the constants defined in
17529     * {@link HapticFeedbackConstants}
17530     */
17531    public boolean performHapticFeedback(int feedbackConstant) {
17532        return performHapticFeedback(feedbackConstant, 0);
17533    }
17534
17535    /**
17536     * BZZZTT!!1!
17537     *
17538     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17539     *
17540     * @param feedbackConstant One of the constants defined in
17541     * {@link HapticFeedbackConstants}
17542     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17543     */
17544    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17545        if (mAttachInfo == null) {
17546            return false;
17547        }
17548        //noinspection SimplifiableIfStatement
17549        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17550                && !isHapticFeedbackEnabled()) {
17551            return false;
17552        }
17553        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17554                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17555    }
17556
17557    /**
17558     * Request that the visibility of the status bar or other screen/window
17559     * decorations be changed.
17560     *
17561     * <p>This method is used to put the over device UI into temporary modes
17562     * where the user's attention is focused more on the application content,
17563     * by dimming or hiding surrounding system affordances.  This is typically
17564     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17565     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17566     * to be placed behind the action bar (and with these flags other system
17567     * affordances) so that smooth transitions between hiding and showing them
17568     * can be done.
17569     *
17570     * <p>Two representative examples of the use of system UI visibility is
17571     * implementing a content browsing application (like a magazine reader)
17572     * and a video playing application.
17573     *
17574     * <p>The first code shows a typical implementation of a View in a content
17575     * browsing application.  In this implementation, the application goes
17576     * into a content-oriented mode by hiding the status bar and action bar,
17577     * and putting the navigation elements into lights out mode.  The user can
17578     * then interact with content while in this mode.  Such an application should
17579     * provide an easy way for the user to toggle out of the mode (such as to
17580     * check information in the status bar or access notifications).  In the
17581     * implementation here, this is done simply by tapping on the content.
17582     *
17583     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17584     *      content}
17585     *
17586     * <p>This second code sample shows a typical implementation of a View
17587     * in a video playing application.  In this situation, while the video is
17588     * playing the application would like to go into a complete full-screen mode,
17589     * to use as much of the display as possible for the video.  When in this state
17590     * the user can not interact with the application; the system intercepts
17591     * touching on the screen to pop the UI out of full screen mode.  See
17592     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17593     *
17594     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17595     *      content}
17596     *
17597     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17598     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17599     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17600     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17601     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17602     */
17603    public void setSystemUiVisibility(int visibility) {
17604        if (visibility != mSystemUiVisibility) {
17605            mSystemUiVisibility = visibility;
17606            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17607                mParent.recomputeViewAttributes(this);
17608            }
17609        }
17610    }
17611
17612    /**
17613     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17614     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17615     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17616     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17617     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17618     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17619     */
17620    public int getSystemUiVisibility() {
17621        return mSystemUiVisibility;
17622    }
17623
17624    /**
17625     * Returns the current system UI visibility that is currently set for
17626     * the entire window.  This is the combination of the
17627     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17628     * views in the window.
17629     */
17630    public int getWindowSystemUiVisibility() {
17631        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17632    }
17633
17634    /**
17635     * Override to find out when the window's requested system UI visibility
17636     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17637     * This is different from the callbacks received through
17638     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17639     * in that this is only telling you about the local request of the window,
17640     * not the actual values applied by the system.
17641     */
17642    public void onWindowSystemUiVisibilityChanged(int visible) {
17643    }
17644
17645    /**
17646     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17647     * the view hierarchy.
17648     */
17649    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17650        onWindowSystemUiVisibilityChanged(visible);
17651    }
17652
17653    /**
17654     * Set a listener to receive callbacks when the visibility of the system bar changes.
17655     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17656     */
17657    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17658        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17659        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17660            mParent.recomputeViewAttributes(this);
17661        }
17662    }
17663
17664    /**
17665     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17666     * the view hierarchy.
17667     */
17668    public void dispatchSystemUiVisibilityChanged(int visibility) {
17669        ListenerInfo li = mListenerInfo;
17670        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17671            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17672                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17673        }
17674    }
17675
17676    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17677        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17678        if (val != mSystemUiVisibility) {
17679            setSystemUiVisibility(val);
17680            return true;
17681        }
17682        return false;
17683    }
17684
17685    /** @hide */
17686    public void setDisabledSystemUiVisibility(int flags) {
17687        if (mAttachInfo != null) {
17688            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17689                mAttachInfo.mDisabledSystemUiVisibility = flags;
17690                if (mParent != null) {
17691                    mParent.recomputeViewAttributes(this);
17692                }
17693            }
17694        }
17695    }
17696
17697    /**
17698     * Creates an image that the system displays during the drag and drop
17699     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17700     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17701     * appearance as the given View. The default also positions the center of the drag shadow
17702     * directly under the touch point. If no View is provided (the constructor with no parameters
17703     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17704     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17705     * default is an invisible drag shadow.
17706     * <p>
17707     * You are not required to use the View you provide to the constructor as the basis of the
17708     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17709     * anything you want as the drag shadow.
17710     * </p>
17711     * <p>
17712     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17713     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17714     *  size and position of the drag shadow. It uses this data to construct a
17715     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17716     *  so that your application can draw the shadow image in the Canvas.
17717     * </p>
17718     *
17719     * <div class="special reference">
17720     * <h3>Developer Guides</h3>
17721     * <p>For a guide to implementing drag and drop features, read the
17722     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17723     * </div>
17724     */
17725    public static class DragShadowBuilder {
17726        private final WeakReference<View> mView;
17727
17728        /**
17729         * Constructs a shadow image builder based on a View. By default, the resulting drag
17730         * shadow will have the same appearance and dimensions as the View, with the touch point
17731         * over the center of the View.
17732         * @param view A View. Any View in scope can be used.
17733         */
17734        public DragShadowBuilder(View view) {
17735            mView = new WeakReference<View>(view);
17736        }
17737
17738        /**
17739         * Construct a shadow builder object with no associated View.  This
17740         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17741         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17742         * to supply the drag shadow's dimensions and appearance without
17743         * reference to any View object. If they are not overridden, then the result is an
17744         * invisible drag shadow.
17745         */
17746        public DragShadowBuilder() {
17747            mView = new WeakReference<View>(null);
17748        }
17749
17750        /**
17751         * Returns the View object that had been passed to the
17752         * {@link #View.DragShadowBuilder(View)}
17753         * constructor.  If that View parameter was {@code null} or if the
17754         * {@link #View.DragShadowBuilder()}
17755         * constructor was used to instantiate the builder object, this method will return
17756         * null.
17757         *
17758         * @return The View object associate with this builder object.
17759         */
17760        @SuppressWarnings({"JavadocReference"})
17761        final public View getView() {
17762            return mView.get();
17763        }
17764
17765        /**
17766         * Provides the metrics for the shadow image. These include the dimensions of
17767         * the shadow image, and the point within that shadow that should
17768         * be centered under the touch location while dragging.
17769         * <p>
17770         * The default implementation sets the dimensions of the shadow to be the
17771         * same as the dimensions of the View itself and centers the shadow under
17772         * the touch point.
17773         * </p>
17774         *
17775         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17776         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17777         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17778         * image.
17779         *
17780         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17781         * shadow image that should be underneath the touch point during the drag and drop
17782         * operation. Your application must set {@link android.graphics.Point#x} to the
17783         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17784         */
17785        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17786            final View view = mView.get();
17787            if (view != null) {
17788                shadowSize.set(view.getWidth(), view.getHeight());
17789                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17790            } else {
17791                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17792            }
17793        }
17794
17795        /**
17796         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17797         * based on the dimensions it received from the
17798         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17799         *
17800         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17801         */
17802        public void onDrawShadow(Canvas canvas) {
17803            final View view = mView.get();
17804            if (view != null) {
17805                view.draw(canvas);
17806            } else {
17807                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17808            }
17809        }
17810    }
17811
17812    /**
17813     * Starts a drag and drop operation. When your application calls this method, it passes a
17814     * {@link android.view.View.DragShadowBuilder} object to the system. The
17815     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17816     * to get metrics for the drag shadow, and then calls the object's
17817     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17818     * <p>
17819     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17820     *  drag events to all the View objects in your application that are currently visible. It does
17821     *  this either by calling the View object's drag listener (an implementation of
17822     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17823     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17824     *  Both are passed a {@link android.view.DragEvent} object that has a
17825     *  {@link android.view.DragEvent#getAction()} value of
17826     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17827     * </p>
17828     * <p>
17829     * Your application can invoke startDrag() on any attached View object. The View object does not
17830     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17831     * be related to the View the user selected for dragging.
17832     * </p>
17833     * @param data A {@link android.content.ClipData} object pointing to the data to be
17834     * transferred by the drag and drop operation.
17835     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17836     * drag shadow.
17837     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17838     * drop operation. This Object is put into every DragEvent object sent by the system during the
17839     * current drag.
17840     * <p>
17841     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17842     * to the target Views. For example, it can contain flags that differentiate between a
17843     * a copy operation and a move operation.
17844     * </p>
17845     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17846     * so the parameter should be set to 0.
17847     * @return {@code true} if the method completes successfully, or
17848     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17849     * do a drag, and so no drag operation is in progress.
17850     */
17851    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17852            Object myLocalState, int flags) {
17853        if (ViewDebug.DEBUG_DRAG) {
17854            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17855        }
17856        boolean okay = false;
17857
17858        Point shadowSize = new Point();
17859        Point shadowTouchPoint = new Point();
17860        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17861
17862        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17863                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17864            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17865        }
17866
17867        if (ViewDebug.DEBUG_DRAG) {
17868            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17869                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17870        }
17871        Surface surface = new Surface();
17872        try {
17873            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17874                    flags, shadowSize.x, shadowSize.y, surface);
17875            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17876                    + " surface=" + surface);
17877            if (token != null) {
17878                Canvas canvas = surface.lockCanvas(null);
17879                try {
17880                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17881                    shadowBuilder.onDrawShadow(canvas);
17882                } finally {
17883                    surface.unlockCanvasAndPost(canvas);
17884                }
17885
17886                final ViewRootImpl root = getViewRootImpl();
17887
17888                // Cache the local state object for delivery with DragEvents
17889                root.setLocalDragState(myLocalState);
17890
17891                // repurpose 'shadowSize' for the last touch point
17892                root.getLastTouchPoint(shadowSize);
17893
17894                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17895                        shadowSize.x, shadowSize.y,
17896                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17897                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17898
17899                // Off and running!  Release our local surface instance; the drag
17900                // shadow surface is now managed by the system process.
17901                surface.release();
17902            }
17903        } catch (Exception e) {
17904            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17905            surface.destroy();
17906        }
17907
17908        return okay;
17909    }
17910
17911    /**
17912     * Handles drag events sent by the system following a call to
17913     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17914     *<p>
17915     * When the system calls this method, it passes a
17916     * {@link android.view.DragEvent} object. A call to
17917     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17918     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17919     * operation.
17920     * @param event The {@link android.view.DragEvent} sent by the system.
17921     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17922     * in DragEvent, indicating the type of drag event represented by this object.
17923     * @return {@code true} if the method was successful, otherwise {@code false}.
17924     * <p>
17925     *  The method should return {@code true} in response to an action type of
17926     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17927     *  operation.
17928     * </p>
17929     * <p>
17930     *  The method should also return {@code true} in response to an action type of
17931     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17932     *  {@code false} if it didn't.
17933     * </p>
17934     */
17935    public boolean onDragEvent(DragEvent event) {
17936        return false;
17937    }
17938
17939    /**
17940     * Detects if this View is enabled and has a drag event listener.
17941     * If both are true, then it calls the drag event listener with the
17942     * {@link android.view.DragEvent} it received. If the drag event listener returns
17943     * {@code true}, then dispatchDragEvent() returns {@code true}.
17944     * <p>
17945     * For all other cases, the method calls the
17946     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17947     * method and returns its result.
17948     * </p>
17949     * <p>
17950     * This ensures that a drag event is always consumed, even if the View does not have a drag
17951     * event listener. However, if the View has a listener and the listener returns true, then
17952     * onDragEvent() is not called.
17953     * </p>
17954     */
17955    public boolean dispatchDragEvent(DragEvent event) {
17956        ListenerInfo li = mListenerInfo;
17957        //noinspection SimplifiableIfStatement
17958        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17959                && li.mOnDragListener.onDrag(this, event)) {
17960            return true;
17961        }
17962        return onDragEvent(event);
17963    }
17964
17965    boolean canAcceptDrag() {
17966        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17967    }
17968
17969    /**
17970     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17971     * it is ever exposed at all.
17972     * @hide
17973     */
17974    public void onCloseSystemDialogs(String reason) {
17975    }
17976
17977    /**
17978     * Given a Drawable whose bounds have been set to draw into this view,
17979     * update a Region being computed for
17980     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17981     * that any non-transparent parts of the Drawable are removed from the
17982     * given transparent region.
17983     *
17984     * @param dr The Drawable whose transparency is to be applied to the region.
17985     * @param region A Region holding the current transparency information,
17986     * where any parts of the region that are set are considered to be
17987     * transparent.  On return, this region will be modified to have the
17988     * transparency information reduced by the corresponding parts of the
17989     * Drawable that are not transparent.
17990     * {@hide}
17991     */
17992    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17993        if (DBG) {
17994            Log.i("View", "Getting transparent region for: " + this);
17995        }
17996        final Region r = dr.getTransparentRegion();
17997        final Rect db = dr.getBounds();
17998        final AttachInfo attachInfo = mAttachInfo;
17999        if (r != null && attachInfo != null) {
18000            final int w = getRight()-getLeft();
18001            final int h = getBottom()-getTop();
18002            if (db.left > 0) {
18003                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18004                r.op(0, 0, db.left, h, Region.Op.UNION);
18005            }
18006            if (db.right < w) {
18007                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18008                r.op(db.right, 0, w, h, Region.Op.UNION);
18009            }
18010            if (db.top > 0) {
18011                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18012                r.op(0, 0, w, db.top, Region.Op.UNION);
18013            }
18014            if (db.bottom < h) {
18015                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18016                r.op(0, db.bottom, w, h, Region.Op.UNION);
18017            }
18018            final int[] location = attachInfo.mTransparentLocation;
18019            getLocationInWindow(location);
18020            r.translate(location[0], location[1]);
18021            region.op(r, Region.Op.INTERSECT);
18022        } else {
18023            region.op(db, Region.Op.DIFFERENCE);
18024        }
18025    }
18026
18027    private void checkForLongClick(int delayOffset) {
18028        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18029            mHasPerformedLongPress = false;
18030
18031            if (mPendingCheckForLongPress == null) {
18032                mPendingCheckForLongPress = new CheckForLongPress();
18033            }
18034            mPendingCheckForLongPress.rememberWindowAttachCount();
18035            postDelayed(mPendingCheckForLongPress,
18036                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18037        }
18038    }
18039
18040    /**
18041     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18042     * LayoutInflater} class, which provides a full range of options for view inflation.
18043     *
18044     * @param context The Context object for your activity or application.
18045     * @param resource The resource ID to inflate
18046     * @param root A view group that will be the parent.  Used to properly inflate the
18047     * layout_* parameters.
18048     * @see LayoutInflater
18049     */
18050    public static View inflate(Context context, int resource, ViewGroup root) {
18051        LayoutInflater factory = LayoutInflater.from(context);
18052        return factory.inflate(resource, root);
18053    }
18054
18055    /**
18056     * Scroll the view with standard behavior for scrolling beyond the normal
18057     * content boundaries. Views that call this method should override
18058     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18059     * results of an over-scroll operation.
18060     *
18061     * Views can use this method to handle any touch or fling-based scrolling.
18062     *
18063     * @param deltaX Change in X in pixels
18064     * @param deltaY Change in Y in pixels
18065     * @param scrollX Current X scroll value in pixels before applying deltaX
18066     * @param scrollY Current Y scroll value in pixels before applying deltaY
18067     * @param scrollRangeX Maximum content scroll range along the X axis
18068     * @param scrollRangeY Maximum content scroll range along the Y axis
18069     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18070     *          along the X axis.
18071     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18072     *          along the Y axis.
18073     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18074     * @return true if scrolling was clamped to an over-scroll boundary along either
18075     *          axis, false otherwise.
18076     */
18077    @SuppressWarnings({"UnusedParameters"})
18078    protected boolean overScrollBy(int deltaX, int deltaY,
18079            int scrollX, int scrollY,
18080            int scrollRangeX, int scrollRangeY,
18081            int maxOverScrollX, int maxOverScrollY,
18082            boolean isTouchEvent) {
18083        final int overScrollMode = mOverScrollMode;
18084        final boolean canScrollHorizontal =
18085                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18086        final boolean canScrollVertical =
18087                computeVerticalScrollRange() > computeVerticalScrollExtent();
18088        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18089                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18090        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18091                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18092
18093        int newScrollX = scrollX + deltaX;
18094        if (!overScrollHorizontal) {
18095            maxOverScrollX = 0;
18096        }
18097
18098        int newScrollY = scrollY + deltaY;
18099        if (!overScrollVertical) {
18100            maxOverScrollY = 0;
18101        }
18102
18103        // Clamp values if at the limits and record
18104        final int left = -maxOverScrollX;
18105        final int right = maxOverScrollX + scrollRangeX;
18106        final int top = -maxOverScrollY;
18107        final int bottom = maxOverScrollY + scrollRangeY;
18108
18109        boolean clampedX = false;
18110        if (newScrollX > right) {
18111            newScrollX = right;
18112            clampedX = true;
18113        } else if (newScrollX < left) {
18114            newScrollX = left;
18115            clampedX = true;
18116        }
18117
18118        boolean clampedY = false;
18119        if (newScrollY > bottom) {
18120            newScrollY = bottom;
18121            clampedY = true;
18122        } else if (newScrollY < top) {
18123            newScrollY = top;
18124            clampedY = true;
18125        }
18126
18127        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18128
18129        return clampedX || clampedY;
18130    }
18131
18132    /**
18133     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18134     * respond to the results of an over-scroll operation.
18135     *
18136     * @param scrollX New X scroll value in pixels
18137     * @param scrollY New Y scroll value in pixels
18138     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18139     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18140     */
18141    protected void onOverScrolled(int scrollX, int scrollY,
18142            boolean clampedX, boolean clampedY) {
18143        // Intentionally empty.
18144    }
18145
18146    /**
18147     * Returns the over-scroll mode for this view. The result will be
18148     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18149     * (allow over-scrolling only if the view content is larger than the container),
18150     * or {@link #OVER_SCROLL_NEVER}.
18151     *
18152     * @return This view's over-scroll mode.
18153     */
18154    public int getOverScrollMode() {
18155        return mOverScrollMode;
18156    }
18157
18158    /**
18159     * Set the over-scroll mode for this view. Valid over-scroll modes are
18160     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18161     * (allow over-scrolling only if the view content is larger than the container),
18162     * or {@link #OVER_SCROLL_NEVER}.
18163     *
18164     * Setting the over-scroll mode of a view will have an effect only if the
18165     * view is capable of scrolling.
18166     *
18167     * @param overScrollMode The new over-scroll mode for this view.
18168     */
18169    public void setOverScrollMode(int overScrollMode) {
18170        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18171                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18172                overScrollMode != OVER_SCROLL_NEVER) {
18173            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18174        }
18175        mOverScrollMode = overScrollMode;
18176    }
18177
18178    /**
18179     * Enable or disable nested scrolling for this view.
18180     *
18181     * <p>If this property is set to true the view will be permitted to initiate nested
18182     * scrolling operations with a compatible parent view in the current hierarchy. If this
18183     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18184     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18185     * the nested scroll.</p>
18186     *
18187     * @param enabled true to enable nested scrolling, false to disable
18188     *
18189     * @see #isNestedScrollingEnabled()
18190     */
18191    public void setNestedScrollingEnabled(boolean enabled) {
18192        if (enabled) {
18193            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18194        } else {
18195            stopNestedScroll();
18196            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18197        }
18198    }
18199
18200    /**
18201     * Returns true if nested scrolling is enabled for this view.
18202     *
18203     * <p>If nested scrolling is enabled and this View class implementation supports it,
18204     * this view will act as a nested scrolling child view when applicable, forwarding data
18205     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18206     * parent.</p>
18207     *
18208     * @return true if nested scrolling is enabled
18209     *
18210     * @see #setNestedScrollingEnabled(boolean)
18211     */
18212    public boolean isNestedScrollingEnabled() {
18213        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18214                PFLAG3_NESTED_SCROLLING_ENABLED;
18215    }
18216
18217    /**
18218     * Begin a nestable scroll operation along the given axes.
18219     *
18220     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18221     *
18222     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18223     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18224     * In the case of touch scrolling the nested scroll will be terminated automatically in
18225     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18226     * In the event of programmatic scrolling the caller must explicitly call
18227     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18228     *
18229     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18230     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18231     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18232     *
18233     * <p>At each incremental step of the scroll the caller should invoke
18234     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18235     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18236     * parent at least partially consumed the scroll and the caller should adjust the amount it
18237     * scrolls by.</p>
18238     *
18239     * <p>After applying the remainder of the scroll delta the caller should invoke
18240     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18241     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18242     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18243     * </p>
18244     *
18245     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18246     *             {@link #SCROLL_AXIS_VERTICAL}.
18247     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18248     *         the current gesture.
18249     *
18250     * @see #stopNestedScroll()
18251     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18252     * @see #dispatchNestedScroll(int, int, int, int, int[])
18253     */
18254    public boolean startNestedScroll(int axes) {
18255        if (hasNestedScrollingParent()) {
18256            // Already in progress
18257            return true;
18258        }
18259        if (isNestedScrollingEnabled()) {
18260            ViewParent p = getParent();
18261            View child = this;
18262            while (p != null) {
18263                try {
18264                    if (p.onStartNestedScroll(child, this, axes)) {
18265                        mNestedScrollingParent = p;
18266                        p.onNestedScrollAccepted(child, this, axes);
18267                        return true;
18268                    }
18269                } catch (AbstractMethodError e) {
18270                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18271                            "method onStartNestedScroll", e);
18272                    // Allow the search upward to continue
18273                }
18274                if (p instanceof View) {
18275                    child = (View) p;
18276                }
18277                p = p.getParent();
18278            }
18279        }
18280        return false;
18281    }
18282
18283    /**
18284     * Stop a nested scroll in progress.
18285     *
18286     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18287     *
18288     * @see #startNestedScroll(int)
18289     */
18290    public void stopNestedScroll() {
18291        if (mNestedScrollingParent != null) {
18292            mNestedScrollingParent.onStopNestedScroll(this);
18293            mNestedScrollingParent = null;
18294        }
18295    }
18296
18297    /**
18298     * Returns true if this view has a nested scrolling parent.
18299     *
18300     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18301     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18302     *
18303     * @return whether this view has a nested scrolling parent
18304     */
18305    public boolean hasNestedScrollingParent() {
18306        return mNestedScrollingParent != null;
18307    }
18308
18309    /**
18310     * Dispatch one step of a nested scroll in progress.
18311     *
18312     * <p>Implementations of views that support nested scrolling should call this to report
18313     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18314     * is not currently in progress or nested scrolling is not
18315     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18316     *
18317     * <p>Compatible View implementations should also call
18318     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18319     * consuming a component of the scroll event themselves.</p>
18320     *
18321     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18322     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18323     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18324     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18325     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18326     *                       in local view coordinates of this view from before this operation
18327     *                       to after it completes. View implementations may use this to adjust
18328     *                       expected input coordinate tracking.
18329     * @return true if the event was dispatched, false if it could not be dispatched.
18330     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18331     */
18332    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18333            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18334        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18335            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18336                int startX = 0;
18337                int startY = 0;
18338                if (offsetInWindow != null) {
18339                    getLocationInWindow(offsetInWindow);
18340                    startX = offsetInWindow[0];
18341                    startY = offsetInWindow[1];
18342                }
18343
18344                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18345                        dxUnconsumed, dyUnconsumed);
18346
18347                if (offsetInWindow != null) {
18348                    getLocationInWindow(offsetInWindow);
18349                    offsetInWindow[0] -= startX;
18350                    offsetInWindow[1] -= startY;
18351                }
18352                return true;
18353            } else if (offsetInWindow != null) {
18354                // No motion, no dispatch. Keep offsetInWindow up to date.
18355                offsetInWindow[0] = 0;
18356                offsetInWindow[1] = 0;
18357            }
18358        }
18359        return false;
18360    }
18361
18362    /**
18363     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18364     *
18365     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18366     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18367     * scrolling operation to consume some or all of the scroll operation before the child view
18368     * consumes it.</p>
18369     *
18370     * @param dx Horizontal scroll distance in pixels
18371     * @param dy Vertical scroll distance in pixels
18372     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18373     *                 and consumed[1] the consumed dy.
18374     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18375     *                       in local view coordinates of this view from before this operation
18376     *                       to after it completes. View implementations may use this to adjust
18377     *                       expected input coordinate tracking.
18378     * @return true if the parent consumed some or all of the scroll delta
18379     * @see #dispatchNestedScroll(int, int, int, int, int[])
18380     */
18381    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18382        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18383            if (dx != 0 || dy != 0) {
18384                int startX = 0;
18385                int startY = 0;
18386                if (offsetInWindow != null) {
18387                    getLocationInWindow(offsetInWindow);
18388                    startX = offsetInWindow[0];
18389                    startY = offsetInWindow[1];
18390                }
18391
18392                if (consumed == null) {
18393                    if (mTempNestedScrollConsumed == null) {
18394                        mTempNestedScrollConsumed = new int[2];
18395                    }
18396                    consumed = mTempNestedScrollConsumed;
18397                }
18398                consumed[0] = 0;
18399                consumed[1] = 0;
18400                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18401
18402                if (offsetInWindow != null) {
18403                    getLocationInWindow(offsetInWindow);
18404                    offsetInWindow[0] -= startX;
18405                    offsetInWindow[1] -= startY;
18406                }
18407                return consumed[0] != 0 || consumed[1] != 0;
18408            } else if (offsetInWindow != null) {
18409                offsetInWindow[0] = 0;
18410                offsetInWindow[1] = 0;
18411            }
18412        }
18413        return false;
18414    }
18415
18416    /**
18417     * Dispatch a fling to a nested scrolling parent.
18418     *
18419     * <p>This method should be used to indicate that a nested scrolling child has detected
18420     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18421     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18422     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18423     * along a scrollable axis.</p>
18424     *
18425     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18426     * its own content, it can use this method to delegate the fling to its nested scrolling
18427     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18428     *
18429     * @param velocityX Horizontal fling velocity in pixels per second
18430     * @param velocityY Vertical fling velocity in pixels per second
18431     * @param consumed true if the child consumed the fling, false otherwise
18432     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18433     */
18434    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18435        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18436            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18437        }
18438        return false;
18439    }
18440
18441    /**
18442     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18443     *
18444     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18445     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18446     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18447     * before the child view consumes it. If this method returns <code>true</code>, a nested
18448     * parent view consumed the fling and this view should not scroll as a result.</p>
18449     *
18450     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18451     * the fling at a time. If a parent view consumed the fling this method will return false.
18452     * Custom view implementations should account for this in two ways:</p>
18453     *
18454     * <ul>
18455     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18456     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18457     *     position regardless.</li>
18458     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18459     *     even to settle back to a valid idle position.</li>
18460     * </ul>
18461     *
18462     * <p>Views should also not offer fling velocities to nested parent views along an axis
18463     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18464     * should not offer a horizontal fling velocity to its parents since scrolling along that
18465     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18466     *
18467     * @param velocityX Horizontal fling velocity in pixels per second
18468     * @param velocityY Vertical fling velocity in pixels per second
18469     * @return true if a nested scrolling parent consumed the fling
18470     */
18471    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18472        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18473            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18474        }
18475        return false;
18476    }
18477
18478    /**
18479     * Gets a scale factor that determines the distance the view should scroll
18480     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18481     * @return The vertical scroll scale factor.
18482     * @hide
18483     */
18484    protected float getVerticalScrollFactor() {
18485        if (mVerticalScrollFactor == 0) {
18486            TypedValue outValue = new TypedValue();
18487            if (!mContext.getTheme().resolveAttribute(
18488                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18489                throw new IllegalStateException(
18490                        "Expected theme to define listPreferredItemHeight.");
18491            }
18492            mVerticalScrollFactor = outValue.getDimension(
18493                    mContext.getResources().getDisplayMetrics());
18494        }
18495        return mVerticalScrollFactor;
18496    }
18497
18498    /**
18499     * Gets a scale factor that determines the distance the view should scroll
18500     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18501     * @return The horizontal scroll scale factor.
18502     * @hide
18503     */
18504    protected float getHorizontalScrollFactor() {
18505        // TODO: Should use something else.
18506        return getVerticalScrollFactor();
18507    }
18508
18509    /**
18510     * Return the value specifying the text direction or policy that was set with
18511     * {@link #setTextDirection(int)}.
18512     *
18513     * @return the defined text direction. It can 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     * @attr ref android.R.styleable#View_textDirection
18523     *
18524     * @hide
18525     */
18526    @ViewDebug.ExportedProperty(category = "text", mapping = {
18527            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18528            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18529            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18530            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18531            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18532            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18533    })
18534    public int getRawTextDirection() {
18535        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18536    }
18537
18538    /**
18539     * Set the text direction.
18540     *
18541     * @param textDirection the direction to set. Should be one of:
18542     *
18543     * {@link #TEXT_DIRECTION_INHERIT},
18544     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18545     * {@link #TEXT_DIRECTION_ANY_RTL},
18546     * {@link #TEXT_DIRECTION_LTR},
18547     * {@link #TEXT_DIRECTION_RTL},
18548     * {@link #TEXT_DIRECTION_LOCALE}
18549     *
18550     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18551     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18552     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18553     *
18554     * @attr ref android.R.styleable#View_textDirection
18555     */
18556    public void setTextDirection(int textDirection) {
18557        if (getRawTextDirection() != textDirection) {
18558            // Reset the current text direction and the resolved one
18559            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18560            resetResolvedTextDirection();
18561            // Set the new text direction
18562            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18563            // Do resolution
18564            resolveTextDirection();
18565            // Notify change
18566            onRtlPropertiesChanged(getLayoutDirection());
18567            // Refresh
18568            requestLayout();
18569            invalidate(true);
18570        }
18571    }
18572
18573    /**
18574     * Return the resolved text direction.
18575     *
18576     * @return the resolved text direction. Returns one of:
18577     *
18578     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18579     * {@link #TEXT_DIRECTION_ANY_RTL},
18580     * {@link #TEXT_DIRECTION_LTR},
18581     * {@link #TEXT_DIRECTION_RTL},
18582     * {@link #TEXT_DIRECTION_LOCALE}
18583     *
18584     * @attr ref android.R.styleable#View_textDirection
18585     */
18586    @ViewDebug.ExportedProperty(category = "text", mapping = {
18587            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18588            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18589            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18590            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18591            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18592            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18593    })
18594    public int getTextDirection() {
18595        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18596    }
18597
18598    /**
18599     * Resolve the text direction.
18600     *
18601     * @return true if resolution has been done, false otherwise.
18602     *
18603     * @hide
18604     */
18605    public boolean resolveTextDirection() {
18606        // Reset any previous text direction resolution
18607        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18608
18609        if (hasRtlSupport()) {
18610            // Set resolved text direction flag depending on text direction flag
18611            final int textDirection = getRawTextDirection();
18612            switch(textDirection) {
18613                case TEXT_DIRECTION_INHERIT:
18614                    if (!canResolveTextDirection()) {
18615                        // We cannot do the resolution if there is no parent, so use the default one
18616                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18617                        // Resolution will need to happen again later
18618                        return false;
18619                    }
18620
18621                    // Parent has not yet resolved, so we still return the default
18622                    try {
18623                        if (!mParent.isTextDirectionResolved()) {
18624                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18625                            // Resolution will need to happen again later
18626                            return false;
18627                        }
18628                    } catch (AbstractMethodError e) {
18629                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18630                                " does not fully implement ViewParent", e);
18631                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18632                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18633                        return true;
18634                    }
18635
18636                    // Set current resolved direction to the same value as the parent's one
18637                    int parentResolvedDirection;
18638                    try {
18639                        parentResolvedDirection = mParent.getTextDirection();
18640                    } catch (AbstractMethodError e) {
18641                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18642                                " does not fully implement ViewParent", e);
18643                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18644                    }
18645                    switch (parentResolvedDirection) {
18646                        case TEXT_DIRECTION_FIRST_STRONG:
18647                        case TEXT_DIRECTION_ANY_RTL:
18648                        case TEXT_DIRECTION_LTR:
18649                        case TEXT_DIRECTION_RTL:
18650                        case TEXT_DIRECTION_LOCALE:
18651                            mPrivateFlags2 |=
18652                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18653                            break;
18654                        default:
18655                            // Default resolved direction is "first strong" heuristic
18656                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18657                    }
18658                    break;
18659                case TEXT_DIRECTION_FIRST_STRONG:
18660                case TEXT_DIRECTION_ANY_RTL:
18661                case TEXT_DIRECTION_LTR:
18662                case TEXT_DIRECTION_RTL:
18663                case TEXT_DIRECTION_LOCALE:
18664                    // Resolved direction is the same as text direction
18665                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18666                    break;
18667                default:
18668                    // Default resolved direction is "first strong" heuristic
18669                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18670            }
18671        } else {
18672            // Default resolved direction is "first strong" heuristic
18673            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18674        }
18675
18676        // Set to resolved
18677        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18678        return true;
18679    }
18680
18681    /**
18682     * Check if text direction resolution can be done.
18683     *
18684     * @return true if text direction resolution can be done otherwise return false.
18685     */
18686    public boolean canResolveTextDirection() {
18687        switch (getRawTextDirection()) {
18688            case TEXT_DIRECTION_INHERIT:
18689                if (mParent != null) {
18690                    try {
18691                        return mParent.canResolveTextDirection();
18692                    } catch (AbstractMethodError e) {
18693                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18694                                " does not fully implement ViewParent", e);
18695                    }
18696                }
18697                return false;
18698
18699            default:
18700                return true;
18701        }
18702    }
18703
18704    /**
18705     * Reset resolved text direction. Text direction will be resolved during a call to
18706     * {@link #onMeasure(int, int)}.
18707     *
18708     * @hide
18709     */
18710    public void resetResolvedTextDirection() {
18711        // Reset any previous text direction resolution
18712        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18713        // Set to default value
18714        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18715    }
18716
18717    /**
18718     * @return true if text direction is inherited.
18719     *
18720     * @hide
18721     */
18722    public boolean isTextDirectionInherited() {
18723        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18724    }
18725
18726    /**
18727     * @return true if text direction is resolved.
18728     */
18729    public boolean isTextDirectionResolved() {
18730        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18731    }
18732
18733    /**
18734     * Return the value specifying the text alignment or policy that was set with
18735     * {@link #setTextAlignment(int)}.
18736     *
18737     * @return the defined text alignment. It can be one of:
18738     *
18739     * {@link #TEXT_ALIGNMENT_INHERIT},
18740     * {@link #TEXT_ALIGNMENT_GRAVITY},
18741     * {@link #TEXT_ALIGNMENT_CENTER},
18742     * {@link #TEXT_ALIGNMENT_TEXT_START},
18743     * {@link #TEXT_ALIGNMENT_TEXT_END},
18744     * {@link #TEXT_ALIGNMENT_VIEW_START},
18745     * {@link #TEXT_ALIGNMENT_VIEW_END}
18746     *
18747     * @attr ref android.R.styleable#View_textAlignment
18748     *
18749     * @hide
18750     */
18751    @ViewDebug.ExportedProperty(category = "text", mapping = {
18752            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18753            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18754            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18755            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18756            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18757            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18758            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18759    })
18760    @TextAlignment
18761    public int getRawTextAlignment() {
18762        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18763    }
18764
18765    /**
18766     * Set the text alignment.
18767     *
18768     * @param textAlignment The text alignment to set. Should be one of
18769     *
18770     * {@link #TEXT_ALIGNMENT_INHERIT},
18771     * {@link #TEXT_ALIGNMENT_GRAVITY},
18772     * {@link #TEXT_ALIGNMENT_CENTER},
18773     * {@link #TEXT_ALIGNMENT_TEXT_START},
18774     * {@link #TEXT_ALIGNMENT_TEXT_END},
18775     * {@link #TEXT_ALIGNMENT_VIEW_START},
18776     * {@link #TEXT_ALIGNMENT_VIEW_END}
18777     *
18778     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18779     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18780     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18781     *
18782     * @attr ref android.R.styleable#View_textAlignment
18783     */
18784    public void setTextAlignment(@TextAlignment int textAlignment) {
18785        if (textAlignment != getRawTextAlignment()) {
18786            // Reset the current and resolved text alignment
18787            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18788            resetResolvedTextAlignment();
18789            // Set the new text alignment
18790            mPrivateFlags2 |=
18791                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18792            // Do resolution
18793            resolveTextAlignment();
18794            // Notify change
18795            onRtlPropertiesChanged(getLayoutDirection());
18796            // Refresh
18797            requestLayout();
18798            invalidate(true);
18799        }
18800    }
18801
18802    /**
18803     * Return the resolved text alignment.
18804     *
18805     * @return the resolved text alignment. Returns one of:
18806     *
18807     * {@link #TEXT_ALIGNMENT_GRAVITY},
18808     * {@link #TEXT_ALIGNMENT_CENTER},
18809     * {@link #TEXT_ALIGNMENT_TEXT_START},
18810     * {@link #TEXT_ALIGNMENT_TEXT_END},
18811     * {@link #TEXT_ALIGNMENT_VIEW_START},
18812     * {@link #TEXT_ALIGNMENT_VIEW_END}
18813     *
18814     * @attr ref android.R.styleable#View_textAlignment
18815     */
18816    @ViewDebug.ExportedProperty(category = "text", mapping = {
18817            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18818            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18819            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18820            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18821            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18822            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18823            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18824    })
18825    @TextAlignment
18826    public int getTextAlignment() {
18827        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18828                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18829    }
18830
18831    /**
18832     * Resolve the text alignment.
18833     *
18834     * @return true if resolution has been done, false otherwise.
18835     *
18836     * @hide
18837     */
18838    public boolean resolveTextAlignment() {
18839        // Reset any previous text alignment resolution
18840        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18841
18842        if (hasRtlSupport()) {
18843            // Set resolved text alignment flag depending on text alignment flag
18844            final int textAlignment = getRawTextAlignment();
18845            switch (textAlignment) {
18846                case TEXT_ALIGNMENT_INHERIT:
18847                    // Check if we can resolve the text alignment
18848                    if (!canResolveTextAlignment()) {
18849                        // We cannot do the resolution if there is no parent so use the default
18850                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18851                        // Resolution will need to happen again later
18852                        return false;
18853                    }
18854
18855                    // Parent has not yet resolved, so we still return the default
18856                    try {
18857                        if (!mParent.isTextAlignmentResolved()) {
18858                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18859                            // Resolution will need to happen again later
18860                            return false;
18861                        }
18862                    } catch (AbstractMethodError e) {
18863                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18864                                " does not fully implement ViewParent", e);
18865                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18866                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18867                        return true;
18868                    }
18869
18870                    int parentResolvedTextAlignment;
18871                    try {
18872                        parentResolvedTextAlignment = mParent.getTextAlignment();
18873                    } catch (AbstractMethodError e) {
18874                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18875                                " does not fully implement ViewParent", e);
18876                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18877                    }
18878                    switch (parentResolvedTextAlignment) {
18879                        case TEXT_ALIGNMENT_GRAVITY:
18880                        case TEXT_ALIGNMENT_TEXT_START:
18881                        case TEXT_ALIGNMENT_TEXT_END:
18882                        case TEXT_ALIGNMENT_CENTER:
18883                        case TEXT_ALIGNMENT_VIEW_START:
18884                        case TEXT_ALIGNMENT_VIEW_END:
18885                            // Resolved text alignment is the same as the parent resolved
18886                            // text alignment
18887                            mPrivateFlags2 |=
18888                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18889                            break;
18890                        default:
18891                            // Use default resolved text alignment
18892                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18893                    }
18894                    break;
18895                case TEXT_ALIGNMENT_GRAVITY:
18896                case TEXT_ALIGNMENT_TEXT_START:
18897                case TEXT_ALIGNMENT_TEXT_END:
18898                case TEXT_ALIGNMENT_CENTER:
18899                case TEXT_ALIGNMENT_VIEW_START:
18900                case TEXT_ALIGNMENT_VIEW_END:
18901                    // Resolved text alignment is the same as text alignment
18902                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18903                    break;
18904                default:
18905                    // Use default resolved text alignment
18906                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18907            }
18908        } else {
18909            // Use default resolved text alignment
18910            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18911        }
18912
18913        // Set the resolved
18914        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18915        return true;
18916    }
18917
18918    /**
18919     * Check if text alignment resolution can be done.
18920     *
18921     * @return true if text alignment resolution can be done otherwise return false.
18922     */
18923    public boolean canResolveTextAlignment() {
18924        switch (getRawTextAlignment()) {
18925            case TEXT_DIRECTION_INHERIT:
18926                if (mParent != null) {
18927                    try {
18928                        return mParent.canResolveTextAlignment();
18929                    } catch (AbstractMethodError e) {
18930                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18931                                " does not fully implement ViewParent", e);
18932                    }
18933                }
18934                return false;
18935
18936            default:
18937                return true;
18938        }
18939    }
18940
18941    /**
18942     * Reset resolved text alignment. Text alignment will be resolved during a call to
18943     * {@link #onMeasure(int, int)}.
18944     *
18945     * @hide
18946     */
18947    public void resetResolvedTextAlignment() {
18948        // Reset any previous text alignment resolution
18949        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18950        // Set to default
18951        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18952    }
18953
18954    /**
18955     * @return true if text alignment is inherited.
18956     *
18957     * @hide
18958     */
18959    public boolean isTextAlignmentInherited() {
18960        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18961    }
18962
18963    /**
18964     * @return true if text alignment is resolved.
18965     */
18966    public boolean isTextAlignmentResolved() {
18967        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18968    }
18969
18970    /**
18971     * Generate a value suitable for use in {@link #setId(int)}.
18972     * This value will not collide with ID values generated at build time by aapt for R.id.
18973     *
18974     * @return a generated ID value
18975     */
18976    public static int generateViewId() {
18977        for (;;) {
18978            final int result = sNextGeneratedId.get();
18979            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18980            int newValue = result + 1;
18981            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18982            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18983                return result;
18984            }
18985        }
18986    }
18987
18988    /**
18989     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18990     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18991     *                           a normal View or a ViewGroup with
18992     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18993     * @hide
18994     */
18995    public void captureTransitioningViews(List<View> transitioningViews) {
18996        if (getVisibility() == View.VISIBLE) {
18997            transitioningViews.add(this);
18998        }
18999    }
19000
19001    /**
19002     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19003     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19004     * @hide
19005     */
19006    public void findNamedViews(Map<String, View> namedElements) {
19007        if (getVisibility() == VISIBLE) {
19008            String transitionName = getTransitionName();
19009            if (transitionName != null) {
19010                namedElements.put(transitionName, this);
19011            }
19012        }
19013    }
19014
19015    //
19016    // Properties
19017    //
19018    /**
19019     * A Property wrapper around the <code>alpha</code> functionality handled by the
19020     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19021     */
19022    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19023        @Override
19024        public void setValue(View object, float value) {
19025            object.setAlpha(value);
19026        }
19027
19028        @Override
19029        public Float get(View object) {
19030            return object.getAlpha();
19031        }
19032    };
19033
19034    /**
19035     * A Property wrapper around the <code>translationX</code> functionality handled by the
19036     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19037     */
19038    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19039        @Override
19040        public void setValue(View object, float value) {
19041            object.setTranslationX(value);
19042        }
19043
19044                @Override
19045        public Float get(View object) {
19046            return object.getTranslationX();
19047        }
19048    };
19049
19050    /**
19051     * A Property wrapper around the <code>translationY</code> functionality handled by the
19052     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19053     */
19054    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19055        @Override
19056        public void setValue(View object, float value) {
19057            object.setTranslationY(value);
19058        }
19059
19060        @Override
19061        public Float get(View object) {
19062            return object.getTranslationY();
19063        }
19064    };
19065
19066    /**
19067     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19068     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19069     */
19070    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19071        @Override
19072        public void setValue(View object, float value) {
19073            object.setTranslationZ(value);
19074        }
19075
19076        @Override
19077        public Float get(View object) {
19078            return object.getTranslationZ();
19079        }
19080    };
19081
19082    /**
19083     * A Property wrapper around the <code>x</code> functionality handled by the
19084     * {@link View#setX(float)} and {@link View#getX()} methods.
19085     */
19086    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19087        @Override
19088        public void setValue(View object, float value) {
19089            object.setX(value);
19090        }
19091
19092        @Override
19093        public Float get(View object) {
19094            return object.getX();
19095        }
19096    };
19097
19098    /**
19099     * A Property wrapper around the <code>y</code> functionality handled by the
19100     * {@link View#setY(float)} and {@link View#getY()} methods.
19101     */
19102    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19103        @Override
19104        public void setValue(View object, float value) {
19105            object.setY(value);
19106        }
19107
19108        @Override
19109        public Float get(View object) {
19110            return object.getY();
19111        }
19112    };
19113
19114    /**
19115     * A Property wrapper around the <code>z</code> functionality handled by the
19116     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19117     */
19118    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19119        @Override
19120        public void setValue(View object, float value) {
19121            object.setZ(value);
19122        }
19123
19124        @Override
19125        public Float get(View object) {
19126            return object.getZ();
19127        }
19128    };
19129
19130    /**
19131     * A Property wrapper around the <code>rotation</code> functionality handled by the
19132     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19133     */
19134    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19135        @Override
19136        public void setValue(View object, float value) {
19137            object.setRotation(value);
19138        }
19139
19140        @Override
19141        public Float get(View object) {
19142            return object.getRotation();
19143        }
19144    };
19145
19146    /**
19147     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19148     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19149     */
19150    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19151        @Override
19152        public void setValue(View object, float value) {
19153            object.setRotationX(value);
19154        }
19155
19156        @Override
19157        public Float get(View object) {
19158            return object.getRotationX();
19159        }
19160    };
19161
19162    /**
19163     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19164     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19165     */
19166    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19167        @Override
19168        public void setValue(View object, float value) {
19169            object.setRotationY(value);
19170        }
19171
19172        @Override
19173        public Float get(View object) {
19174            return object.getRotationY();
19175        }
19176    };
19177
19178    /**
19179     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19180     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19181     */
19182    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19183        @Override
19184        public void setValue(View object, float value) {
19185            object.setScaleX(value);
19186        }
19187
19188        @Override
19189        public Float get(View object) {
19190            return object.getScaleX();
19191        }
19192    };
19193
19194    /**
19195     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19196     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19197     */
19198    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19199        @Override
19200        public void setValue(View object, float value) {
19201            object.setScaleY(value);
19202        }
19203
19204        @Override
19205        public Float get(View object) {
19206            return object.getScaleY();
19207        }
19208    };
19209
19210    /**
19211     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19212     * Each MeasureSpec represents a requirement for either the width or the height.
19213     * A MeasureSpec is comprised of a size and a mode. There are three possible
19214     * modes:
19215     * <dl>
19216     * <dt>UNSPECIFIED</dt>
19217     * <dd>
19218     * The parent has not imposed any constraint on the child. It can be whatever size
19219     * it wants.
19220     * </dd>
19221     *
19222     * <dt>EXACTLY</dt>
19223     * <dd>
19224     * The parent has determined an exact size for the child. The child is going to be
19225     * given those bounds regardless of how big it wants to be.
19226     * </dd>
19227     *
19228     * <dt>AT_MOST</dt>
19229     * <dd>
19230     * The child can be as large as it wants up to the specified size.
19231     * </dd>
19232     * </dl>
19233     *
19234     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19235     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19236     */
19237    public static class MeasureSpec {
19238        private static final int MODE_SHIFT = 30;
19239        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19240
19241        /**
19242         * Measure specification mode: The parent has not imposed any constraint
19243         * on the child. It can be whatever size it wants.
19244         */
19245        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19246
19247        /**
19248         * Measure specification mode: The parent has determined an exact size
19249         * for the child. The child is going to be given those bounds regardless
19250         * of how big it wants to be.
19251         */
19252        public static final int EXACTLY     = 1 << MODE_SHIFT;
19253
19254        /**
19255         * Measure specification mode: The child can be as large as it wants up
19256         * to the specified size.
19257         */
19258        public static final int AT_MOST     = 2 << MODE_SHIFT;
19259
19260        /**
19261         * Creates a measure specification based on the supplied size and mode.
19262         *
19263         * The mode must always be one of the following:
19264         * <ul>
19265         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19266         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19267         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19268         * </ul>
19269         *
19270         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19271         * implementation was such that the order of arguments did not matter
19272         * and overflow in either value could impact the resulting MeasureSpec.
19273         * {@link android.widget.RelativeLayout} was affected by this bug.
19274         * Apps targeting API levels greater than 17 will get the fixed, more strict
19275         * behavior.</p>
19276         *
19277         * @param size the size of the measure specification
19278         * @param mode the mode of the measure specification
19279         * @return the measure specification based on size and mode
19280         */
19281        public static int makeMeasureSpec(int size, int mode) {
19282            if (sUseBrokenMakeMeasureSpec) {
19283                return size + mode;
19284            } else {
19285                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19286            }
19287        }
19288
19289        /**
19290         * Extracts the mode from the supplied measure specification.
19291         *
19292         * @param measureSpec the measure specification to extract the mode from
19293         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19294         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19295         *         {@link android.view.View.MeasureSpec#EXACTLY}
19296         */
19297        public static int getMode(int measureSpec) {
19298            return (measureSpec & MODE_MASK);
19299        }
19300
19301        /**
19302         * Extracts the size from the supplied measure specification.
19303         *
19304         * @param measureSpec the measure specification to extract the size from
19305         * @return the size in pixels defined in the supplied measure specification
19306         */
19307        public static int getSize(int measureSpec) {
19308            return (measureSpec & ~MODE_MASK);
19309        }
19310
19311        static int adjust(int measureSpec, int delta) {
19312            final int mode = getMode(measureSpec);
19313            if (mode == UNSPECIFIED) {
19314                // No need to adjust size for UNSPECIFIED mode.
19315                return makeMeasureSpec(0, UNSPECIFIED);
19316            }
19317            int size = getSize(measureSpec) + delta;
19318            if (size < 0) {
19319                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19320                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19321                size = 0;
19322            }
19323            return makeMeasureSpec(size, mode);
19324        }
19325
19326        /**
19327         * Returns a String representation of the specified measure
19328         * specification.
19329         *
19330         * @param measureSpec the measure specification to convert to a String
19331         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19332         */
19333        public static String toString(int measureSpec) {
19334            int mode = getMode(measureSpec);
19335            int size = getSize(measureSpec);
19336
19337            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19338
19339            if (mode == UNSPECIFIED)
19340                sb.append("UNSPECIFIED ");
19341            else if (mode == EXACTLY)
19342                sb.append("EXACTLY ");
19343            else if (mode == AT_MOST)
19344                sb.append("AT_MOST ");
19345            else
19346                sb.append(mode).append(" ");
19347
19348            sb.append(size);
19349            return sb.toString();
19350        }
19351    }
19352
19353    private final class CheckForLongPress implements Runnable {
19354        private int mOriginalWindowAttachCount;
19355
19356        @Override
19357        public void run() {
19358            if (isPressed() && (mParent != null)
19359                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19360                if (performLongClick()) {
19361                    mHasPerformedLongPress = true;
19362                }
19363            }
19364        }
19365
19366        public void rememberWindowAttachCount() {
19367            mOriginalWindowAttachCount = mWindowAttachCount;
19368        }
19369    }
19370
19371    private final class CheckForTap implements Runnable {
19372        public float x;
19373        public float y;
19374
19375        @Override
19376        public void run() {
19377            mPrivateFlags &= ~PFLAG_PREPRESSED;
19378            setPressed(true, x, y);
19379            checkForLongClick(ViewConfiguration.getTapTimeout());
19380        }
19381    }
19382
19383    private final class PerformClick implements Runnable {
19384        @Override
19385        public void run() {
19386            performClick();
19387        }
19388    }
19389
19390    /** @hide */
19391    public void hackTurnOffWindowResizeAnim(boolean off) {
19392        mAttachInfo.mTurnOffWindowResizeAnim = off;
19393    }
19394
19395    /**
19396     * This method returns a ViewPropertyAnimator object, which can be used to animate
19397     * specific properties on this View.
19398     *
19399     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19400     */
19401    public ViewPropertyAnimator animate() {
19402        if (mAnimator == null) {
19403            mAnimator = new ViewPropertyAnimator(this);
19404        }
19405        return mAnimator;
19406    }
19407
19408    /**
19409     * Sets the name of the View to be used to identify Views in Transitions.
19410     * Names should be unique in the View hierarchy.
19411     *
19412     * @param transitionName The name of the View to uniquely identify it for Transitions.
19413     */
19414    public final void setTransitionName(String transitionName) {
19415        mTransitionName = transitionName;
19416    }
19417
19418    /**
19419     * Returns the name of the View to be used to identify Views in Transitions.
19420     * Names should be unique in the View hierarchy.
19421     *
19422     * <p>This returns null if the View has not been given a name.</p>
19423     *
19424     * @return The name used of the View to be used to identify Views in Transitions or null
19425     * if no name has been given.
19426     */
19427    @ViewDebug.ExportedProperty
19428    public String getTransitionName() {
19429        return mTransitionName;
19430    }
19431
19432    /**
19433     * Interface definition for a callback to be invoked when a hardware key event is
19434     * dispatched to this view. The callback will be invoked before the key event is
19435     * given to the view. This is only useful for hardware keyboards; a software input
19436     * method has no obligation to trigger this listener.
19437     */
19438    public interface OnKeyListener {
19439        /**
19440         * Called when a hardware key is dispatched to a view. This allows listeners to
19441         * get a chance to respond before the target view.
19442         * <p>Key presses in software keyboards will generally NOT trigger this method,
19443         * although some may elect to do so in some situations. Do not assume a
19444         * software input method has to be key-based; even if it is, it may use key presses
19445         * in a different way than you expect, so there is no way to reliably catch soft
19446         * input key presses.
19447         *
19448         * @param v The view the key has been dispatched to.
19449         * @param keyCode The code for the physical key that was pressed
19450         * @param event The KeyEvent object containing full information about
19451         *        the event.
19452         * @return True if the listener has consumed the event, false otherwise.
19453         */
19454        boolean onKey(View v, int keyCode, KeyEvent event);
19455    }
19456
19457    /**
19458     * Interface definition for a callback to be invoked when a touch event is
19459     * dispatched to this view. The callback will be invoked before the touch
19460     * event is given to the view.
19461     */
19462    public interface OnTouchListener {
19463        /**
19464         * Called when a touch event is dispatched to a view. This allows listeners to
19465         * get a chance to respond before the target view.
19466         *
19467         * @param v The view the touch event has been dispatched to.
19468         * @param event The MotionEvent object containing full information about
19469         *        the event.
19470         * @return True if the listener has consumed the event, false otherwise.
19471         */
19472        boolean onTouch(View v, MotionEvent event);
19473    }
19474
19475    /**
19476     * Interface definition for a callback to be invoked when a hover event is
19477     * dispatched to this view. The callback will be invoked before the hover
19478     * event is given to the view.
19479     */
19480    public interface OnHoverListener {
19481        /**
19482         * Called when a hover event is dispatched to a view. This allows listeners to
19483         * get a chance to respond before the target view.
19484         *
19485         * @param v The view the hover event has been dispatched to.
19486         * @param event The MotionEvent object containing full information about
19487         *        the event.
19488         * @return True if the listener has consumed the event, false otherwise.
19489         */
19490        boolean onHover(View v, MotionEvent event);
19491    }
19492
19493    /**
19494     * Interface definition for a callback to be invoked when a generic motion event is
19495     * dispatched to this view. The callback will be invoked before the generic motion
19496     * event is given to the view.
19497     */
19498    public interface OnGenericMotionListener {
19499        /**
19500         * Called when a generic motion event is dispatched to a view. This allows listeners to
19501         * get a chance to respond before the target view.
19502         *
19503         * @param v The view the generic motion event has been dispatched to.
19504         * @param event The MotionEvent object containing full information about
19505         *        the event.
19506         * @return True if the listener has consumed the event, false otherwise.
19507         */
19508        boolean onGenericMotion(View v, MotionEvent event);
19509    }
19510
19511    /**
19512     * Interface definition for a callback to be invoked when a view has been clicked and held.
19513     */
19514    public interface OnLongClickListener {
19515        /**
19516         * Called when a view has been clicked and held.
19517         *
19518         * @param v The view that was clicked and held.
19519         *
19520         * @return true if the callback consumed the long click, false otherwise.
19521         */
19522        boolean onLongClick(View v);
19523    }
19524
19525    /**
19526     * Interface definition for a callback to be invoked when a drag is being dispatched
19527     * to this view.  The callback will be invoked before the hosting view's own
19528     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19529     * onDrag(event) behavior, it should return 'false' from this callback.
19530     *
19531     * <div class="special reference">
19532     * <h3>Developer Guides</h3>
19533     * <p>For a guide to implementing drag and drop features, read the
19534     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19535     * </div>
19536     */
19537    public interface OnDragListener {
19538        /**
19539         * Called when a drag event is dispatched to a view. This allows listeners
19540         * to get a chance to override base View behavior.
19541         *
19542         * @param v The View that received the drag event.
19543         * @param event The {@link android.view.DragEvent} object for the drag event.
19544         * @return {@code true} if the drag event was handled successfully, or {@code false}
19545         * if the drag event was not handled. Note that {@code false} will trigger the View
19546         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19547         */
19548        boolean onDrag(View v, DragEvent event);
19549    }
19550
19551    /**
19552     * Interface definition for a callback to be invoked when the focus state of
19553     * a view changed.
19554     */
19555    public interface OnFocusChangeListener {
19556        /**
19557         * Called when the focus state of a view has changed.
19558         *
19559         * @param v The view whose state has changed.
19560         * @param hasFocus The new focus state of v.
19561         */
19562        void onFocusChange(View v, boolean hasFocus);
19563    }
19564
19565    /**
19566     * Interface definition for a callback to be invoked when a view is clicked.
19567     */
19568    public interface OnClickListener {
19569        /**
19570         * Called when a view has been clicked.
19571         *
19572         * @param v The view that was clicked.
19573         */
19574        void onClick(View v);
19575    }
19576
19577    /**
19578     * Interface definition for a callback to be invoked when the context menu
19579     * for this view is being built.
19580     */
19581    public interface OnCreateContextMenuListener {
19582        /**
19583         * Called when the context menu for this view is being built. It is not
19584         * safe to hold onto the menu after this method returns.
19585         *
19586         * @param menu The context menu that is being built
19587         * @param v The view for which the context menu is being built
19588         * @param menuInfo Extra information about the item for which the
19589         *            context menu should be shown. This information will vary
19590         *            depending on the class of v.
19591         */
19592        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19593    }
19594
19595    /**
19596     * Interface definition for a callback to be invoked when the status bar changes
19597     * visibility.  This reports <strong>global</strong> changes to the system UI
19598     * state, not what the application is requesting.
19599     *
19600     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19601     */
19602    public interface OnSystemUiVisibilityChangeListener {
19603        /**
19604         * Called when the status bar changes visibility because of a call to
19605         * {@link View#setSystemUiVisibility(int)}.
19606         *
19607         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19608         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19609         * This tells you the <strong>global</strong> state of these UI visibility
19610         * flags, not what your app is currently applying.
19611         */
19612        public void onSystemUiVisibilityChange(int visibility);
19613    }
19614
19615    /**
19616     * Interface definition for a callback to be invoked when this view is attached
19617     * or detached from its window.
19618     */
19619    public interface OnAttachStateChangeListener {
19620        /**
19621         * Called when the view is attached to a window.
19622         * @param v The view that was attached
19623         */
19624        public void onViewAttachedToWindow(View v);
19625        /**
19626         * Called when the view is detached from a window.
19627         * @param v The view that was detached
19628         */
19629        public void onViewDetachedFromWindow(View v);
19630    }
19631
19632    /**
19633     * Listener for applying window insets on a view in a custom way.
19634     *
19635     * <p>Apps may choose to implement this interface if they want to apply custom policy
19636     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19637     * is set, its
19638     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19639     * method will be called instead of the View's own
19640     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19641     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19642     * the View's normal behavior as part of its own.</p>
19643     */
19644    public interface OnApplyWindowInsetsListener {
19645        /**
19646         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19647         * on a View, this listener method will be called instead of the view's own
19648         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19649         *
19650         * @param v The view applying window insets
19651         * @param insets The insets to apply
19652         * @return The insets supplied, minus any insets that were consumed
19653         */
19654        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19655    }
19656
19657    private final class UnsetPressedState implements Runnable {
19658        @Override
19659        public void run() {
19660            setPressed(false);
19661        }
19662    }
19663
19664    /**
19665     * Base class for derived classes that want to save and restore their own
19666     * state in {@link android.view.View#onSaveInstanceState()}.
19667     */
19668    public static class BaseSavedState extends AbsSavedState {
19669        /**
19670         * Constructor used when reading from a parcel. Reads the state of the superclass.
19671         *
19672         * @param source
19673         */
19674        public BaseSavedState(Parcel source) {
19675            super(source);
19676        }
19677
19678        /**
19679         * Constructor called by derived classes when creating their SavedState objects
19680         *
19681         * @param superState The state of the superclass of this view
19682         */
19683        public BaseSavedState(Parcelable superState) {
19684            super(superState);
19685        }
19686
19687        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19688                new Parcelable.Creator<BaseSavedState>() {
19689            public BaseSavedState createFromParcel(Parcel in) {
19690                return new BaseSavedState(in);
19691            }
19692
19693            public BaseSavedState[] newArray(int size) {
19694                return new BaseSavedState[size];
19695            }
19696        };
19697    }
19698
19699    /**
19700     * A set of information given to a view when it is attached to its parent
19701     * window.
19702     */
19703    final static class AttachInfo {
19704        interface Callbacks {
19705            void playSoundEffect(int effectId);
19706            boolean performHapticFeedback(int effectId, boolean always);
19707        }
19708
19709        /**
19710         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19711         * to a Handler. This class contains the target (View) to invalidate and
19712         * the coordinates of the dirty rectangle.
19713         *
19714         * For performance purposes, this class also implements a pool of up to
19715         * POOL_LIMIT objects that get reused. This reduces memory allocations
19716         * whenever possible.
19717         */
19718        static class InvalidateInfo {
19719            private static final int POOL_LIMIT = 10;
19720
19721            private static final SynchronizedPool<InvalidateInfo> sPool =
19722                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19723
19724            View target;
19725
19726            int left;
19727            int top;
19728            int right;
19729            int bottom;
19730
19731            public static InvalidateInfo obtain() {
19732                InvalidateInfo instance = sPool.acquire();
19733                return (instance != null) ? instance : new InvalidateInfo();
19734            }
19735
19736            public void recycle() {
19737                target = null;
19738                sPool.release(this);
19739            }
19740        }
19741
19742        final IWindowSession mSession;
19743
19744        final IWindow mWindow;
19745
19746        final IBinder mWindowToken;
19747
19748        final Display mDisplay;
19749
19750        final Callbacks mRootCallbacks;
19751
19752        IWindowId mIWindowId;
19753        WindowId mWindowId;
19754
19755        /**
19756         * The top view of the hierarchy.
19757         */
19758        View mRootView;
19759
19760        IBinder mPanelParentWindowToken;
19761
19762        boolean mHardwareAccelerated;
19763        boolean mHardwareAccelerationRequested;
19764        HardwareRenderer mHardwareRenderer;
19765
19766        /**
19767         * The state of the display to which the window is attached, as reported
19768         * by {@link Display#getState()}.  Note that the display state constants
19769         * declared by {@link Display} do not exactly line up with the screen state
19770         * constants declared by {@link View} (there are more display states than
19771         * screen states).
19772         */
19773        int mDisplayState = Display.STATE_UNKNOWN;
19774
19775        /**
19776         * Scale factor used by the compatibility mode
19777         */
19778        float mApplicationScale;
19779
19780        /**
19781         * Indicates whether the application is in compatibility mode
19782         */
19783        boolean mScalingRequired;
19784
19785        /**
19786         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19787         */
19788        boolean mTurnOffWindowResizeAnim;
19789
19790        /**
19791         * Left position of this view's window
19792         */
19793        int mWindowLeft;
19794
19795        /**
19796         * Top position of this view's window
19797         */
19798        int mWindowTop;
19799
19800        /**
19801         * Indicates whether views need to use 32-bit drawing caches
19802         */
19803        boolean mUse32BitDrawingCache;
19804
19805        /**
19806         * For windows that are full-screen but using insets to layout inside
19807         * of the screen areas, these are the current insets to appear inside
19808         * the overscan area of the display.
19809         */
19810        final Rect mOverscanInsets = new Rect();
19811
19812        /**
19813         * For windows that are full-screen but using insets to layout inside
19814         * of the screen decorations, these are the current insets for the
19815         * content of the window.
19816         */
19817        final Rect mContentInsets = new Rect();
19818
19819        /**
19820         * For windows that are full-screen but using insets to layout inside
19821         * of the screen decorations, these are the current insets for the
19822         * actual visible parts of the window.
19823         */
19824        final Rect mVisibleInsets = new Rect();
19825
19826        /**
19827         * For windows that are full-screen but using insets to layout inside
19828         * of the screen decorations, these are the current insets for the
19829         * stable system windows.
19830         */
19831        final Rect mStableInsets = new Rect();
19832
19833        /**
19834         * The internal insets given by this window.  This value is
19835         * supplied by the client (through
19836         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19837         * be given to the window manager when changed to be used in laying
19838         * out windows behind it.
19839         */
19840        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19841                = new ViewTreeObserver.InternalInsetsInfo();
19842
19843        /**
19844         * Set to true when mGivenInternalInsets is non-empty.
19845         */
19846        boolean mHasNonEmptyGivenInternalInsets;
19847
19848        /**
19849         * All views in the window's hierarchy that serve as scroll containers,
19850         * used to determine if the window can be resized or must be panned
19851         * to adjust for a soft input area.
19852         */
19853        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19854
19855        final KeyEvent.DispatcherState mKeyDispatchState
19856                = new KeyEvent.DispatcherState();
19857
19858        /**
19859         * Indicates whether the view's window currently has the focus.
19860         */
19861        boolean mHasWindowFocus;
19862
19863        /**
19864         * The current visibility of the window.
19865         */
19866        int mWindowVisibility;
19867
19868        /**
19869         * Indicates the time at which drawing started to occur.
19870         */
19871        long mDrawingTime;
19872
19873        /**
19874         * Indicates whether or not ignoring the DIRTY_MASK flags.
19875         */
19876        boolean mIgnoreDirtyState;
19877
19878        /**
19879         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19880         * to avoid clearing that flag prematurely.
19881         */
19882        boolean mSetIgnoreDirtyState = false;
19883
19884        /**
19885         * Indicates whether the view's window is currently in touch mode.
19886         */
19887        boolean mInTouchMode;
19888
19889        /**
19890         * Indicates whether the view has requested unbuffered input dispatching for the current
19891         * event stream.
19892         */
19893        boolean mUnbufferedDispatchRequested;
19894
19895        /**
19896         * Indicates that ViewAncestor should trigger a global layout change
19897         * the next time it performs a traversal
19898         */
19899        boolean mRecomputeGlobalAttributes;
19900
19901        /**
19902         * Always report new attributes at next traversal.
19903         */
19904        boolean mForceReportNewAttributes;
19905
19906        /**
19907         * Set during a traveral if any views want to keep the screen on.
19908         */
19909        boolean mKeepScreenOn;
19910
19911        /**
19912         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19913         */
19914        int mSystemUiVisibility;
19915
19916        /**
19917         * Hack to force certain system UI visibility flags to be cleared.
19918         */
19919        int mDisabledSystemUiVisibility;
19920
19921        /**
19922         * Last global system UI visibility reported by the window manager.
19923         */
19924        int mGlobalSystemUiVisibility;
19925
19926        /**
19927         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19928         * attached.
19929         */
19930        boolean mHasSystemUiListeners;
19931
19932        /**
19933         * Set if the window has requested to extend into the overscan region
19934         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19935         */
19936        boolean mOverscanRequested;
19937
19938        /**
19939         * Set if the visibility of any views has changed.
19940         */
19941        boolean mViewVisibilityChanged;
19942
19943        /**
19944         * Set to true if a view has been scrolled.
19945         */
19946        boolean mViewScrollChanged;
19947
19948        /**
19949         * Set to true if high contrast mode enabled
19950         */
19951        boolean mHighContrastText;
19952
19953        /**
19954         * Global to the view hierarchy used as a temporary for dealing with
19955         * x/y points in the transparent region computations.
19956         */
19957        final int[] mTransparentLocation = new int[2];
19958
19959        /**
19960         * Global to the view hierarchy used as a temporary for dealing with
19961         * x/y points in the ViewGroup.invalidateChild implementation.
19962         */
19963        final int[] mInvalidateChildLocation = new int[2];
19964
19965        /**
19966         * Global to the view hierarchy used as a temporary for dealng with
19967         * computing absolute on-screen location.
19968         */
19969        final int[] mTmpLocation = new int[2];
19970
19971        /**
19972         * Global to the view hierarchy used as a temporary for dealing with
19973         * x/y location when view is transformed.
19974         */
19975        final float[] mTmpTransformLocation = new float[2];
19976
19977        /**
19978         * The view tree observer used to dispatch global events like
19979         * layout, pre-draw, touch mode change, etc.
19980         */
19981        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19982
19983        /**
19984         * A Canvas used by the view hierarchy to perform bitmap caching.
19985         */
19986        Canvas mCanvas;
19987
19988        /**
19989         * The view root impl.
19990         */
19991        final ViewRootImpl mViewRootImpl;
19992
19993        /**
19994         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19995         * handler can be used to pump events in the UI events queue.
19996         */
19997        final Handler mHandler;
19998
19999        /**
20000         * Temporary for use in computing invalidate rectangles while
20001         * calling up the hierarchy.
20002         */
20003        final Rect mTmpInvalRect = new Rect();
20004
20005        /**
20006         * Temporary for use in computing hit areas with transformed views
20007         */
20008        final RectF mTmpTransformRect = new RectF();
20009
20010        /**
20011         * Temporary for use in transforming invalidation rect
20012         */
20013        final Matrix mTmpMatrix = new Matrix();
20014
20015        /**
20016         * Temporary for use in transforming invalidation rect
20017         */
20018        final Transformation mTmpTransformation = new Transformation();
20019
20020        /**
20021         * Temporary for use in querying outlines from OutlineProviders
20022         */
20023        final Outline mTmpOutline = new Outline();
20024
20025        /**
20026         * Temporary list for use in collecting focusable descendents of a view.
20027         */
20028        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20029
20030        /**
20031         * The id of the window for accessibility purposes.
20032         */
20033        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20034
20035        /**
20036         * Flags related to accessibility processing.
20037         *
20038         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20039         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20040         */
20041        int mAccessibilityFetchFlags;
20042
20043        /**
20044         * The drawable for highlighting accessibility focus.
20045         */
20046        Drawable mAccessibilityFocusDrawable;
20047
20048        /**
20049         * Show where the margins, bounds and layout bounds are for each view.
20050         */
20051        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20052
20053        /**
20054         * Point used to compute visible regions.
20055         */
20056        final Point mPoint = new Point();
20057
20058        /**
20059         * Used to track which View originated a requestLayout() call, used when
20060         * requestLayout() is called during layout.
20061         */
20062        View mViewRequestingLayout;
20063
20064        /**
20065         * Creates a new set of attachment information with the specified
20066         * events handler and thread.
20067         *
20068         * @param handler the events handler the view must use
20069         */
20070        AttachInfo(IWindowSession session, IWindow window, Display display,
20071                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20072            mSession = session;
20073            mWindow = window;
20074            mWindowToken = window.asBinder();
20075            mDisplay = display;
20076            mViewRootImpl = viewRootImpl;
20077            mHandler = handler;
20078            mRootCallbacks = effectPlayer;
20079        }
20080    }
20081
20082    /**
20083     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20084     * is supported. This avoids keeping too many unused fields in most
20085     * instances of View.</p>
20086     */
20087    private static class ScrollabilityCache implements Runnable {
20088
20089        /**
20090         * Scrollbars are not visible
20091         */
20092        public static final int OFF = 0;
20093
20094        /**
20095         * Scrollbars are visible
20096         */
20097        public static final int ON = 1;
20098
20099        /**
20100         * Scrollbars are fading away
20101         */
20102        public static final int FADING = 2;
20103
20104        public boolean fadeScrollBars;
20105
20106        public int fadingEdgeLength;
20107        public int scrollBarDefaultDelayBeforeFade;
20108        public int scrollBarFadeDuration;
20109
20110        public int scrollBarSize;
20111        public ScrollBarDrawable scrollBar;
20112        public float[] interpolatorValues;
20113        public View host;
20114
20115        public final Paint paint;
20116        public final Matrix matrix;
20117        public Shader shader;
20118
20119        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20120
20121        private static final float[] OPAQUE = { 255 };
20122        private static final float[] TRANSPARENT = { 0.0f };
20123
20124        /**
20125         * When fading should start. This time moves into the future every time
20126         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20127         */
20128        public long fadeStartTime;
20129
20130
20131        /**
20132         * The current state of the scrollbars: ON, OFF, or FADING
20133         */
20134        public int state = OFF;
20135
20136        private int mLastColor;
20137
20138        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20139            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20140            scrollBarSize = configuration.getScaledScrollBarSize();
20141            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20142            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20143
20144            paint = new Paint();
20145            matrix = new Matrix();
20146            // use use a height of 1, and then wack the matrix each time we
20147            // actually use it.
20148            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20149            paint.setShader(shader);
20150            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20151
20152            this.host = host;
20153        }
20154
20155        public void setFadeColor(int color) {
20156            if (color != mLastColor) {
20157                mLastColor = color;
20158
20159                if (color != 0) {
20160                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20161                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20162                    paint.setShader(shader);
20163                    // Restore the default transfer mode (src_over)
20164                    paint.setXfermode(null);
20165                } else {
20166                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20167                    paint.setShader(shader);
20168                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20169                }
20170            }
20171        }
20172
20173        public void run() {
20174            long now = AnimationUtils.currentAnimationTimeMillis();
20175            if (now >= fadeStartTime) {
20176
20177                // the animation fades the scrollbars out by changing
20178                // the opacity (alpha) from fully opaque to fully
20179                // transparent
20180                int nextFrame = (int) now;
20181                int framesCount = 0;
20182
20183                Interpolator interpolator = scrollBarInterpolator;
20184
20185                // Start opaque
20186                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20187
20188                // End transparent
20189                nextFrame += scrollBarFadeDuration;
20190                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20191
20192                state = FADING;
20193
20194                // Kick off the fade animation
20195                host.invalidate(true);
20196            }
20197        }
20198    }
20199
20200    /**
20201     * Resuable callback for sending
20202     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20203     */
20204    private class SendViewScrolledAccessibilityEvent implements Runnable {
20205        public volatile boolean mIsPending;
20206
20207        public void run() {
20208            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20209            mIsPending = false;
20210        }
20211    }
20212
20213    /**
20214     * <p>
20215     * This class represents a delegate that can be registered in a {@link View}
20216     * to enhance accessibility support via composition rather via inheritance.
20217     * It is specifically targeted to widget developers that extend basic View
20218     * classes i.e. classes in package android.view, that would like their
20219     * applications to be backwards compatible.
20220     * </p>
20221     * <div class="special reference">
20222     * <h3>Developer Guides</h3>
20223     * <p>For more information about making applications accessible, read the
20224     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20225     * developer guide.</p>
20226     * </div>
20227     * <p>
20228     * A scenario in which a developer would like to use an accessibility delegate
20229     * is overriding a method introduced in a later API version then the minimal API
20230     * version supported by the application. For example, the method
20231     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20232     * in API version 4 when the accessibility APIs were first introduced. If a
20233     * developer would like his application to run on API version 4 devices (assuming
20234     * all other APIs used by the application are version 4 or lower) and take advantage
20235     * of this method, instead of overriding the method which would break the application's
20236     * backwards compatibility, he can override the corresponding method in this
20237     * delegate and register the delegate in the target View if the API version of
20238     * the system is high enough i.e. the API version is same or higher to the API
20239     * version that introduced
20240     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20241     * </p>
20242     * <p>
20243     * Here is an example implementation:
20244     * </p>
20245     * <code><pre><p>
20246     * if (Build.VERSION.SDK_INT >= 14) {
20247     *     // If the API version is equal of higher than the version in
20248     *     // which onInitializeAccessibilityNodeInfo was introduced we
20249     *     // register a delegate with a customized implementation.
20250     *     View view = findViewById(R.id.view_id);
20251     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20252     *         public void onInitializeAccessibilityNodeInfo(View host,
20253     *                 AccessibilityNodeInfo info) {
20254     *             // Let the default implementation populate the info.
20255     *             super.onInitializeAccessibilityNodeInfo(host, info);
20256     *             // Set some other information.
20257     *             info.setEnabled(host.isEnabled());
20258     *         }
20259     *     });
20260     * }
20261     * </code></pre></p>
20262     * <p>
20263     * This delegate contains methods that correspond to the accessibility methods
20264     * in View. If a delegate has been specified the implementation in View hands
20265     * off handling to the corresponding method in this delegate. The default
20266     * implementation the delegate methods behaves exactly as the corresponding
20267     * method in View for the case of no accessibility delegate been set. Hence,
20268     * to customize the behavior of a View method, clients can override only the
20269     * corresponding delegate method without altering the behavior of the rest
20270     * accessibility related methods of the host view.
20271     * </p>
20272     */
20273    public static class AccessibilityDelegate {
20274
20275        /**
20276         * Sends an accessibility event of the given type. If accessibility is not
20277         * enabled this method has no effect.
20278         * <p>
20279         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20280         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20281         * been set.
20282         * </p>
20283         *
20284         * @param host The View hosting the delegate.
20285         * @param eventType The type of the event to send.
20286         *
20287         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20288         */
20289        public void sendAccessibilityEvent(View host, int eventType) {
20290            host.sendAccessibilityEventInternal(eventType);
20291        }
20292
20293        /**
20294         * Performs the specified accessibility action on the view. For
20295         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20296         * <p>
20297         * The default implementation behaves as
20298         * {@link View#performAccessibilityAction(int, Bundle)
20299         *  View#performAccessibilityAction(int, Bundle)} for the case of
20300         *  no accessibility delegate been set.
20301         * </p>
20302         *
20303         * @param action The action to perform.
20304         * @return Whether the action was performed.
20305         *
20306         * @see View#performAccessibilityAction(int, Bundle)
20307         *      View#performAccessibilityAction(int, Bundle)
20308         */
20309        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20310            return host.performAccessibilityActionInternal(action, args);
20311        }
20312
20313        /**
20314         * Sends an accessibility event. This method behaves exactly as
20315         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20316         * empty {@link AccessibilityEvent} and does not perform a check whether
20317         * accessibility is enabled.
20318         * <p>
20319         * The default implementation behaves as
20320         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20321         *  View#sendAccessibilityEventUnchecked(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 to send.
20327         *
20328         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20329         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20330         */
20331        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20332            host.sendAccessibilityEventUncheckedInternal(event);
20333        }
20334
20335        /**
20336         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20337         * to its children for adding their text content to the event.
20338         * <p>
20339         * The default implementation behaves as
20340         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20341         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20342         * the case of no accessibility delegate been set.
20343         * </p>
20344         *
20345         * @param host The View hosting the delegate.
20346         * @param event The event.
20347         * @return True if the event population was completed.
20348         *
20349         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20350         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20351         */
20352        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20353            return host.dispatchPopulateAccessibilityEventInternal(event);
20354        }
20355
20356        /**
20357         * Gives a chance to the host View to populate the accessibility event with its
20358         * text content.
20359         * <p>
20360         * The default implementation behaves as
20361         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20362         *  View#onPopulateAccessibilityEvent(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 accessibility event which to populate.
20368         *
20369         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20370         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20371         */
20372        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20373            host.onPopulateAccessibilityEventInternal(event);
20374        }
20375
20376        /**
20377         * Initializes an {@link AccessibilityEvent} with information about the
20378         * the host View which is the event source.
20379         * <p>
20380         * The default implementation behaves as
20381         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20382         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20383         * the case of no accessibility delegate been set.
20384         * </p>
20385         *
20386         * @param host The View hosting the delegate.
20387         * @param event The event to initialize.
20388         *
20389         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20390         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20391         */
20392        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20393            host.onInitializeAccessibilityEventInternal(event);
20394        }
20395
20396        /**
20397         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20398         * <p>
20399         * The default implementation behaves as
20400         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20401         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20402         * the case of no accessibility delegate been set.
20403         * </p>
20404         *
20405         * @param host The View hosting the delegate.
20406         * @param info The instance to initialize.
20407         *
20408         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20409         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20410         */
20411        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20412            host.onInitializeAccessibilityNodeInfoInternal(info);
20413        }
20414
20415        /**
20416         * Called when a child of the host View has requested sending an
20417         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20418         * to augment the event.
20419         * <p>
20420         * The default implementation behaves as
20421         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20422         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20423         * the case of no accessibility delegate been set.
20424         * </p>
20425         *
20426         * @param host The View hosting the delegate.
20427         * @param child The child which requests sending the event.
20428         * @param event The event to be sent.
20429         * @return True if the event should be sent
20430         *
20431         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20432         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20433         */
20434        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20435                AccessibilityEvent event) {
20436            return host.onRequestSendAccessibilityEventInternal(child, event);
20437        }
20438
20439        /**
20440         * Gets the provider for managing a virtual view hierarchy rooted at this View
20441         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20442         * that explore the window content.
20443         * <p>
20444         * The default implementation behaves as
20445         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20446         * the case of no accessibility delegate been set.
20447         * </p>
20448         *
20449         * @return The provider.
20450         *
20451         * @see AccessibilityNodeProvider
20452         */
20453        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20454            return null;
20455        }
20456
20457        /**
20458         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20459         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20460         * This method is responsible for obtaining an accessibility node info from a
20461         * pool of reusable instances and calling
20462         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20463         * view to initialize the former.
20464         * <p>
20465         * <strong>Note:</strong> The client is responsible for recycling the obtained
20466         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20467         * creation.
20468         * </p>
20469         * <p>
20470         * The default implementation behaves as
20471         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20472         * the case of no accessibility delegate been set.
20473         * </p>
20474         * @return A populated {@link AccessibilityNodeInfo}.
20475         *
20476         * @see AccessibilityNodeInfo
20477         *
20478         * @hide
20479         */
20480        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20481            return host.createAccessibilityNodeInfoInternal();
20482        }
20483    }
20484
20485    private class MatchIdPredicate implements Predicate<View> {
20486        public int mId;
20487
20488        @Override
20489        public boolean apply(View view) {
20490            return (view.mID == mId);
20491        }
20492    }
20493
20494    private class MatchLabelForPredicate implements Predicate<View> {
20495        private int mLabeledId;
20496
20497        @Override
20498        public boolean apply(View view) {
20499            return (view.mLabelForId == mLabeledId);
20500        }
20501    }
20502
20503    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20504        private int mChangeTypes = 0;
20505        private boolean mPosted;
20506        private boolean mPostedWithDelay;
20507        private long mLastEventTimeMillis;
20508
20509        @Override
20510        public void run() {
20511            mPosted = false;
20512            mPostedWithDelay = false;
20513            mLastEventTimeMillis = SystemClock.uptimeMillis();
20514            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20515                final AccessibilityEvent event = AccessibilityEvent.obtain();
20516                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20517                event.setContentChangeTypes(mChangeTypes);
20518                sendAccessibilityEventUnchecked(event);
20519            }
20520            mChangeTypes = 0;
20521        }
20522
20523        public void runOrPost(int changeType) {
20524            mChangeTypes |= changeType;
20525
20526            // If this is a live region or the child of a live region, collect
20527            // all events from this frame and send them on the next frame.
20528            if (inLiveRegion()) {
20529                // If we're already posted with a delay, remove that.
20530                if (mPostedWithDelay) {
20531                    removeCallbacks(this);
20532                    mPostedWithDelay = false;
20533                }
20534                // Only post if we're not already posted.
20535                if (!mPosted) {
20536                    post(this);
20537                    mPosted = true;
20538                }
20539                return;
20540            }
20541
20542            if (mPosted) {
20543                return;
20544            }
20545            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20546            final long minEventIntevalMillis =
20547                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20548            if (timeSinceLastMillis >= minEventIntevalMillis) {
20549                removeCallbacks(this);
20550                run();
20551            } else {
20552                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20553                mPosted = true;
20554                mPostedWithDelay = true;
20555            }
20556        }
20557    }
20558
20559    private boolean inLiveRegion() {
20560        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20561            return true;
20562        }
20563
20564        ViewParent parent = getParent();
20565        while (parent instanceof View) {
20566            if (((View) parent).getAccessibilityLiveRegion()
20567                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20568                return true;
20569            }
20570            parent = parent.getParent();
20571        }
20572
20573        return false;
20574    }
20575
20576    /**
20577     * Dump all private flags in readable format, useful for documentation and
20578     * sanity checking.
20579     */
20580    private static void dumpFlags() {
20581        final HashMap<String, String> found = Maps.newHashMap();
20582        try {
20583            for (Field field : View.class.getDeclaredFields()) {
20584                final int modifiers = field.getModifiers();
20585                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20586                    if (field.getType().equals(int.class)) {
20587                        final int value = field.getInt(null);
20588                        dumpFlag(found, field.getName(), value);
20589                    } else if (field.getType().equals(int[].class)) {
20590                        final int[] values = (int[]) field.get(null);
20591                        for (int i = 0; i < values.length; i++) {
20592                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20593                        }
20594                    }
20595                }
20596            }
20597        } catch (IllegalAccessException e) {
20598            throw new RuntimeException(e);
20599        }
20600
20601        final ArrayList<String> keys = Lists.newArrayList();
20602        keys.addAll(found.keySet());
20603        Collections.sort(keys);
20604        for (String key : keys) {
20605            Log.d(VIEW_LOG_TAG, found.get(key));
20606        }
20607    }
20608
20609    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20610        // Sort flags by prefix, then by bits, always keeping unique keys
20611        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20612        final int prefix = name.indexOf('_');
20613        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20614        final String output = bits + " " + name;
20615        found.put(key, output);
20616    }
20617}
20618