View.java revision b942b6f15c51c2ff48c59d8f620ee6156d00f67e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.Path;
39import android.graphics.PathMeasure;
40import android.graphics.PixelFormat;
41import android.graphics.Point;
42import android.graphics.PorterDuff;
43import android.graphics.PorterDuffXfermode;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.ColorDrawable;
49import android.graphics.drawable.Drawable;
50import android.hardware.display.DisplayManagerGlobal;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.RemoteException;
57import android.os.SystemClock;
58import android.os.SystemProperties;
59import android.os.Trace;
60import android.text.TextUtils;
61import android.util.AttributeSet;
62import android.util.FloatProperty;
63import android.util.LayoutDirection;
64import android.util.Log;
65import android.util.LongSparseLongArray;
66import android.util.Pools.SynchronizedPool;
67import android.util.Property;
68import android.util.SparseArray;
69import android.util.SuperNotCalledException;
70import android.util.TypedValue;
71import android.view.ContextMenu.ContextMenuInfo;
72import android.view.AccessibilityIterators.TextSegmentIterator;
73import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
74import android.view.AccessibilityIterators.WordTextSegmentIterator;
75import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
76import android.view.accessibility.AccessibilityEvent;
77import android.view.accessibility.AccessibilityEventSource;
78import android.view.accessibility.AccessibilityManager;
79import android.view.accessibility.AccessibilityNodeInfo;
80import android.view.accessibility.AccessibilityNodeProvider;
81import android.view.animation.Animation;
82import android.view.animation.AnimationUtils;
83import android.view.animation.Transformation;
84import android.view.inputmethod.EditorInfo;
85import android.view.inputmethod.InputConnection;
86import android.view.inputmethod.InputMethodManager;
87import android.widget.ScrollBarDrawable;
88
89import static android.os.Build.VERSION_CODES.*;
90import static java.lang.Math.max;
91
92import com.android.internal.R;
93import com.android.internal.util.Predicate;
94import com.android.internal.view.menu.MenuBuilder;
95import com.google.android.collect.Lists;
96import com.google.android.collect.Maps;
97
98import java.lang.annotation.Retention;
99import java.lang.annotation.RetentionPolicy;
100import java.lang.ref.WeakReference;
101import java.lang.reflect.Field;
102import java.lang.reflect.InvocationTargetException;
103import java.lang.reflect.Method;
104import java.lang.reflect.Modifier;
105import java.util.ArrayList;
106import java.util.Arrays;
107import java.util.Collections;
108import java.util.HashMap;
109import java.util.List;
110import java.util.Locale;
111import java.util.Map;
112import java.util.concurrent.CopyOnWriteArrayList;
113import java.util.concurrent.atomic.AtomicInteger;
114
115/**
116 * <p>
117 * This class represents the basic building block for user interface components. A View
118 * occupies a rectangular area on the screen and is responsible for drawing and
119 * event handling. View is the base class for <em>widgets</em>, which are
120 * used to create interactive UI components (buttons, text fields, etc.). The
121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
122 * are invisible containers that hold other Views (or other ViewGroups) and define
123 * their layout properties.
124 * </p>
125 *
126 * <div class="special reference">
127 * <h3>Developer Guides</h3>
128 * <p>For information about using this class to develop your application's user interface,
129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
130 * </div>
131 *
132 * <a name="Using"></a>
133 * <h3>Using Views</h3>
134 * <p>
135 * All of the views in a window are arranged in a single tree. You can add views
136 * either from code or by specifying a tree of views in one or more XML layout
137 * files. There are many specialized subclasses of views that act as controls or
138 * are capable of displaying text, images, or other content.
139 * </p>
140 * <p>
141 * Once you have created a tree of views, there are typically a few types of
142 * common operations you may wish to perform:
143 * <ul>
144 * <li><strong>Set properties:</strong> for example setting the text of a
145 * {@link android.widget.TextView}. The available properties and the methods
146 * that set them will vary among the different subclasses of views. Note that
147 * properties that are known at build time can be set in the XML layout
148 * files.</li>
149 * <li><strong>Set focus:</strong> The framework will handled moving focus in
150 * response to user input. To force focus to a specific view, call
151 * {@link #requestFocus}.</li>
152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
153 * that will be notified when something interesting happens to the view. For
154 * example, all views will let you set a listener to be notified when the view
155 * gains or loses focus. You can register such a listener using
156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
157 * Other view subclasses offer more specialized listeners. For example, a Button
158 * exposes a listener to notify clients when the button is clicked.</li>
159 * <li><strong>Set visibility:</strong> You can hide or show views using
160 * {@link #setVisibility(int)}.</li>
161 * </ul>
162 * </p>
163 * <p><em>
164 * Note: The Android framework is responsible for measuring, laying out and
165 * drawing views. You should not call methods that perform these actions on
166 * views yourself unless you are actually implementing a
167 * {@link android.view.ViewGroup}.
168 * </em></p>
169 *
170 * <a name="Lifecycle"></a>
171 * <h3>Implementing a Custom View</h3>
172 *
173 * <p>
174 * To implement a custom view, you will usually begin by providing overrides for
175 * some of the standard methods that the framework calls on all views. You do
176 * not need to override all of these methods. In fact, you can start by just
177 * overriding {@link #onDraw(android.graphics.Canvas)}.
178 * <table border="2" width="85%" align="center" cellpadding="5">
179 *     <thead>
180 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
181 *     </thead>
182 *
183 *     <tbody>
184 *     <tr>
185 *         <td rowspan="2">Creation</td>
186 *         <td>Constructors</td>
187 *         <td>There is a form of the constructor that are called when the view
188 *         is created from code and a form that is called when the view is
189 *         inflated from a layout file. The second form should parse and apply
190 *         any attributes defined in the layout file.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onFinishInflate()}</code></td>
195 *         <td>Called after a view and all of its children has been inflated
196 *         from XML.</td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td rowspan="3">Layout</td>
201 *         <td><code>{@link #onMeasure(int, int)}</code></td>
202 *         <td>Called to determine the size requirements for this view and all
203 *         of its children.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
208 *         <td>Called when this view should assign a size and position to all
209 *         of its children.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
214 *         <td>Called when the size of this view has changed.
215 *         </td>
216 *     </tr>
217 *
218 *     <tr>
219 *         <td>Drawing</td>
220 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
221 *         <td>Called when the view should render its content.
222 *         </td>
223 *     </tr>
224 *
225 *     <tr>
226 *         <td rowspan="4">Event processing</td>
227 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
228 *         <td>Called when a new hardware key event occurs.
229 *         </td>
230 *     </tr>
231 *     <tr>
232 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
233 *         <td>Called when a hardware key up event occurs.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
238 *         <td>Called when a trackball motion event occurs.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
243 *         <td>Called when a touch screen motion event occurs.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="2">Focus</td>
249 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
250 *         <td>Called when the view gains or loses focus.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
256 *         <td>Called when the window containing the view gains or loses focus.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td rowspan="3">Attaching</td>
262 *         <td><code>{@link #onAttachedToWindow()}</code></td>
263 *         <td>Called when the view is attached to a window.
264 *         </td>
265 *     </tr>
266 *
267 *     <tr>
268 *         <td><code>{@link #onDetachedFromWindow}</code></td>
269 *         <td>Called when the view is detached from its window.
270 *         </td>
271 *     </tr>
272 *
273 *     <tr>
274 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
275 *         <td>Called when the visibility of the window containing the view
276 *         has changed.
277 *         </td>
278 *     </tr>
279 *     </tbody>
280 *
281 * </table>
282 * </p>
283 *
284 * <a name="IDs"></a>
285 * <h3>IDs</h3>
286 * Views may have an integer id associated with them. These ids are typically
287 * assigned in the layout XML files, and are used to find specific views within
288 * the view tree. A common pattern is to:
289 * <ul>
290 * <li>Define a Button in the layout file and assign it a unique ID.
291 * <pre>
292 * &lt;Button
293 *     android:id="@+id/my_button"
294 *     android:layout_width="wrap_content"
295 *     android:layout_height="wrap_content"
296 *     android:text="@string/my_button_text"/&gt;
297 * </pre></li>
298 * <li>From the onCreate method of an Activity, find the Button
299 * <pre class="prettyprint">
300 *      Button myButton = (Button) findViewById(R.id.my_button);
301 * </pre></li>
302 * </ul>
303 * <p>
304 * View IDs need not be unique throughout the tree, but it is good practice to
305 * ensure that they are at least unique within the part of the tree you are
306 * searching.
307 * </p>
308 *
309 * <a name="Position"></a>
310 * <h3>Position</h3>
311 * <p>
312 * The geometry of a view is that of a rectangle. A view has a location,
313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
314 * two dimensions, expressed as a width and a height. The unit for location
315 * and dimensions is the pixel.
316 * </p>
317 *
318 * <p>
319 * It is possible to retrieve the location of a view by invoking the methods
320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
321 * coordinate of the rectangle representing the view. The latter returns the
322 * top, or Y, coordinate of the rectangle representing the view. These methods
323 * both return the location of the view relative to its parent. For instance,
324 * when getLeft() returns 20, that means the view is located 20 pixels to the
325 * right of the left edge of its direct parent.
326 * </p>
327 *
328 * <p>
329 * In addition, several convenience methods are offered to avoid unnecessary
330 * computations, namely {@link #getRight()} and {@link #getBottom()}.
331 * These methods return the coordinates of the right and bottom edges of the
332 * rectangle representing the view. For instance, calling {@link #getRight()}
333 * is similar to the following computation: <code>getLeft() + getWidth()</code>
334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
335 * </p>
336 *
337 * <a name="SizePaddingMargins"></a>
338 * <h3>Size, padding and margins</h3>
339 * <p>
340 * The size of a view is expressed with a width and a height. A view actually
341 * possess two pairs of width and height values.
342 * </p>
343 *
344 * <p>
345 * The first pair is known as <em>measured width</em> and
346 * <em>measured height</em>. These dimensions define how big a view wants to be
347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
349 * and {@link #getMeasuredHeight()}.
350 * </p>
351 *
352 * <p>
353 * The second pair is simply known as <em>width</em> and <em>height</em>, or
354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
355 * dimensions define the actual size of the view on screen, at drawing time and
356 * after layout. These values may, but do not have to, be different from the
357 * measured width and height. The width and height can be obtained by calling
358 * {@link #getWidth()} and {@link #getHeight()}.
359 * </p>
360 *
361 * <p>
362 * To measure its dimensions, a view takes into account its padding. The padding
363 * is expressed in pixels for the left, top, right and bottom parts of the view.
364 * Padding can be used to offset the content of the view by a specific amount of
365 * pixels. For instance, a left padding of 2 will push the view's content by
366 * 2 pixels to the right of the left edge. Padding can be set using the
367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
370 * {@link #getPaddingEnd()}.
371 * </p>
372 *
373 * <p>
374 * Even though a view can define a padding, it does not provide any support for
375 * margins. However, view groups provide such a support. Refer to
376 * {@link android.view.ViewGroup} and
377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
378 * </p>
379 *
380 * <a name="Layout"></a>
381 * <h3>Layout</h3>
382 * <p>
383 * Layout is a two pass process: a measure pass and a layout pass. The measuring
384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
385 * of the view tree. Each view pushes dimension specifications down the tree
386 * during the recursion. At the end of the measure pass, every view has stored
387 * its measurements. The second pass happens in
388 * {@link #layout(int,int,int,int)} and is also top-down. During
389 * this pass each parent is responsible for positioning all of its children
390 * using the sizes computed in the measure pass.
391 * </p>
392 *
393 * <p>
394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
395 * {@link #getMeasuredHeight()} values must be set, along with those for all of
396 * that view's descendants. A view's measured width and measured height values
397 * must respect the constraints imposed by the view's parents. This guarantees
398 * that at the end of the measure pass, all parents accept all of their
399 * children's measurements. A parent view may call measure() more than once on
400 * its children. For example, the parent may measure each child once with
401 * unspecified dimensions to find out how big they want to be, then call
402 * measure() on them again with actual numbers if the sum of all the children's
403 * unconstrained sizes is too big or too small.
404 * </p>
405 *
406 * <p>
407 * The measure pass uses two classes to communicate dimensions. The
408 * {@link MeasureSpec} class is used by views to tell their parents how they
409 * want to be measured and positioned. The base LayoutParams class just
410 * describes how big the view wants to be for both width and height. For each
411 * dimension, it can specify one of:
412 * <ul>
413 * <li> an exact number
414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
415 * (minus padding)
416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
417 * enclose its content (plus padding).
418 * </ul>
419 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
421 * an X and Y value.
422 * </p>
423 *
424 * <p>
425 * MeasureSpecs are used to push requirements down the tree from parent to
426 * child. A MeasureSpec can be in one of three modes:
427 * <ul>
428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
429 * of a child view. For example, a LinearLayout may call measure() on its child
430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
431 * tall the child view wants to be given a width of 240 pixels.
432 * <li>EXACTLY: This is used by the parent to impose an exact size on the
433 * child. The child must use this size, and guarantee that all of its
434 * descendants will fit within this size.
435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
436 * child. The child must guarantee that it and all of its descendants will fit
437 * within this size.
438 * </ul>
439 * </p>
440 *
441 * <p>
442 * To intiate a layout, call {@link #requestLayout}. This method is typically
443 * called by a view on itself when it believes that is can no longer fit within
444 * its current bounds.
445 * </p>
446 *
447 * <a name="Drawing"></a>
448 * <h3>Drawing</h3>
449 * <p>
450 * Drawing is handled by walking the tree and recording the drawing commands of
451 * any View that needs to update. After this, the drawing commands of the
452 * entire tree are issued to screen, clipped to the newly damaged area.
453 * </p>
454 *
455 * <p>
456 * The tree is largely recorded and drawn in order, with parents drawn before
457 * (i.e., behind) their children, with siblings drawn in the order they appear
458 * in the tree. If you set a background drawable for a View, then the View will
459 * draw it before calling back to its <code>onDraw()</code> method. The child
460 * drawing order can be overridden with
461 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
462 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
463 * </p>
464 *
465 * <p>
466 * To force a view to draw, call {@link #invalidate()}.
467 * </p>
468 *
469 * <a name="EventHandlingThreading"></a>
470 * <h3>Event Handling and Threading</h3>
471 * <p>
472 * The basic cycle of a view is as follows:
473 * <ol>
474 * <li>An event comes in and is dispatched to the appropriate view. The view
475 * handles the event and notifies any listeners.</li>
476 * <li>If in the course of processing the event, the view's bounds may need
477 * to be changed, the view will call {@link #requestLayout()}.</li>
478 * <li>Similarly, if in the course of processing the event the view's appearance
479 * may need to be changed, the view will call {@link #invalidate()}.</li>
480 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
481 * the framework will take care of measuring, laying out, and drawing the tree
482 * as appropriate.</li>
483 * </ol>
484 * </p>
485 *
486 * <p><em>Note: The entire view tree is single threaded. You must always be on
487 * the UI thread when calling any method on any view.</em>
488 * If you are doing work on other threads and want to update the state of a view
489 * from that thread, you should use a {@link Handler}.
490 * </p>
491 *
492 * <a name="FocusHandling"></a>
493 * <h3>Focus Handling</h3>
494 * <p>
495 * The framework will handle routine focus movement in response to user input.
496 * This includes changing the focus as views are removed or hidden, or as new
497 * views become available. Views indicate their willingness to take focus
498 * through the {@link #isFocusable} method. To change whether a view can take
499 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
500 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
501 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
502 * </p>
503 * <p>
504 * Focus movement is based on an algorithm which finds the nearest neighbor in a
505 * given direction. In rare cases, the default algorithm may not match the
506 * intended behavior of the developer. In these situations, you can provide
507 * explicit overrides by using these XML attributes in the layout file:
508 * <pre>
509 * nextFocusDown
510 * nextFocusLeft
511 * nextFocusRight
512 * nextFocusUp
513 * </pre>
514 * </p>
515 *
516 *
517 * <p>
518 * To get a particular view to take focus, call {@link #requestFocus()}.
519 * </p>
520 *
521 * <a name="TouchMode"></a>
522 * <h3>Touch Mode</h3>
523 * <p>
524 * When a user is navigating a user interface via directional keys such as a D-pad, it is
525 * necessary to give focus to actionable items such as buttons so the user can see
526 * what will take input.  If the device has touch capabilities, however, and the user
527 * begins interacting with the interface by touching it, it is no longer necessary to
528 * always highlight, or give focus to, a particular view.  This motivates a mode
529 * for interaction named 'touch mode'.
530 * </p>
531 * <p>
532 * For a touch capable device, once the user touches the screen, the device
533 * will enter touch mode.  From this point onward, only views for which
534 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
535 * Other views that are touchable, like buttons, will not take focus when touched; they will
536 * only fire the on click listeners.
537 * </p>
538 * <p>
539 * Any time a user hits a directional key, such as a D-pad direction, the view device will
540 * exit touch mode, and find a view to take focus, so that the user may resume interacting
541 * with the user interface without touching the screen again.
542 * </p>
543 * <p>
544 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
545 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
546 * </p>
547 *
548 * <a name="Scrolling"></a>
549 * <h3>Scrolling</h3>
550 * <p>
551 * The framework provides basic support for views that wish to internally
552 * scroll their content. This includes keeping track of the X and Y scroll
553 * offset as well as mechanisms for drawing scrollbars. See
554 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
555 * {@link #awakenScrollBars()} for more details.
556 * </p>
557 *
558 * <a name="Tags"></a>
559 * <h3>Tags</h3>
560 * <p>
561 * Unlike IDs, tags are not used to identify views. Tags are essentially an
562 * extra piece of information that can be associated with a view. They are most
563 * often used as a convenience to store data related to views in the views
564 * themselves rather than by putting them in a separate structure.
565 * </p>
566 *
567 * <a name="Properties"></a>
568 * <h3>Properties</h3>
569 * <p>
570 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
571 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
572 * available both in the {@link Property} form as well as in similarly-named setter/getter
573 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
574 * be used to set persistent state associated with these rendering-related properties on the view.
575 * The properties and methods can also be used in conjunction with
576 * {@link android.animation.Animator Animator}-based animations, described more in the
577 * <a href="#Animation">Animation</a> section.
578 * </p>
579 *
580 * <a name="Animation"></a>
581 * <h3>Animation</h3>
582 * <p>
583 * Starting with Android 3.0, the preferred way of animating views is to use the
584 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
585 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
586 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
587 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
588 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
589 * makes animating these View properties particularly easy and efficient.
590 * </p>
591 * <p>
592 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
593 * You can attach an {@link Animation} object to a view using
594 * {@link #setAnimation(Animation)} or
595 * {@link #startAnimation(Animation)}. The animation can alter the scale,
596 * rotation, translation and alpha of a view over time. If the animation is
597 * attached to a view that has children, the animation will affect the entire
598 * subtree rooted by that node. When an animation is started, the framework will
599 * take care of redrawing the appropriate views until the animation completes.
600 * </p>
601 *
602 * <a name="Security"></a>
603 * <h3>Security</h3>
604 * <p>
605 * Sometimes it is essential that an application be able to verify that an action
606 * is being performed with the full knowledge and consent of the user, such as
607 * granting a permission request, making a purchase or clicking on an advertisement.
608 * Unfortunately, a malicious application could try to spoof the user into
609 * performing these actions, unaware, by concealing the intended purpose of the view.
610 * As a remedy, the framework offers a touch filtering mechanism that can be used to
611 * improve the security of views that provide access to sensitive functionality.
612 * </p><p>
613 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
614 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
615 * will discard touches that are received whenever the view's window is obscured by
616 * another visible window.  As a result, the view will not receive touches whenever a
617 * toast, dialog or other window appears above the view's window.
618 * </p><p>
619 * For more fine-grained control over security, consider overriding the
620 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
621 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
622 * </p>
623 *
624 * @attr ref android.R.styleable#View_alpha
625 * @attr ref android.R.styleable#View_background
626 * @attr ref android.R.styleable#View_clickable
627 * @attr ref android.R.styleable#View_contentDescription
628 * @attr ref android.R.styleable#View_drawingCacheQuality
629 * @attr ref android.R.styleable#View_duplicateParentState
630 * @attr ref android.R.styleable#View_id
631 * @attr ref android.R.styleable#View_requiresFadingEdge
632 * @attr ref android.R.styleable#View_fadeScrollbars
633 * @attr ref android.R.styleable#View_fadingEdgeLength
634 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
635 * @attr ref android.R.styleable#View_fitsSystemWindows
636 * @attr ref android.R.styleable#View_isScrollContainer
637 * @attr ref android.R.styleable#View_focusable
638 * @attr ref android.R.styleable#View_focusableInTouchMode
639 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
640 * @attr ref android.R.styleable#View_keepScreenOn
641 * @attr ref android.R.styleable#View_layerType
642 * @attr ref android.R.styleable#View_layoutDirection
643 * @attr ref android.R.styleable#View_longClickable
644 * @attr ref android.R.styleable#View_minHeight
645 * @attr ref android.R.styleable#View_minWidth
646 * @attr ref android.R.styleable#View_nextFocusDown
647 * @attr ref android.R.styleable#View_nextFocusLeft
648 * @attr ref android.R.styleable#View_nextFocusRight
649 * @attr ref android.R.styleable#View_nextFocusUp
650 * @attr ref android.R.styleable#View_onClick
651 * @attr ref android.R.styleable#View_padding
652 * @attr ref android.R.styleable#View_paddingBottom
653 * @attr ref android.R.styleable#View_paddingLeft
654 * @attr ref android.R.styleable#View_paddingRight
655 * @attr ref android.R.styleable#View_paddingTop
656 * @attr ref android.R.styleable#View_paddingStart
657 * @attr ref android.R.styleable#View_paddingEnd
658 * @attr ref android.R.styleable#View_saveEnabled
659 * @attr ref android.R.styleable#View_rotation
660 * @attr ref android.R.styleable#View_rotationX
661 * @attr ref android.R.styleable#View_rotationY
662 * @attr ref android.R.styleable#View_scaleX
663 * @attr ref android.R.styleable#View_scaleY
664 * @attr ref android.R.styleable#View_scrollX
665 * @attr ref android.R.styleable#View_scrollY
666 * @attr ref android.R.styleable#View_scrollbarSize
667 * @attr ref android.R.styleable#View_scrollbarStyle
668 * @attr ref android.R.styleable#View_scrollbars
669 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
670 * @attr ref android.R.styleable#View_scrollbarFadeDuration
671 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
672 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
673 * @attr ref android.R.styleable#View_scrollbarThumbVertical
674 * @attr ref android.R.styleable#View_scrollbarTrackVertical
675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
677 * @attr ref android.R.styleable#View_stateListAnimator
678 * @attr ref android.R.styleable#View_transitionName
679 * @attr ref android.R.styleable#View_soundEffectsEnabled
680 * @attr ref android.R.styleable#View_tag
681 * @attr ref android.R.styleable#View_textAlignment
682 * @attr ref android.R.styleable#View_textDirection
683 * @attr ref android.R.styleable#View_transformPivotX
684 * @attr ref android.R.styleable#View_transformPivotY
685 * @attr ref android.R.styleable#View_translationX
686 * @attr ref android.R.styleable#View_translationY
687 * @attr ref android.R.styleable#View_translationZ
688 * @attr ref android.R.styleable#View_visibility
689 *
690 * @see android.view.ViewGroup
691 */
692public class View implements Drawable.Callback, KeyEvent.Callback,
693        AccessibilityEventSource {
694    private static final boolean DBG = false;
695
696    /**
697     * The logging tag used by this class with android.util.Log.
698     */
699    protected static final String VIEW_LOG_TAG = "View";
700
701    /**
702     * When set to true, apps will draw debugging information about their layouts.
703     *
704     * @hide
705     */
706    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
707
708    /**
709     * When set to true, this view will save its attribute data.
710     *
711     * @hide
712     */
713    public static boolean mDebugViewAttributes = false;
714
715    /**
716     * Used to mark a View that has no ID.
717     */
718    public static final int NO_ID = -1;
719
720    /**
721     * Signals that compatibility booleans have been initialized according to
722     * target SDK versions.
723     */
724    private static boolean sCompatibilityDone = false;
725
726    /**
727     * Use the old (broken) way of building MeasureSpecs.
728     */
729    private static boolean sUseBrokenMakeMeasureSpec = false;
730
731    /**
732     * Ignore any optimizations using the measure cache.
733     */
734    private static boolean sIgnoreMeasureCache = false;
735
736    /**
737     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
738     * calling setFlags.
739     */
740    private static final int NOT_FOCUSABLE = 0x00000000;
741
742    /**
743     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
744     * setFlags.
745     */
746    private static final int FOCUSABLE = 0x00000001;
747
748    /**
749     * Mask for use with setFlags indicating bits used for focus.
750     */
751    private static final int FOCUSABLE_MASK = 0x00000001;
752
753    /**
754     * This view will adjust its padding to fit sytem windows (e.g. status bar)
755     */
756    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
757
758    /** @hide */
759    @IntDef({VISIBLE, INVISIBLE, GONE})
760    @Retention(RetentionPolicy.SOURCE)
761    public @interface Visibility {}
762
763    /**
764     * This view is visible.
765     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
766     * android:visibility}.
767     */
768    public static final int VISIBLE = 0x00000000;
769
770    /**
771     * This view is invisible, but it still takes up space for layout purposes.
772     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
773     * android:visibility}.
774     */
775    public static final int INVISIBLE = 0x00000004;
776
777    /**
778     * This view is invisible, and it doesn't take any space for layout
779     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
780     * android:visibility}.
781     */
782    public static final int GONE = 0x00000008;
783
784    /**
785     * Mask for use with setFlags indicating bits used for visibility.
786     * {@hide}
787     */
788    static final int VISIBILITY_MASK = 0x0000000C;
789
790    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
791
792    /**
793     * This view is enabled. Interpretation varies by subclass.
794     * Use with ENABLED_MASK when calling setFlags.
795     * {@hide}
796     */
797    static final int ENABLED = 0x00000000;
798
799    /**
800     * This view is disabled. Interpretation varies by subclass.
801     * Use with ENABLED_MASK when calling setFlags.
802     * {@hide}
803     */
804    static final int DISABLED = 0x00000020;
805
806   /**
807    * Mask for use with setFlags indicating bits used for indicating whether
808    * this view is enabled
809    * {@hide}
810    */
811    static final int ENABLED_MASK = 0x00000020;
812
813    /**
814     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
815     * called and further optimizations will be performed. It is okay to have
816     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
817     * {@hide}
818     */
819    static final int WILL_NOT_DRAW = 0x00000080;
820
821    /**
822     * Mask for use with setFlags indicating bits used for indicating whether
823     * this view is will draw
824     * {@hide}
825     */
826    static final int DRAW_MASK = 0x00000080;
827
828    /**
829     * <p>This view doesn't show scrollbars.</p>
830     * {@hide}
831     */
832    static final int SCROLLBARS_NONE = 0x00000000;
833
834    /**
835     * <p>This view shows horizontal scrollbars.</p>
836     * {@hide}
837     */
838    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
839
840    /**
841     * <p>This view shows vertical scrollbars.</p>
842     * {@hide}
843     */
844    static final int SCROLLBARS_VERTICAL = 0x00000200;
845
846    /**
847     * <p>Mask for use with setFlags indicating bits used for indicating which
848     * scrollbars are enabled.</p>
849     * {@hide}
850     */
851    static final int SCROLLBARS_MASK = 0x00000300;
852
853    /**
854     * Indicates that the view should filter touches when its window is obscured.
855     * Refer to the class comments for more information about this security feature.
856     * {@hide}
857     */
858    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
859
860    /**
861     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
862     * that they are optional and should be skipped if the window has
863     * requested system UI flags that ignore those insets for layout.
864     */
865    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
866
867    /**
868     * <p>This view doesn't show fading edges.</p>
869     * {@hide}
870     */
871    static final int FADING_EDGE_NONE = 0x00000000;
872
873    /**
874     * <p>This view shows horizontal fading edges.</p>
875     * {@hide}
876     */
877    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
878
879    /**
880     * <p>This view shows vertical fading edges.</p>
881     * {@hide}
882     */
883    static final int FADING_EDGE_VERTICAL = 0x00002000;
884
885    /**
886     * <p>Mask for use with setFlags indicating bits used for indicating which
887     * fading edges are enabled.</p>
888     * {@hide}
889     */
890    static final int FADING_EDGE_MASK = 0x00003000;
891
892    /**
893     * <p>Indicates this view can be clicked. When clickable, a View reacts
894     * to clicks by notifying the OnClickListener.<p>
895     * {@hide}
896     */
897    static final int CLICKABLE = 0x00004000;
898
899    /**
900     * <p>Indicates this view is caching its drawing into a bitmap.</p>
901     * {@hide}
902     */
903    static final int DRAWING_CACHE_ENABLED = 0x00008000;
904
905    /**
906     * <p>Indicates that no icicle should be saved for this view.<p>
907     * {@hide}
908     */
909    static final int SAVE_DISABLED = 0x000010000;
910
911    /**
912     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
913     * property.</p>
914     * {@hide}
915     */
916    static final int SAVE_DISABLED_MASK = 0x000010000;
917
918    /**
919     * <p>Indicates that no drawing cache should ever be created for this view.<p>
920     * {@hide}
921     */
922    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
923
924    /**
925     * <p>Indicates this view can take / keep focus when int touch mode.</p>
926     * {@hide}
927     */
928    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
929
930    /** @hide */
931    @Retention(RetentionPolicy.SOURCE)
932    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
933    public @interface DrawingCacheQuality {}
934
935    /**
936     * <p>Enables low quality mode for the drawing cache.</p>
937     */
938    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
939
940    /**
941     * <p>Enables high quality mode for the drawing cache.</p>
942     */
943    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
944
945    /**
946     * <p>Enables automatic quality mode for the drawing cache.</p>
947     */
948    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
949
950    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
951            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
952    };
953
954    /**
955     * <p>Mask for use with setFlags indicating bits used for the cache
956     * quality property.</p>
957     * {@hide}
958     */
959    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
960
961    /**
962     * <p>
963     * Indicates this view can be long clicked. When long clickable, a View
964     * reacts to long clicks by notifying the OnLongClickListener or showing a
965     * context menu.
966     * </p>
967     * {@hide}
968     */
969    static final int LONG_CLICKABLE = 0x00200000;
970
971    /**
972     * <p>Indicates that this view gets its drawable states from its direct parent
973     * and ignores its original internal states.</p>
974     *
975     * @hide
976     */
977    static final int DUPLICATE_PARENT_STATE = 0x00400000;
978
979    /** @hide */
980    @IntDef({
981        SCROLLBARS_INSIDE_OVERLAY,
982        SCROLLBARS_INSIDE_INSET,
983        SCROLLBARS_OUTSIDE_OVERLAY,
984        SCROLLBARS_OUTSIDE_INSET
985    })
986    @Retention(RetentionPolicy.SOURCE)
987    public @interface ScrollBarStyle {}
988
989    /**
990     * The scrollbar style to display the scrollbars inside the content area,
991     * without increasing the padding. The scrollbars will be overlaid with
992     * translucency on the view's content.
993     */
994    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
995
996    /**
997     * The scrollbar style to display the scrollbars inside the padded area,
998     * increasing the padding of the view. The scrollbars will not overlap the
999     * content area of the view.
1000     */
1001    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1002
1003    /**
1004     * The scrollbar style to display the scrollbars at the edge of the view,
1005     * without increasing the padding. The scrollbars will be overlaid with
1006     * translucency.
1007     */
1008    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1009
1010    /**
1011     * The scrollbar style to display the scrollbars at the edge of the view,
1012     * increasing the padding of the view. The scrollbars will only overlap the
1013     * background, if any.
1014     */
1015    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1016
1017    /**
1018     * Mask to check if the scrollbar style is overlay or inset.
1019     * {@hide}
1020     */
1021    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1022
1023    /**
1024     * Mask to check if the scrollbar style is inside or outside.
1025     * {@hide}
1026     */
1027    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1028
1029    /**
1030     * Mask for scrollbar style.
1031     * {@hide}
1032     */
1033    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1034
1035    /**
1036     * View flag indicating that the screen should remain on while the
1037     * window containing this view is visible to the user.  This effectively
1038     * takes care of automatically setting the WindowManager's
1039     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1040     */
1041    public static final int KEEP_SCREEN_ON = 0x04000000;
1042
1043    /**
1044     * View flag indicating whether this view should have sound effects enabled
1045     * for events such as clicking and touching.
1046     */
1047    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1048
1049    /**
1050     * View flag indicating whether this view should have haptic feedback
1051     * enabled for events such as long presses.
1052     */
1053    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1054
1055    /**
1056     * <p>Indicates that the view hierarchy should stop saving state when
1057     * it reaches this view.  If state saving is initiated immediately at
1058     * the view, it will be allowed.
1059     * {@hide}
1060     */
1061    static final int PARENT_SAVE_DISABLED = 0x20000000;
1062
1063    /**
1064     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1065     * {@hide}
1066     */
1067    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1068
1069    /** @hide */
1070    @IntDef(flag = true,
1071            value = {
1072                FOCUSABLES_ALL,
1073                FOCUSABLES_TOUCH_MODE
1074            })
1075    @Retention(RetentionPolicy.SOURCE)
1076    public @interface FocusableMode {}
1077
1078    /**
1079     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1080     * should add all focusable Views regardless if they are focusable in touch mode.
1081     */
1082    public static final int FOCUSABLES_ALL = 0x00000000;
1083
1084    /**
1085     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1086     * should add only Views focusable in touch mode.
1087     */
1088    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1089
1090    /** @hide */
1091    @IntDef({
1092            FOCUS_BACKWARD,
1093            FOCUS_FORWARD,
1094            FOCUS_LEFT,
1095            FOCUS_UP,
1096            FOCUS_RIGHT,
1097            FOCUS_DOWN
1098    })
1099    @Retention(RetentionPolicy.SOURCE)
1100    public @interface FocusDirection {}
1101
1102    /** @hide */
1103    @IntDef({
1104            FOCUS_LEFT,
1105            FOCUS_UP,
1106            FOCUS_RIGHT,
1107            FOCUS_DOWN
1108    })
1109    @Retention(RetentionPolicy.SOURCE)
1110    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1114     * item.
1115     */
1116    public static final int FOCUS_BACKWARD = 0x00000001;
1117
1118    /**
1119     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1120     * item.
1121     */
1122    public static final int FOCUS_FORWARD = 0x00000002;
1123
1124    /**
1125     * Use with {@link #focusSearch(int)}. Move focus to the left.
1126     */
1127    public static final int FOCUS_LEFT = 0x00000011;
1128
1129    /**
1130     * Use with {@link #focusSearch(int)}. Move focus up.
1131     */
1132    public static final int FOCUS_UP = 0x00000021;
1133
1134    /**
1135     * Use with {@link #focusSearch(int)}. Move focus to the right.
1136     */
1137    public static final int FOCUS_RIGHT = 0x00000042;
1138
1139    /**
1140     * Use with {@link #focusSearch(int)}. Move focus down.
1141     */
1142    public static final int FOCUS_DOWN = 0x00000082;
1143
1144    /**
1145     * Bits of {@link #getMeasuredWidthAndState()} and
1146     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1147     */
1148    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1149
1150    /**
1151     * Bits of {@link #getMeasuredWidthAndState()} and
1152     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1153     */
1154    public static final int MEASURED_STATE_MASK = 0xff000000;
1155
1156    /**
1157     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1158     * for functions that combine both width and height into a single int,
1159     * such as {@link #getMeasuredState()} and the childState argument of
1160     * {@link #resolveSizeAndState(int, int, int)}.
1161     */
1162    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1163
1164    /**
1165     * Bit of {@link #getMeasuredWidthAndState()} and
1166     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1167     * is smaller that the space the view would like to have.
1168     */
1169    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1170
1171    /**
1172     * Base View state sets
1173     */
1174    // Singles
1175    /**
1176     * Indicates the view has no states set. States are used with
1177     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1178     * view depending on its state.
1179     *
1180     * @see android.graphics.drawable.Drawable
1181     * @see #getDrawableState()
1182     */
1183    protected static final int[] EMPTY_STATE_SET;
1184    /**
1185     * Indicates the view is enabled. States are used with
1186     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1187     * view depending on its state.
1188     *
1189     * @see android.graphics.drawable.Drawable
1190     * @see #getDrawableState()
1191     */
1192    protected static final int[] ENABLED_STATE_SET;
1193    /**
1194     * Indicates the view is focused. States are used with
1195     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1196     * view depending on its state.
1197     *
1198     * @see android.graphics.drawable.Drawable
1199     * @see #getDrawableState()
1200     */
1201    protected static final int[] FOCUSED_STATE_SET;
1202    /**
1203     * Indicates the view is selected. States are used with
1204     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1205     * view depending on its state.
1206     *
1207     * @see android.graphics.drawable.Drawable
1208     * @see #getDrawableState()
1209     */
1210    protected static final int[] SELECTED_STATE_SET;
1211    /**
1212     * Indicates the view is pressed. States are used with
1213     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1214     * view depending on its state.
1215     *
1216     * @see android.graphics.drawable.Drawable
1217     * @see #getDrawableState()
1218     */
1219    protected static final int[] PRESSED_STATE_SET;
1220    /**
1221     * Indicates the view's window has focus. States are used with
1222     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1223     * view depending on its state.
1224     *
1225     * @see android.graphics.drawable.Drawable
1226     * @see #getDrawableState()
1227     */
1228    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1229    // Doubles
1230    /**
1231     * Indicates the view is enabled and has the focus.
1232     *
1233     * @see #ENABLED_STATE_SET
1234     * @see #FOCUSED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1237    /**
1238     * Indicates the view is enabled and selected.
1239     *
1240     * @see #ENABLED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     */
1243    protected static final int[] ENABLED_SELECTED_STATE_SET;
1244    /**
1245     * Indicates the view is enabled and that its window has focus.
1246     *
1247     * @see #ENABLED_STATE_SET
1248     * @see #WINDOW_FOCUSED_STATE_SET
1249     */
1250    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1251    /**
1252     * Indicates the view is focused and selected.
1253     *
1254     * @see #FOCUSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     */
1257    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1258    /**
1259     * Indicates the view has the focus and that its window has the focus.
1260     *
1261     * @see #FOCUSED_STATE_SET
1262     * @see #WINDOW_FOCUSED_STATE_SET
1263     */
1264    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1265    /**
1266     * Indicates the view is selected and that its window has the focus.
1267     *
1268     * @see #SELECTED_STATE_SET
1269     * @see #WINDOW_FOCUSED_STATE_SET
1270     */
1271    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1272    // Triples
1273    /**
1274     * Indicates the view is enabled, focused and selected.
1275     *
1276     * @see #ENABLED_STATE_SET
1277     * @see #FOCUSED_STATE_SET
1278     * @see #SELECTED_STATE_SET
1279     */
1280    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1281    /**
1282     * Indicates the view is enabled, focused and its window has the focus.
1283     *
1284     * @see #ENABLED_STATE_SET
1285     * @see #FOCUSED_STATE_SET
1286     * @see #WINDOW_FOCUSED_STATE_SET
1287     */
1288    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1289    /**
1290     * Indicates the view is enabled, selected and its window has the focus.
1291     *
1292     * @see #ENABLED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     * @see #WINDOW_FOCUSED_STATE_SET
1295     */
1296    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1297    /**
1298     * Indicates the view is focused, selected and its window has the focus.
1299     *
1300     * @see #FOCUSED_STATE_SET
1301     * @see #SELECTED_STATE_SET
1302     * @see #WINDOW_FOCUSED_STATE_SET
1303     */
1304    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1305    /**
1306     * Indicates the view is enabled, focused, selected and its window
1307     * has the focus.
1308     *
1309     * @see #ENABLED_STATE_SET
1310     * @see #FOCUSED_STATE_SET
1311     * @see #SELECTED_STATE_SET
1312     * @see #WINDOW_FOCUSED_STATE_SET
1313     */
1314    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1315    /**
1316     * Indicates the view is pressed and its window has the focus.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #WINDOW_FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed and selected.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_SELECTED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, selected and its window has the focus.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #WINDOW_FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed and focused.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1344    /**
1345     * Indicates the view is pressed, focused and its window has the focus.
1346     *
1347     * @see #PRESSED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     * @see #WINDOW_FOCUSED_STATE_SET
1350     */
1351    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1352    /**
1353     * Indicates the view is pressed, focused and selected.
1354     *
1355     * @see #PRESSED_STATE_SET
1356     * @see #SELECTED_STATE_SET
1357     * @see #FOCUSED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, focused, selected and its window has the focus.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #FOCUSED_STATE_SET
1365     * @see #SELECTED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed and enabled.
1371     *
1372     * @see #PRESSED_STATE_SET
1373     * @see #ENABLED_STATE_SET
1374     */
1375    protected static final int[] PRESSED_ENABLED_STATE_SET;
1376    /**
1377     * Indicates the view is pressed, enabled and its window has the focus.
1378     *
1379     * @see #PRESSED_STATE_SET
1380     * @see #ENABLED_STATE_SET
1381     * @see #WINDOW_FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1384    /**
1385     * Indicates the view is pressed, enabled and selected.
1386     *
1387     * @see #PRESSED_STATE_SET
1388     * @see #ENABLED_STATE_SET
1389     * @see #SELECTED_STATE_SET
1390     */
1391    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1392    /**
1393     * Indicates the view is pressed, enabled, selected and its window has the
1394     * focus.
1395     *
1396     * @see #PRESSED_STATE_SET
1397     * @see #ENABLED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is pressed, enabled and focused.
1404     *
1405     * @see #PRESSED_STATE_SET
1406     * @see #ENABLED_STATE_SET
1407     * @see #FOCUSED_STATE_SET
1408     */
1409    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1410    /**
1411     * Indicates the view is pressed, enabled, focused and its window has the
1412     * focus.
1413     *
1414     * @see #PRESSED_STATE_SET
1415     * @see #ENABLED_STATE_SET
1416     * @see #FOCUSED_STATE_SET
1417     * @see #WINDOW_FOCUSED_STATE_SET
1418     */
1419    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1420    /**
1421     * Indicates the view is pressed, enabled, focused and selected.
1422     *
1423     * @see #PRESSED_STATE_SET
1424     * @see #ENABLED_STATE_SET
1425     * @see #SELECTED_STATE_SET
1426     * @see #FOCUSED_STATE_SET
1427     */
1428    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1429    /**
1430     * Indicates the view is pressed, enabled, focused, selected and its window
1431     * has the focus.
1432     *
1433     * @see #PRESSED_STATE_SET
1434     * @see #ENABLED_STATE_SET
1435     * @see #SELECTED_STATE_SET
1436     * @see #FOCUSED_STATE_SET
1437     * @see #WINDOW_FOCUSED_STATE_SET
1438     */
1439    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1440
1441    /**
1442     * The order here is very important to {@link #getDrawableState()}
1443     */
1444    private static final int[][] VIEW_STATE_SETS;
1445
1446    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1447    static final int VIEW_STATE_SELECTED = 1 << 1;
1448    static final int VIEW_STATE_FOCUSED = 1 << 2;
1449    static final int VIEW_STATE_ENABLED = 1 << 3;
1450    static final int VIEW_STATE_PRESSED = 1 << 4;
1451    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1452    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1453    static final int VIEW_STATE_HOVERED = 1 << 7;
1454    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1455    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1456
1457    static final int[] VIEW_STATE_IDS = new int[] {
1458        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1459        R.attr.state_selected,          VIEW_STATE_SELECTED,
1460        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1461        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1462        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1463        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1464        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1465        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1466        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1467        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1468    };
1469
1470    static {
1471        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1472            throw new IllegalStateException(
1473                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1474        }
1475        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1476        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1477            int viewState = R.styleable.ViewDrawableStates[i];
1478            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1479                if (VIEW_STATE_IDS[j] == viewState) {
1480                    orderedIds[i * 2] = viewState;
1481                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1482                }
1483            }
1484        }
1485        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1486        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1487        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1488            int numBits = Integer.bitCount(i);
1489            int[] set = new int[numBits];
1490            int pos = 0;
1491            for (int j = 0; j < orderedIds.length; j += 2) {
1492                if ((i & orderedIds[j+1]) != 0) {
1493                    set[pos++] = orderedIds[j];
1494                }
1495            }
1496            VIEW_STATE_SETS[i] = set;
1497        }
1498
1499        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1500        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1501        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1502        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1504        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1505        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1507        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1509        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1511                | VIEW_STATE_FOCUSED];
1512        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1513        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1515        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1517        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1518                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1519                | VIEW_STATE_ENABLED];
1520        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1521                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1522        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1523                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1524                | VIEW_STATE_ENABLED];
1525        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1527                | VIEW_STATE_ENABLED];
1528        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1530                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1531
1532        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1533        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1535        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1537        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1538                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1539                | VIEW_STATE_PRESSED];
1540        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1541                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1542        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1543                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1544                | VIEW_STATE_PRESSED];
1545        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1546                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1547                | VIEW_STATE_PRESSED];
1548        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1549                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1550                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1551        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1552                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1555                | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1558                | VIEW_STATE_PRESSED];
1559        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1560                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1561                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1562        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1563                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1564                | VIEW_STATE_PRESSED];
1565        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1566                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1567                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1568        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1569                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1570                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1571        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1572                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1573                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1574                | VIEW_STATE_PRESSED];
1575    }
1576
1577    /**
1578     * Accessibility event types that are dispatched for text population.
1579     */
1580    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1581            AccessibilityEvent.TYPE_VIEW_CLICKED
1582            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1583            | AccessibilityEvent.TYPE_VIEW_SELECTED
1584            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1585            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1586            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1587            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1588            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1589            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1590            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1591            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1592
1593    /**
1594     * Temporary Rect currently for use in setBackground().  This will probably
1595     * be extended in the future to hold our own class with more than just
1596     * a Rect. :)
1597     */
1598    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1599
1600    /**
1601     * Map used to store views' tags.
1602     */
1603    private SparseArray<Object> mKeyedTags;
1604
1605    /**
1606     * The next available accessibility id.
1607     */
1608    private static int sNextAccessibilityViewId;
1609
1610    /**
1611     * The animation currently associated with this view.
1612     * @hide
1613     */
1614    protected Animation mCurrentAnimation = null;
1615
1616    /**
1617     * Width as measured during measure pass.
1618     * {@hide}
1619     */
1620    @ViewDebug.ExportedProperty(category = "measurement")
1621    int mMeasuredWidth;
1622
1623    /**
1624     * Height as measured during measure pass.
1625     * {@hide}
1626     */
1627    @ViewDebug.ExportedProperty(category = "measurement")
1628    int mMeasuredHeight;
1629
1630    /**
1631     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1632     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1633     * its display list. This flag, used only when hw accelerated, allows us to clear the
1634     * flag while retaining this information until it's needed (at getDisplayList() time and
1635     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1636     *
1637     * {@hide}
1638     */
1639    boolean mRecreateDisplayList = false;
1640
1641    /**
1642     * The view's identifier.
1643     * {@hide}
1644     *
1645     * @see #setId(int)
1646     * @see #getId()
1647     */
1648    @ViewDebug.ExportedProperty(resolveId = true)
1649    int mID = NO_ID;
1650
1651    /**
1652     * The stable ID of this view for accessibility purposes.
1653     */
1654    int mAccessibilityViewId = NO_ID;
1655
1656    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1657
1658    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1659
1660    /**
1661     * The view's tag.
1662     * {@hide}
1663     *
1664     * @see #setTag(Object)
1665     * @see #getTag()
1666     */
1667    protected Object mTag = null;
1668
1669    // for mPrivateFlags:
1670    /** {@hide} */
1671    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1672    /** {@hide} */
1673    static final int PFLAG_FOCUSED                     = 0x00000002;
1674    /** {@hide} */
1675    static final int PFLAG_SELECTED                    = 0x00000004;
1676    /** {@hide} */
1677    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1678    /** {@hide} */
1679    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1680    /** {@hide} */
1681    static final int PFLAG_DRAWN                       = 0x00000020;
1682    /**
1683     * When this flag is set, this view is running an animation on behalf of its
1684     * children and should therefore not cancel invalidate requests, even if they
1685     * lie outside of this view's bounds.
1686     *
1687     * {@hide}
1688     */
1689    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1690    /** {@hide} */
1691    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1692    /** {@hide} */
1693    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1694    /** {@hide} */
1695    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1696    /** {@hide} */
1697    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1698    /** {@hide} */
1699    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1700    /** {@hide} */
1701    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1702    /** {@hide} */
1703    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1704
1705    private static final int PFLAG_PRESSED             = 0x00004000;
1706
1707    /** {@hide} */
1708    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1709    /**
1710     * Flag used to indicate that this view should be drawn once more (and only once
1711     * more) after its animation has completed.
1712     * {@hide}
1713     */
1714    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1715
1716    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1717
1718    /**
1719     * Indicates that the View returned true when onSetAlpha() was called and that
1720     * the alpha must be restored.
1721     * {@hide}
1722     */
1723    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1724
1725    /**
1726     * Set by {@link #setScrollContainer(boolean)}.
1727     */
1728    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1729
1730    /**
1731     * Set by {@link #setScrollContainer(boolean)}.
1732     */
1733    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1734
1735    /**
1736     * View flag indicating whether this view was invalidated (fully or partially.)
1737     *
1738     * @hide
1739     */
1740    static final int PFLAG_DIRTY                       = 0x00200000;
1741
1742    /**
1743     * View flag indicating whether this view was invalidated by an opaque
1744     * invalidate request.
1745     *
1746     * @hide
1747     */
1748    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1749
1750    /**
1751     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1752     *
1753     * @hide
1754     */
1755    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1756
1757    /**
1758     * Indicates whether the background is opaque.
1759     *
1760     * @hide
1761     */
1762    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1763
1764    /**
1765     * Indicates whether the scrollbars are opaque.
1766     *
1767     * @hide
1768     */
1769    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1770
1771    /**
1772     * Indicates whether the view is opaque.
1773     *
1774     * @hide
1775     */
1776    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1777
1778    /**
1779     * Indicates a prepressed state;
1780     * the short time between ACTION_DOWN and recognizing
1781     * a 'real' press. Prepressed is used to recognize quick taps
1782     * even when they are shorter than ViewConfiguration.getTapTimeout().
1783     *
1784     * @hide
1785     */
1786    private static final int PFLAG_PREPRESSED          = 0x02000000;
1787
1788    /**
1789     * Indicates whether the view is temporarily detached.
1790     *
1791     * @hide
1792     */
1793    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1794
1795    /**
1796     * Indicates that we should awaken scroll bars once attached
1797     *
1798     * @hide
1799     */
1800    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1801
1802    /**
1803     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1804     * @hide
1805     */
1806    private static final int PFLAG_HOVERED             = 0x10000000;
1807
1808    /**
1809     * no longer needed, should be reused
1810     */
1811    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1812
1813    /** {@hide} */
1814    static final int PFLAG_ACTIVATED                   = 0x40000000;
1815
1816    /**
1817     * Indicates that this view was specifically invalidated, not just dirtied because some
1818     * child view was invalidated. The flag is used to determine when we need to recreate
1819     * a view's display list (as opposed to just returning a reference to its existing
1820     * display list).
1821     *
1822     * @hide
1823     */
1824    static final int PFLAG_INVALIDATED                 = 0x80000000;
1825
1826    /**
1827     * Masks for mPrivateFlags2, as generated by dumpFlags():
1828     *
1829     * |-------|-------|-------|-------|
1830     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1831     *                                1  PFLAG2_DRAG_HOVERED
1832     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1833     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1834     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1835     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1836     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1837     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1838     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1839     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1840     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1841     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1842     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1843     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1844     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1845     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1846     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1847     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1848     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1849     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1850     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1851     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1852     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1853     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1854     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1855     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1856     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1857     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1858     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1859     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1860     *    1                              PFLAG2_PADDING_RESOLVED
1861     *   1                               PFLAG2_DRAWABLE_RESOLVED
1862     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1863     * |-------|-------|-------|-------|
1864     */
1865
1866    /**
1867     * Indicates that this view has reported that it can accept the current drag's content.
1868     * Cleared when the drag operation concludes.
1869     * @hide
1870     */
1871    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1872
1873    /**
1874     * Indicates that this view is currently directly under the drag location in a
1875     * drag-and-drop operation involving content that it can accept.  Cleared when
1876     * the drag exits the view, or when the drag operation concludes.
1877     * @hide
1878     */
1879    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1880
1881    /** @hide */
1882    @IntDef({
1883        LAYOUT_DIRECTION_LTR,
1884        LAYOUT_DIRECTION_RTL,
1885        LAYOUT_DIRECTION_INHERIT,
1886        LAYOUT_DIRECTION_LOCALE
1887    })
1888    @Retention(RetentionPolicy.SOURCE)
1889    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1890    public @interface LayoutDir {}
1891
1892    /** @hide */
1893    @IntDef({
1894        LAYOUT_DIRECTION_LTR,
1895        LAYOUT_DIRECTION_RTL
1896    })
1897    @Retention(RetentionPolicy.SOURCE)
1898    public @interface ResolvedLayoutDir {}
1899
1900    /**
1901     * Horizontal layout direction of this view is from Left to Right.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1905
1906    /**
1907     * Horizontal layout direction of this view is from Right to Left.
1908     * Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1911
1912    /**
1913     * Horizontal layout direction of this view is inherited from its parent.
1914     * Use with {@link #setLayoutDirection}.
1915     */
1916    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1917
1918    /**
1919     * Horizontal layout direction of this view is from deduced from the default language
1920     * script for the locale. Use with {@link #setLayoutDirection}.
1921     */
1922    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1923
1924    /**
1925     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1926     * @hide
1927     */
1928    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1929
1930    /**
1931     * Mask for use with private flags indicating bits used for horizontal layout direction.
1932     * @hide
1933     */
1934    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1935
1936    /**
1937     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1938     * right-to-left direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1942
1943    /**
1944     * Indicates whether the view horizontal layout direction has been resolved.
1945     * @hide
1946     */
1947    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1948
1949    /**
1950     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1951     * @hide
1952     */
1953    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1954            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1955
1956    /*
1957     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1958     * flag value.
1959     * @hide
1960     */
1961    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1962            LAYOUT_DIRECTION_LTR,
1963            LAYOUT_DIRECTION_RTL,
1964            LAYOUT_DIRECTION_INHERIT,
1965            LAYOUT_DIRECTION_LOCALE
1966    };
1967
1968    /**
1969     * Default horizontal layout direction.
1970     */
1971    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1972
1973    /**
1974     * Default horizontal layout direction.
1975     * @hide
1976     */
1977    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1978
1979    /**
1980     * Text direction is inherited thru {@link ViewGroup}
1981     */
1982    public static final int TEXT_DIRECTION_INHERIT = 0;
1983
1984    /**
1985     * Text direction is using "first strong algorithm". The first strong directional character
1986     * determines the paragraph direction. If there is no strong directional character, the
1987     * paragraph direction is the view's resolved layout direction.
1988     */
1989    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1990
1991    /**
1992     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1993     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1994     * If there are neither, the paragraph direction is the view's resolved layout direction.
1995     */
1996    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1997
1998    /**
1999     * Text direction is forced to LTR.
2000     */
2001    public static final int TEXT_DIRECTION_LTR = 3;
2002
2003    /**
2004     * Text direction is forced to RTL.
2005     */
2006    public static final int TEXT_DIRECTION_RTL = 4;
2007
2008    /**
2009     * Text direction is coming from the system Locale.
2010     */
2011    public static final int TEXT_DIRECTION_LOCALE = 5;
2012
2013    /**
2014     * Default text direction is inherited
2015     */
2016    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2017
2018    /**
2019     * Default resolved text direction
2020     * @hide
2021     */
2022    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2023
2024    /**
2025     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2026     * @hide
2027     */
2028    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2029
2030    /**
2031     * Mask for use with private flags indicating bits used for text direction.
2032     * @hide
2033     */
2034    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2035            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2036
2037    /**
2038     * Array of text direction flags for mapping attribute "textDirection" to correct
2039     * flag value.
2040     * @hide
2041     */
2042    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2043            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2044            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2045            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2046            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2047            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2048            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2049    };
2050
2051    /**
2052     * Indicates whether the view text direction has been resolved.
2053     * @hide
2054     */
2055    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2056            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2057
2058    /**
2059     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2060     * @hide
2061     */
2062    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2063
2064    /**
2065     * Mask for use with private flags indicating bits used for resolved text direction.
2066     * @hide
2067     */
2068    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2069            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2070
2071    /**
2072     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2073     * @hide
2074     */
2075    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2076            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2077
2078    /** @hide */
2079    @IntDef({
2080        TEXT_ALIGNMENT_INHERIT,
2081        TEXT_ALIGNMENT_GRAVITY,
2082        TEXT_ALIGNMENT_CENTER,
2083        TEXT_ALIGNMENT_TEXT_START,
2084        TEXT_ALIGNMENT_TEXT_END,
2085        TEXT_ALIGNMENT_VIEW_START,
2086        TEXT_ALIGNMENT_VIEW_END
2087    })
2088    @Retention(RetentionPolicy.SOURCE)
2089    public @interface TextAlignment {}
2090
2091    /**
2092     * Default text alignment. The text alignment of this View is inherited from its parent.
2093     * Use with {@link #setTextAlignment(int)}
2094     */
2095    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2096
2097    /**
2098     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2099     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2100     *
2101     * Use with {@link #setTextAlignment(int)}
2102     */
2103    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2104
2105    /**
2106     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2107     *
2108     * Use with {@link #setTextAlignment(int)}
2109     */
2110    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2111
2112    /**
2113     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2114     *
2115     * Use with {@link #setTextAlignment(int)}
2116     */
2117    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2118
2119    /**
2120     * Center the paragraph, e.g. ALIGN_CENTER.
2121     *
2122     * Use with {@link #setTextAlignment(int)}
2123     */
2124    public static final int TEXT_ALIGNMENT_CENTER = 4;
2125
2126    /**
2127     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2128     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2129     *
2130     * Use with {@link #setTextAlignment(int)}
2131     */
2132    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2133
2134    /**
2135     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2136     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2137     *
2138     * Use with {@link #setTextAlignment(int)}
2139     */
2140    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2141
2142    /**
2143     * Default text alignment is inherited
2144     */
2145    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2146
2147    /**
2148     * Default resolved text alignment
2149     * @hide
2150     */
2151    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2152
2153    /**
2154      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2155      * @hide
2156      */
2157    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2158
2159    /**
2160      * Mask for use with private flags indicating bits used for text alignment.
2161      * @hide
2162      */
2163    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2164
2165    /**
2166     * Array of text direction flags for mapping attribute "textAlignment" to correct
2167     * flag value.
2168     * @hide
2169     */
2170    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2171            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2172            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2173            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2174            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2175            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2176            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2177            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2178    };
2179
2180    /**
2181     * Indicates whether the view text alignment has been resolved.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2185
2186    /**
2187     * Bit shift to get the resolved text alignment.
2188     * @hide
2189     */
2190    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2191
2192    /**
2193     * Mask for use with private flags indicating bits used for text alignment.
2194     * @hide
2195     */
2196    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2197            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2198
2199    /**
2200     * Indicates whether if the view text alignment has been resolved to gravity
2201     */
2202    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2203            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2204
2205    // Accessiblity constants for mPrivateFlags2
2206
2207    /**
2208     * Shift for the bits in {@link #mPrivateFlags2} related to the
2209     * "importantForAccessibility" attribute.
2210     */
2211    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2212
2213    /**
2214     * Automatically determine whether a view is important for accessibility.
2215     */
2216    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2217
2218    /**
2219     * The view is important for accessibility.
2220     */
2221    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2222
2223    /**
2224     * The view is not important for accessibility.
2225     */
2226    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2227
2228    /**
2229     * The view is not important for accessibility, nor are any of its
2230     * descendant views.
2231     */
2232    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2233
2234    /**
2235     * The default whether the view is important for accessibility.
2236     */
2237    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2238
2239    /**
2240     * Mask for obtainig the bits which specify how to determine
2241     * whether a view is important for accessibility.
2242     */
2243    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2244        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2245        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2246        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2247
2248    /**
2249     * Shift for the bits in {@link #mPrivateFlags2} related to the
2250     * "accessibilityLiveRegion" attribute.
2251     */
2252    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2253
2254    /**
2255     * Live region mode specifying that accessibility services should not
2256     * automatically announce changes to this view. This is the default live
2257     * region mode for most views.
2258     * <p>
2259     * Use with {@link #setAccessibilityLiveRegion(int)}.
2260     */
2261    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2262
2263    /**
2264     * Live region mode specifying that accessibility services should announce
2265     * changes to this view.
2266     * <p>
2267     * Use with {@link #setAccessibilityLiveRegion(int)}.
2268     */
2269    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2270
2271    /**
2272     * Live region mode specifying that accessibility services should interrupt
2273     * ongoing speech to immediately announce changes to this view.
2274     * <p>
2275     * Use with {@link #setAccessibilityLiveRegion(int)}.
2276     */
2277    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2278
2279    /**
2280     * The default whether the view is important for accessibility.
2281     */
2282    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2283
2284    /**
2285     * Mask for obtaining the bits which specify a view's accessibility live
2286     * region mode.
2287     */
2288    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2289            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2290            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2291
2292    /**
2293     * Flag indicating whether a view has accessibility focus.
2294     */
2295    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2296
2297    /**
2298     * Flag whether the accessibility state of the subtree rooted at this view changed.
2299     */
2300    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2301
2302    /**
2303     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2304     * is used to check whether later changes to the view's transform should invalidate the
2305     * view to force the quickReject test to run again.
2306     */
2307    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2308
2309    /**
2310     * Flag indicating that start/end padding has been resolved into left/right padding
2311     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2312     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2313     * during measurement. In some special cases this is required such as when an adapter-based
2314     * view measures prospective children without attaching them to a window.
2315     */
2316    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2317
2318    /**
2319     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2320     */
2321    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2322
2323    /**
2324     * Indicates that the view is tracking some sort of transient state
2325     * that the app should not need to be aware of, but that the framework
2326     * should take special care to preserve.
2327     */
2328    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2329
2330    /**
2331     * Group of bits indicating that RTL properties resolution is done.
2332     */
2333    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2334            PFLAG2_TEXT_DIRECTION_RESOLVED |
2335            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2336            PFLAG2_PADDING_RESOLVED |
2337            PFLAG2_DRAWABLE_RESOLVED;
2338
2339    // There are a couple of flags left in mPrivateFlags2
2340
2341    /* End of masks for mPrivateFlags2 */
2342
2343    /**
2344     * Masks for mPrivateFlags3, as generated by dumpFlags():
2345     *
2346     * |-------|-------|-------|-------|
2347     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2348     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2349     *                               1   PFLAG3_IS_LAID_OUT
2350     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2351     *                             1     PFLAG3_CALLED_SUPER
2352     * |-------|-------|-------|-------|
2353     */
2354
2355    /**
2356     * Flag indicating that view has a transform animation set on it. This is used to track whether
2357     * an animation is cleared between successive frames, in order to tell the associated
2358     * DisplayList to clear its animation matrix.
2359     */
2360    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2361
2362    /**
2363     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2364     * animation is cleared between successive frames, in order to tell the associated
2365     * DisplayList to restore its alpha value.
2366     */
2367    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2368
2369    /**
2370     * Flag indicating that the view has been through at least one layout since it
2371     * was last attached to a window.
2372     */
2373    static final int PFLAG3_IS_LAID_OUT = 0x4;
2374
2375    /**
2376     * Flag indicating that a call to measure() was skipped and should be done
2377     * instead when layout() is invoked.
2378     */
2379    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2380
2381    /**
2382     * Flag indicating that an overridden method correctly called down to
2383     * the superclass implementation as required by the API spec.
2384     */
2385    static final int PFLAG3_CALLED_SUPER = 0x10;
2386
2387    /**
2388     * Flag indicating that we're in the process of applying window insets.
2389     */
2390    static final int PFLAG3_APPLYING_INSETS = 0x20;
2391
2392    /**
2393     * Flag indicating that we're in the process of fitting system windows using the old method.
2394     */
2395    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2396
2397    /**
2398     * Flag indicating that nested scrolling is enabled for this view.
2399     * The view will optionally cooperate with views up its parent chain to allow for
2400     * integrated nested scrolling along the same axis.
2401     */
2402    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2403
2404    /* End of masks for mPrivateFlags3 */
2405
2406    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2407
2408    /**
2409     * Always allow a user to over-scroll this view, provided it is a
2410     * view that can scroll.
2411     *
2412     * @see #getOverScrollMode()
2413     * @see #setOverScrollMode(int)
2414     */
2415    public static final int OVER_SCROLL_ALWAYS = 0;
2416
2417    /**
2418     * Allow a user to over-scroll this view only if the content is large
2419     * enough to meaningfully scroll, provided it is a view that can scroll.
2420     *
2421     * @see #getOverScrollMode()
2422     * @see #setOverScrollMode(int)
2423     */
2424    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2425
2426    /**
2427     * Never allow a user to over-scroll this view.
2428     *
2429     * @see #getOverScrollMode()
2430     * @see #setOverScrollMode(int)
2431     */
2432    public static final int OVER_SCROLL_NEVER = 2;
2433
2434    /**
2435     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2436     * requested the system UI (status bar) to be visible (the default).
2437     *
2438     * @see #setSystemUiVisibility(int)
2439     */
2440    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2441
2442    /**
2443     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2444     * system UI to enter an unobtrusive "low profile" mode.
2445     *
2446     * <p>This is for use in games, book readers, video players, or any other
2447     * "immersive" application where the usual system chrome is deemed too distracting.
2448     *
2449     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2450     *
2451     * @see #setSystemUiVisibility(int)
2452     */
2453    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2454
2455    /**
2456     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2457     * system navigation be temporarily hidden.
2458     *
2459     * <p>This is an even less obtrusive state than that called for by
2460     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2461     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2462     * those to disappear. This is useful (in conjunction with the
2463     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2464     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2465     * window flags) for displaying content using every last pixel on the display.
2466     *
2467     * <p>There is a limitation: because navigation controls are so important, the least user
2468     * interaction will cause them to reappear immediately.  When this happens, both
2469     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2470     * so that both elements reappear at the same time.
2471     *
2472     * @see #setSystemUiVisibility(int)
2473     */
2474    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2475
2476    /**
2477     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2478     * into the normal fullscreen mode so that its content can take over the screen
2479     * while still allowing the user to interact with the application.
2480     *
2481     * <p>This has the same visual effect as
2482     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2483     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2484     * meaning that non-critical screen decorations (such as the status bar) will be
2485     * hidden while the user is in the View's window, focusing the experience on
2486     * that content.  Unlike the window flag, if you are using ActionBar in
2487     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2488     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2489     * hide the action bar.
2490     *
2491     * <p>This approach to going fullscreen is best used over the window flag when
2492     * it is a transient state -- that is, the application does this at certain
2493     * points in its user interaction where it wants to allow the user to focus
2494     * on content, but not as a continuous state.  For situations where the application
2495     * would like to simply stay full screen the entire time (such as a game that
2496     * wants to take over the screen), the
2497     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2498     * is usually a better approach.  The state set here will be removed by the system
2499     * in various situations (such as the user moving to another application) like
2500     * the other system UI states.
2501     *
2502     * <p>When using this flag, the application should provide some easy facility
2503     * for the user to go out of it.  A common example would be in an e-book
2504     * reader, where tapping on the screen brings back whatever screen and UI
2505     * decorations that had been hidden while the user was immersed in reading
2506     * the book.
2507     *
2508     * @see #setSystemUiVisibility(int)
2509     */
2510    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2511
2512    /**
2513     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2514     * flags, we would like a stable view of the content insets given to
2515     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2516     * will always represent the worst case that the application can expect
2517     * as a continuous state.  In the stock Android UI this is the space for
2518     * the system bar, nav bar, and status bar, but not more transient elements
2519     * such as an input method.
2520     *
2521     * The stable layout your UI sees is based on the system UI modes you can
2522     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2523     * then you will get a stable layout for changes of the
2524     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2526     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2527     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2528     * with a stable layout.  (Note that you should avoid using
2529     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2530     *
2531     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2532     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2533     * then a hidden status bar will be considered a "stable" state for purposes
2534     * here.  This allows your UI to continually hide the status bar, while still
2535     * using the system UI flags to hide the action bar while still retaining
2536     * a stable layout.  Note that changing the window fullscreen flag will never
2537     * provide a stable layout for a clean transition.
2538     *
2539     * <p>If you are using ActionBar in
2540     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2541     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2542     * insets it adds to those given to the application.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
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_HIDE_NAVIGATION}, 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 the navigation system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2560     * to be layed out as if it has requested
2561     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2562     * allows it to avoid artifacts when switching in and out of that mode, at
2563     * the expense that some of its user interface may be covered by screen
2564     * decorations when they are shown.  You can perform layout of your inner
2565     * UI elements to account for non-fullscreen system UI through the
2566     * {@link #fitSystemWindows(Rect)} method.
2567     */
2568    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2569
2570    /**
2571     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2572     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2573     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2574     * user interaction.
2575     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2576     * has an effect when used in combination with that flag.</p>
2577     */
2578    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2579
2580    /**
2581     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2582     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2583     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2584     * experience while also hiding the system bars.  If this flag is not set,
2585     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2586     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2587     * if the user swipes from the top of the screen.
2588     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2589     * system gestures, such as swiping from the top of the screen.  These transient system bars
2590     * will overlay app’s content, may have some degree of transparency, and will automatically
2591     * hide after a short timeout.
2592     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2593     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2594     * with one or both of those flags.</p>
2595     */
2596    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2597
2598    /**
2599     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2600     */
2601    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2602
2603    /**
2604     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2605     */
2606    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2607
2608    /**
2609     * @hide
2610     *
2611     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2612     * out of the public fields to keep the undefined bits out of the developer's way.
2613     *
2614     * Flag to make the status bar not expandable.  Unless you also
2615     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2616     */
2617    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2618
2619    /**
2620     * @hide
2621     *
2622     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2623     * out of the public fields to keep the undefined bits out of the developer's way.
2624     *
2625     * Flag to hide notification icons and scrolling ticker text.
2626     */
2627    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2628
2629    /**
2630     * @hide
2631     *
2632     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2633     * out of the public fields to keep the undefined bits out of the developer's way.
2634     *
2635     * Flag to disable incoming notification alerts.  This will not block
2636     * icons, but it will block sound, vibrating and other visual or aural notifications.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
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 only the scrolling ticker.  Note that
2647     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2648     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2649     */
2650    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2651
2652    /**
2653     * @hide
2654     *
2655     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2656     * out of the public fields to keep the undefined bits out of the developer's way.
2657     *
2658     * Flag to hide the center system info area.
2659     */
2660    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2661
2662    /**
2663     * @hide
2664     *
2665     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2666     * out of the public fields to keep the undefined bits out of the developer's way.
2667     *
2668     * Flag to hide only the home button.  Don't use this
2669     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2670     */
2671    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2672
2673    /**
2674     * @hide
2675     *
2676     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2677     * out of the public fields to keep the undefined bits out of the developer's way.
2678     *
2679     * Flag to hide only the back button. Don't use this
2680     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2681     */
2682    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2683
2684    /**
2685     * @hide
2686     *
2687     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2688     * out of the public fields to keep the undefined bits out of the developer's way.
2689     *
2690     * Flag to hide only the clock.  You might use this if your activity has
2691     * its own clock making the status bar's clock redundant.
2692     */
2693    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2694
2695    /**
2696     * @hide
2697     *
2698     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2699     * out of the public fields to keep the undefined bits out of the developer's way.
2700     *
2701     * Flag to hide only the recent apps button. Don't use this
2702     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2703     */
2704    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2705
2706    /**
2707     * @hide
2708     *
2709     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2710     * out of the public fields to keep the undefined bits out of the developer's way.
2711     *
2712     * Flag to disable the global search gesture. Don't use this
2713     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2714     */
2715    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2716
2717    /**
2718     * @hide
2719     *
2720     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2721     * out of the public fields to keep the undefined bits out of the developer's way.
2722     *
2723     * Flag to specify that the status bar is displayed in transient mode.
2724     */
2725    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2726
2727    /**
2728     * @hide
2729     *
2730     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2731     * out of the public fields to keep the undefined bits out of the developer's way.
2732     *
2733     * Flag to specify that the navigation bar is displayed in transient mode.
2734     */
2735    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2736
2737    /**
2738     * @hide
2739     *
2740     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2741     * out of the public fields to keep the undefined bits out of the developer's way.
2742     *
2743     * Flag to specify that the hidden status bar would like to be shown.
2744     */
2745    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2746
2747    /**
2748     * @hide
2749     *
2750     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2751     * out of the public fields to keep the undefined bits out of the developer's way.
2752     *
2753     * Flag to specify that the hidden navigation bar would like to be shown.
2754     */
2755    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2756
2757    /**
2758     * @hide
2759     *
2760     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2761     * out of the public fields to keep the undefined bits out of the developer's way.
2762     *
2763     * Flag to specify that the status bar is displayed in translucent mode.
2764     */
2765    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2766
2767    /**
2768     * @hide
2769     *
2770     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2771     * out of the public fields to keep the undefined bits out of the developer's way.
2772     *
2773     * Flag to specify that the navigation bar is displayed in translucent mode.
2774     */
2775    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2776
2777    /**
2778     * @hide
2779     *
2780     * Whether Recents is visible or not.
2781     */
2782    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2783
2784    /**
2785     * @hide
2786     *
2787     * Makes system ui transparent.
2788     */
2789    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2790
2791    /**
2792     * @hide
2793     */
2794    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2795
2796    /**
2797     * These are the system UI flags that can be cleared by events outside
2798     * of an application.  Currently this is just the ability to tap on the
2799     * screen while hiding the navigation bar to have it return.
2800     * @hide
2801     */
2802    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2803            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2804            | SYSTEM_UI_FLAG_FULLSCREEN;
2805
2806    /**
2807     * Flags that can impact the layout in relation to system UI.
2808     */
2809    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2810            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2811            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2812
2813    /** @hide */
2814    @IntDef(flag = true,
2815            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2816    @Retention(RetentionPolicy.SOURCE)
2817    public @interface FindViewFlags {}
2818
2819    /**
2820     * Find views that render the specified text.
2821     *
2822     * @see #findViewsWithText(ArrayList, CharSequence, int)
2823     */
2824    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2825
2826    /**
2827     * Find find views that contain the specified content description.
2828     *
2829     * @see #findViewsWithText(ArrayList, CharSequence, int)
2830     */
2831    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2832
2833    /**
2834     * Find views that contain {@link AccessibilityNodeProvider}. Such
2835     * a View is a root of virtual view hierarchy and may contain the searched
2836     * text. If this flag is set Views with providers are automatically
2837     * added and it is a responsibility of the client to call the APIs of
2838     * the provider to determine whether the virtual tree rooted at this View
2839     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2840     * representing the virtual views with this text.
2841     *
2842     * @see #findViewsWithText(ArrayList, CharSequence, int)
2843     *
2844     * @hide
2845     */
2846    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2847
2848    /**
2849     * The undefined cursor position.
2850     *
2851     * @hide
2852     */
2853    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2854
2855    /**
2856     * Indicates that the screen has changed state and is now off.
2857     *
2858     * @see #onScreenStateChanged(int)
2859     */
2860    public static final int SCREEN_STATE_OFF = 0x0;
2861
2862    /**
2863     * Indicates that the screen has changed state and is now on.
2864     *
2865     * @see #onScreenStateChanged(int)
2866     */
2867    public static final int SCREEN_STATE_ON = 0x1;
2868
2869    /**
2870     * Indicates no axis of view scrolling.
2871     */
2872    public static final int SCROLL_AXIS_NONE = 0;
2873
2874    /**
2875     * Indicates scrolling along the horizontal axis.
2876     */
2877    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2878
2879    /**
2880     * Indicates scrolling along the vertical axis.
2881     */
2882    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2883
2884    /**
2885     * Controls the over-scroll mode for this view.
2886     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2887     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2888     * and {@link #OVER_SCROLL_NEVER}.
2889     */
2890    private int mOverScrollMode;
2891
2892    /**
2893     * The parent this view is attached to.
2894     * {@hide}
2895     *
2896     * @see #getParent()
2897     */
2898    protected ViewParent mParent;
2899
2900    /**
2901     * {@hide}
2902     */
2903    AttachInfo mAttachInfo;
2904
2905    /**
2906     * {@hide}
2907     */
2908    @ViewDebug.ExportedProperty(flagMapping = {
2909        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2910                name = "FORCE_LAYOUT"),
2911        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2912                name = "LAYOUT_REQUIRED"),
2913        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2914            name = "DRAWING_CACHE_INVALID", outputIf = false),
2915        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2916        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2917        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2918        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2919    }, formatToHexString = true)
2920    int mPrivateFlags;
2921    int mPrivateFlags2;
2922    int mPrivateFlags3;
2923
2924    /**
2925     * This view's request for the visibility of the status bar.
2926     * @hide
2927     */
2928    @ViewDebug.ExportedProperty(flagMapping = {
2929        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2930                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2931                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2932        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2933                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2934                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2935        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2936                                equals = SYSTEM_UI_FLAG_VISIBLE,
2937                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2938    }, formatToHexString = true)
2939    int mSystemUiVisibility;
2940
2941    /**
2942     * Reference count for transient state.
2943     * @see #setHasTransientState(boolean)
2944     */
2945    int mTransientStateCount = 0;
2946
2947    /**
2948     * Count of how many windows this view has been attached to.
2949     */
2950    int mWindowAttachCount;
2951
2952    /**
2953     * The layout parameters associated with this view and used by the parent
2954     * {@link android.view.ViewGroup} to determine how this view should be
2955     * laid out.
2956     * {@hide}
2957     */
2958    protected ViewGroup.LayoutParams mLayoutParams;
2959
2960    /**
2961     * The view flags hold various views states.
2962     * {@hide}
2963     */
2964    @ViewDebug.ExportedProperty(formatToHexString = true)
2965    int mViewFlags;
2966
2967    static class TransformationInfo {
2968        /**
2969         * The transform matrix for the View. This transform is calculated internally
2970         * based on the translation, rotation, and scale properties.
2971         *
2972         * Do *not* use this variable directly; instead call getMatrix(), which will
2973         * load the value from the View's RenderNode.
2974         */
2975        private final Matrix mMatrix = new Matrix();
2976
2977        /**
2978         * The inverse transform matrix for the View. This transform is calculated
2979         * internally based on the translation, rotation, and scale properties.
2980         *
2981         * Do *not* use this variable directly; instead call getInverseMatrix(),
2982         * which will load the value from the View's RenderNode.
2983         */
2984        private Matrix mInverseMatrix;
2985
2986        /**
2987         * The opacity of the View. This is a value from 0 to 1, where 0 means
2988         * completely transparent and 1 means completely opaque.
2989         */
2990        @ViewDebug.ExportedProperty
2991        float mAlpha = 1f;
2992
2993        /**
2994         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2995         * property only used by transitions, which is composited with the other alpha
2996         * values to calculate the final visual alpha value.
2997         */
2998        float mTransitionAlpha = 1f;
2999    }
3000
3001    TransformationInfo mTransformationInfo;
3002
3003    /**
3004     * Current clip bounds. to which all drawing of this view are constrained.
3005     */
3006    Rect mClipBounds = null;
3007
3008    private boolean mLastIsOpaque;
3009
3010    /**
3011     * The distance in pixels from the left edge of this view's parent
3012     * to the left edge of this view.
3013     * {@hide}
3014     */
3015    @ViewDebug.ExportedProperty(category = "layout")
3016    protected int mLeft;
3017    /**
3018     * The distance in pixels from the left edge of this view's parent
3019     * to the right edge of this view.
3020     * {@hide}
3021     */
3022    @ViewDebug.ExportedProperty(category = "layout")
3023    protected int mRight;
3024    /**
3025     * The distance in pixels from the top edge of this view's parent
3026     * to the top edge of this view.
3027     * {@hide}
3028     */
3029    @ViewDebug.ExportedProperty(category = "layout")
3030    protected int mTop;
3031    /**
3032     * The distance in pixels from the top edge of this view's parent
3033     * to the bottom edge of this view.
3034     * {@hide}
3035     */
3036    @ViewDebug.ExportedProperty(category = "layout")
3037    protected int mBottom;
3038
3039    /**
3040     * The offset, in pixels, by which the content of this view is scrolled
3041     * horizontally.
3042     * {@hide}
3043     */
3044    @ViewDebug.ExportedProperty(category = "scrolling")
3045    protected int mScrollX;
3046    /**
3047     * The offset, in pixels, by which the content of this view is scrolled
3048     * vertically.
3049     * {@hide}
3050     */
3051    @ViewDebug.ExportedProperty(category = "scrolling")
3052    protected int mScrollY;
3053
3054    /**
3055     * The left padding in pixels, that is the distance in pixels between the
3056     * left edge of this view and the left edge of its content.
3057     * {@hide}
3058     */
3059    @ViewDebug.ExportedProperty(category = "padding")
3060    protected int mPaddingLeft = 0;
3061    /**
3062     * The right padding in pixels, that is the distance in pixels between the
3063     * right edge of this view and the right edge of its content.
3064     * {@hide}
3065     */
3066    @ViewDebug.ExportedProperty(category = "padding")
3067    protected int mPaddingRight = 0;
3068    /**
3069     * The top padding in pixels, that is the distance in pixels between the
3070     * top edge of this view and the top edge of its content.
3071     * {@hide}
3072     */
3073    @ViewDebug.ExportedProperty(category = "padding")
3074    protected int mPaddingTop;
3075    /**
3076     * The bottom padding in pixels, that is the distance in pixels between the
3077     * bottom edge of this view and the bottom edge of its content.
3078     * {@hide}
3079     */
3080    @ViewDebug.ExportedProperty(category = "padding")
3081    protected int mPaddingBottom;
3082
3083    /**
3084     * The layout insets in pixels, that is the distance in pixels between the
3085     * visible edges of this view its bounds.
3086     */
3087    private Insets mLayoutInsets;
3088
3089    /**
3090     * Briefly describes the view and is primarily used for accessibility support.
3091     */
3092    private CharSequence mContentDescription;
3093
3094    /**
3095     * Specifies the id of a view for which this view serves as a label for
3096     * accessibility purposes.
3097     */
3098    private int mLabelForId = View.NO_ID;
3099
3100    /**
3101     * Predicate for matching labeled view id with its label for
3102     * accessibility purposes.
3103     */
3104    private MatchLabelForPredicate mMatchLabelForPredicate;
3105
3106    /**
3107     * Specifies a view before which this one is visited in accessibility traversal.
3108     */
3109    private int mAccessibilityTraversalBeforeId = NO_ID;
3110
3111    /**
3112     * Specifies a view after which this one is visited in accessibility traversal.
3113     */
3114    private int mAccessibilityTraversalAfterId = NO_ID;
3115
3116    /**
3117     * Predicate for matching a view by its id.
3118     */
3119    private MatchIdPredicate mMatchIdPredicate;
3120
3121    /**
3122     * Cache the paddingRight set by the user to append to the scrollbar's size.
3123     *
3124     * @hide
3125     */
3126    @ViewDebug.ExportedProperty(category = "padding")
3127    protected int mUserPaddingRight;
3128
3129    /**
3130     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3131     *
3132     * @hide
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    protected int mUserPaddingBottom;
3136
3137    /**
3138     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3139     *
3140     * @hide
3141     */
3142    @ViewDebug.ExportedProperty(category = "padding")
3143    protected int mUserPaddingLeft;
3144
3145    /**
3146     * Cache the paddingStart set by the user to append to the scrollbar's size.
3147     *
3148     */
3149    @ViewDebug.ExportedProperty(category = "padding")
3150    int mUserPaddingStart;
3151
3152    /**
3153     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3154     *
3155     */
3156    @ViewDebug.ExportedProperty(category = "padding")
3157    int mUserPaddingEnd;
3158
3159    /**
3160     * Cache initial left padding.
3161     *
3162     * @hide
3163     */
3164    int mUserPaddingLeftInitial;
3165
3166    /**
3167     * Cache initial right padding.
3168     *
3169     * @hide
3170     */
3171    int mUserPaddingRightInitial;
3172
3173    /**
3174     * Default undefined padding
3175     */
3176    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3177
3178    /**
3179     * Cache if a left padding has been defined
3180     */
3181    private boolean mLeftPaddingDefined = false;
3182
3183    /**
3184     * Cache if a right padding has been defined
3185     */
3186    private boolean mRightPaddingDefined = false;
3187
3188    /**
3189     * @hide
3190     */
3191    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3192    /**
3193     * @hide
3194     */
3195    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3196
3197    private LongSparseLongArray mMeasureCache;
3198
3199    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3200    private Drawable mBackground;
3201    private TintInfo mBackgroundTint;
3202
3203    /**
3204     * RenderNode used for backgrounds.
3205     * <p>
3206     * When non-null and valid, this is expected to contain an up-to-date copy
3207     * of the background drawable. It is cleared on temporary detach, and reset
3208     * on cleanup.
3209     */
3210    private RenderNode mBackgroundRenderNode;
3211
3212    private int mBackgroundResource;
3213    private boolean mBackgroundSizeChanged;
3214
3215    private String mTransitionName;
3216
3217    private static class TintInfo {
3218        ColorStateList mTintList;
3219        PorterDuff.Mode mTintMode;
3220        boolean mHasTintMode;
3221        boolean mHasTintList;
3222    }
3223
3224    static class ListenerInfo {
3225        /**
3226         * Listener used to dispatch focus change events.
3227         * This field should be made private, so it is hidden from the SDK.
3228         * {@hide}
3229         */
3230        protected OnFocusChangeListener mOnFocusChangeListener;
3231
3232        /**
3233         * Listeners for layout change events.
3234         */
3235        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3236
3237        protected OnScrollChangeListener mOnScrollChangeListener;
3238
3239        /**
3240         * Listeners for attach events.
3241         */
3242        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3243
3244        /**
3245         * Listener used to dispatch click events.
3246         * This field should be made private, so it is hidden from the SDK.
3247         * {@hide}
3248         */
3249        public OnClickListener mOnClickListener;
3250
3251        /**
3252         * Listener used to dispatch long click events.
3253         * This field should be made private, so it is hidden from the SDK.
3254         * {@hide}
3255         */
3256        protected OnLongClickListener mOnLongClickListener;
3257
3258        /**
3259         * Listener used to build the context menu.
3260         * This field should be made private, so it is hidden from the SDK.
3261         * {@hide}
3262         */
3263        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3264
3265        private OnKeyListener mOnKeyListener;
3266
3267        private OnTouchListener mOnTouchListener;
3268
3269        private OnHoverListener mOnHoverListener;
3270
3271        private OnGenericMotionListener mOnGenericMotionListener;
3272
3273        private OnDragListener mOnDragListener;
3274
3275        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3276
3277        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3278    }
3279
3280    ListenerInfo mListenerInfo;
3281
3282    /**
3283     * The application environment this view lives in.
3284     * This field should be made private, so it is hidden from the SDK.
3285     * {@hide}
3286     */
3287    @ViewDebug.ExportedProperty(deepExport = true)
3288    protected Context mContext;
3289
3290    private final Resources mResources;
3291
3292    private ScrollabilityCache mScrollCache;
3293
3294    private int[] mDrawableState = null;
3295
3296    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3297
3298    /**
3299     * Animator that automatically runs based on state changes.
3300     */
3301    private StateListAnimator mStateListAnimator;
3302
3303    /**
3304     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3305     * the user may specify which view to go to next.
3306     */
3307    private int mNextFocusLeftId = View.NO_ID;
3308
3309    /**
3310     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3311     * the user may specify which view to go to next.
3312     */
3313    private int mNextFocusRightId = View.NO_ID;
3314
3315    /**
3316     * When this view has focus and the next focus is {@link #FOCUS_UP},
3317     * the user may specify which view to go to next.
3318     */
3319    private int mNextFocusUpId = View.NO_ID;
3320
3321    /**
3322     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3323     * the user may specify which view to go to next.
3324     */
3325    private int mNextFocusDownId = View.NO_ID;
3326
3327    /**
3328     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3329     * the user may specify which view to go to next.
3330     */
3331    int mNextFocusForwardId = View.NO_ID;
3332
3333    private CheckForLongPress mPendingCheckForLongPress;
3334    private CheckForTap mPendingCheckForTap = null;
3335    private PerformClick mPerformClick;
3336    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3337
3338    private UnsetPressedState mUnsetPressedState;
3339
3340    /**
3341     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3342     * up event while a long press is invoked as soon as the long press duration is reached, so
3343     * a long press could be performed before the tap is checked, in which case the tap's action
3344     * should not be invoked.
3345     */
3346    private boolean mHasPerformedLongPress;
3347
3348    /**
3349     * The minimum height of the view. We'll try our best to have the height
3350     * of this view to at least this amount.
3351     */
3352    @ViewDebug.ExportedProperty(category = "measurement")
3353    private int mMinHeight;
3354
3355    /**
3356     * The minimum width of the view. We'll try our best to have the width
3357     * of this view to at least this amount.
3358     */
3359    @ViewDebug.ExportedProperty(category = "measurement")
3360    private int mMinWidth;
3361
3362    /**
3363     * The delegate to handle touch events that are physically in this view
3364     * but should be handled by another view.
3365     */
3366    private TouchDelegate mTouchDelegate = null;
3367
3368    /**
3369     * Solid color to use as a background when creating the drawing cache. Enables
3370     * the cache to use 16 bit bitmaps instead of 32 bit.
3371     */
3372    private int mDrawingCacheBackgroundColor = 0;
3373
3374    /**
3375     * Special tree observer used when mAttachInfo is null.
3376     */
3377    private ViewTreeObserver mFloatingTreeObserver;
3378
3379    /**
3380     * Cache the touch slop from the context that created the view.
3381     */
3382    private int mTouchSlop;
3383
3384    /**
3385     * Object that handles automatic animation of view properties.
3386     */
3387    private ViewPropertyAnimator mAnimator = null;
3388
3389    /**
3390     * Flag indicating that a drag can cross window boundaries.  When
3391     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3392     * with this flag set, all visible applications will be able to participate
3393     * in the drag operation and receive the dragged content.
3394     *
3395     * @hide
3396     */
3397    public static final int DRAG_FLAG_GLOBAL = 1;
3398
3399    /**
3400     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3401     */
3402    private float mVerticalScrollFactor;
3403
3404    /**
3405     * Position of the vertical scroll bar.
3406     */
3407    private int mVerticalScrollbarPosition;
3408
3409    /**
3410     * Position the scroll bar at the default position as determined by the system.
3411     */
3412    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3413
3414    /**
3415     * Position the scroll bar along the left edge.
3416     */
3417    public static final int SCROLLBAR_POSITION_LEFT = 1;
3418
3419    /**
3420     * Position the scroll bar along the right edge.
3421     */
3422    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3423
3424    /**
3425     * Indicates that the view does not have a layer.
3426     *
3427     * @see #getLayerType()
3428     * @see #setLayerType(int, android.graphics.Paint)
3429     * @see #LAYER_TYPE_SOFTWARE
3430     * @see #LAYER_TYPE_HARDWARE
3431     */
3432    public static final int LAYER_TYPE_NONE = 0;
3433
3434    /**
3435     * <p>Indicates that the view has a software layer. A software layer is backed
3436     * by a bitmap and causes the view to be rendered using Android's software
3437     * rendering pipeline, even if hardware acceleration is enabled.</p>
3438     *
3439     * <p>Software layers have various usages:</p>
3440     * <p>When the application is not using hardware acceleration, a software layer
3441     * is useful to apply a specific color filter and/or blending mode and/or
3442     * translucency to a view and all its children.</p>
3443     * <p>When the application is using hardware acceleration, a software layer
3444     * is useful to render drawing primitives not supported by the hardware
3445     * accelerated pipeline. It can also be used to cache a complex view tree
3446     * into a texture and reduce the complexity of drawing operations. For instance,
3447     * when animating a complex view tree with a translation, a software layer can
3448     * be used to render the view tree only once.</p>
3449     * <p>Software layers should be avoided when the affected view tree updates
3450     * often. Every update will require to re-render the software layer, which can
3451     * potentially be slow (particularly when hardware acceleration is turned on
3452     * since the layer will have to be uploaded into a hardware texture after every
3453     * update.)</p>
3454     *
3455     * @see #getLayerType()
3456     * @see #setLayerType(int, android.graphics.Paint)
3457     * @see #LAYER_TYPE_NONE
3458     * @see #LAYER_TYPE_HARDWARE
3459     */
3460    public static final int LAYER_TYPE_SOFTWARE = 1;
3461
3462    /**
3463     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3464     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3465     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3466     * rendering pipeline, but only if hardware acceleration is turned on for the
3467     * view hierarchy. When hardware acceleration is turned off, hardware layers
3468     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3469     *
3470     * <p>A hardware layer is useful to apply a specific color filter and/or
3471     * blending mode and/or translucency to a view and all its children.</p>
3472     * <p>A hardware layer can be used to cache a complex view tree into a
3473     * texture and reduce the complexity of drawing operations. For instance,
3474     * when animating a complex view tree with a translation, a hardware layer can
3475     * be used to render the view tree only once.</p>
3476     * <p>A hardware layer can also be used to increase the rendering quality when
3477     * rotation transformations are applied on a view. It can also be used to
3478     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3479     *
3480     * @see #getLayerType()
3481     * @see #setLayerType(int, android.graphics.Paint)
3482     * @see #LAYER_TYPE_NONE
3483     * @see #LAYER_TYPE_SOFTWARE
3484     */
3485    public static final int LAYER_TYPE_HARDWARE = 2;
3486
3487    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3488            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3489            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3490            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3491    })
3492    int mLayerType = LAYER_TYPE_NONE;
3493    Paint mLayerPaint;
3494
3495    /**
3496     * Set to true when drawing cache is enabled and cannot be created.
3497     *
3498     * @hide
3499     */
3500    public boolean mCachingFailed;
3501    private Bitmap mDrawingCache;
3502    private Bitmap mUnscaledDrawingCache;
3503
3504    /**
3505     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3506     * <p>
3507     * When non-null and valid, this is expected to contain an up-to-date copy
3508     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3509     * cleanup.
3510     */
3511    final RenderNode mRenderNode;
3512
3513    /**
3514     * Set to true when the view is sending hover accessibility events because it
3515     * is the innermost hovered view.
3516     */
3517    private boolean mSendingHoverAccessibilityEvents;
3518
3519    /**
3520     * Delegate for injecting accessibility functionality.
3521     */
3522    AccessibilityDelegate mAccessibilityDelegate;
3523
3524    /**
3525     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3526     * and add/remove objects to/from the overlay directly through the Overlay methods.
3527     */
3528    ViewOverlay mOverlay;
3529
3530    /**
3531     * The currently active parent view for receiving delegated nested scrolling events.
3532     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3533     * by {@link #stopNestedScroll()} at the same point where we clear
3534     * requestDisallowInterceptTouchEvent.
3535     */
3536    private ViewParent mNestedScrollingParent;
3537
3538    /**
3539     * Consistency verifier for debugging purposes.
3540     * @hide
3541     */
3542    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3543            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3544                    new InputEventConsistencyVerifier(this, 0) : null;
3545
3546    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3547
3548    private int[] mTempNestedScrollConsumed;
3549
3550    /**
3551     * An overlay is going to draw this View instead of being drawn as part of this
3552     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3553     * when this view is invalidated.
3554     */
3555    GhostView mGhostView;
3556
3557    /**
3558     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3559     * @hide
3560     */
3561    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3562    public String[] mAttributes;
3563
3564    /**
3565     * Maps a Resource id to its name.
3566     */
3567    private static SparseArray<String> mAttributeMap;
3568
3569    /**
3570     * Simple constructor to use when creating a view from code.
3571     *
3572     * @param context The Context the view is running in, through which it can
3573     *        access the current theme, resources, etc.
3574     */
3575    public View(Context context) {
3576        mContext = context;
3577        mResources = context != null ? context.getResources() : null;
3578        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3579        // Set some flags defaults
3580        mPrivateFlags2 =
3581                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3582                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3583                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3584                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3585                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3586                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3587        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3588        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3589        mUserPaddingStart = UNDEFINED_PADDING;
3590        mUserPaddingEnd = UNDEFINED_PADDING;
3591        mRenderNode = RenderNode.create(getClass().getName(), this);
3592
3593        if (!sCompatibilityDone && context != null) {
3594            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3595
3596            // Older apps may need this compatibility hack for measurement.
3597            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3598
3599            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3600            // of whether a layout was requested on that View.
3601            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3602
3603            sCompatibilityDone = true;
3604        }
3605    }
3606
3607    /**
3608     * Constructor that is called when inflating a view from XML. This is called
3609     * when a view is being constructed from an XML file, supplying attributes
3610     * that were specified in the XML file. This version uses a default style of
3611     * 0, so the only attribute values applied are those in the Context's Theme
3612     * and the given AttributeSet.
3613     *
3614     * <p>
3615     * The method onFinishInflate() will be called after all children have been
3616     * added.
3617     *
3618     * @param context The Context the view is running in, through which it can
3619     *        access the current theme, resources, etc.
3620     * @param attrs The attributes of the XML tag that is inflating the view.
3621     * @see #View(Context, AttributeSet, int)
3622     */
3623    public View(Context context, AttributeSet attrs) {
3624        this(context, attrs, 0);
3625    }
3626
3627    /**
3628     * Perform inflation from XML and apply a class-specific base style from a
3629     * theme attribute. This constructor of View allows subclasses to use their
3630     * own base style when they are inflating. For example, a Button class's
3631     * constructor would call this version of the super class constructor and
3632     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3633     * allows the theme's button style to modify all of the base view attributes
3634     * (in particular its background) as well as the Button class's attributes.
3635     *
3636     * @param context The Context the view is running in, through which it can
3637     *        access the current theme, resources, etc.
3638     * @param attrs The attributes of the XML tag that is inflating the view.
3639     * @param defStyleAttr An attribute in the current theme that contains a
3640     *        reference to a style resource that supplies default values for
3641     *        the view. Can be 0 to not look for defaults.
3642     * @see #View(Context, AttributeSet)
3643     */
3644    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3645        this(context, attrs, defStyleAttr, 0);
3646    }
3647
3648    /**
3649     * Perform inflation from XML and apply a class-specific base style from a
3650     * theme attribute or style resource. This constructor of View allows
3651     * subclasses to use their own base style when they are inflating.
3652     * <p>
3653     * When determining the final value of a particular attribute, there are
3654     * four inputs that come into play:
3655     * <ol>
3656     * <li>Any attribute values in the given AttributeSet.
3657     * <li>The style resource specified in the AttributeSet (named "style").
3658     * <li>The default style specified by <var>defStyleAttr</var>.
3659     * <li>The default style specified by <var>defStyleRes</var>.
3660     * <li>The base values in this theme.
3661     * </ol>
3662     * <p>
3663     * Each of these inputs is considered in-order, with the first listed taking
3664     * precedence over the following ones. In other words, if in the
3665     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3666     * , then the button's text will <em>always</em> be black, regardless of
3667     * what is specified in any of the styles.
3668     *
3669     * @param context The Context the view is running in, through which it can
3670     *        access the current theme, resources, etc.
3671     * @param attrs The attributes of the XML tag that is inflating the view.
3672     * @param defStyleAttr An attribute in the current theme that contains a
3673     *        reference to a style resource that supplies default values for
3674     *        the view. Can be 0 to not look for defaults.
3675     * @param defStyleRes A resource identifier of a style resource that
3676     *        supplies default values for the view, used only if
3677     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3678     *        to not look for defaults.
3679     * @see #View(Context, AttributeSet, int)
3680     */
3681    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3682        this(context);
3683
3684        final TypedArray a = context.obtainStyledAttributes(
3685                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3686
3687        if (mDebugViewAttributes) {
3688            saveAttributeData(attrs, a);
3689        }
3690
3691        Drawable background = null;
3692
3693        int leftPadding = -1;
3694        int topPadding = -1;
3695        int rightPadding = -1;
3696        int bottomPadding = -1;
3697        int startPadding = UNDEFINED_PADDING;
3698        int endPadding = UNDEFINED_PADDING;
3699
3700        int padding = -1;
3701
3702        int viewFlagValues = 0;
3703        int viewFlagMasks = 0;
3704
3705        boolean setScrollContainer = false;
3706
3707        int x = 0;
3708        int y = 0;
3709
3710        float tx = 0;
3711        float ty = 0;
3712        float tz = 0;
3713        float elevation = 0;
3714        float rotation = 0;
3715        float rotationX = 0;
3716        float rotationY = 0;
3717        float sx = 1f;
3718        float sy = 1f;
3719        boolean transformSet = false;
3720
3721        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3722        int overScrollMode = mOverScrollMode;
3723        boolean initializeScrollbars = false;
3724
3725        boolean startPaddingDefined = false;
3726        boolean endPaddingDefined = false;
3727        boolean leftPaddingDefined = false;
3728        boolean rightPaddingDefined = false;
3729
3730        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3731
3732        final int N = a.getIndexCount();
3733        for (int i = 0; i < N; i++) {
3734            int attr = a.getIndex(i);
3735            switch (attr) {
3736                case com.android.internal.R.styleable.View_background:
3737                    background = a.getDrawable(attr);
3738                    break;
3739                case com.android.internal.R.styleable.View_padding:
3740                    padding = a.getDimensionPixelSize(attr, -1);
3741                    mUserPaddingLeftInitial = padding;
3742                    mUserPaddingRightInitial = padding;
3743                    leftPaddingDefined = true;
3744                    rightPaddingDefined = true;
3745                    break;
3746                 case com.android.internal.R.styleable.View_paddingLeft:
3747                    leftPadding = a.getDimensionPixelSize(attr, -1);
3748                    mUserPaddingLeftInitial = leftPadding;
3749                    leftPaddingDefined = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_paddingTop:
3752                    topPadding = a.getDimensionPixelSize(attr, -1);
3753                    break;
3754                case com.android.internal.R.styleable.View_paddingRight:
3755                    rightPadding = a.getDimensionPixelSize(attr, -1);
3756                    mUserPaddingRightInitial = rightPadding;
3757                    rightPaddingDefined = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_paddingBottom:
3760                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3761                    break;
3762                case com.android.internal.R.styleable.View_paddingStart:
3763                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3764                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3765                    break;
3766                case com.android.internal.R.styleable.View_paddingEnd:
3767                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3768                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3769                    break;
3770                case com.android.internal.R.styleable.View_scrollX:
3771                    x = a.getDimensionPixelOffset(attr, 0);
3772                    break;
3773                case com.android.internal.R.styleable.View_scrollY:
3774                    y = a.getDimensionPixelOffset(attr, 0);
3775                    break;
3776                case com.android.internal.R.styleable.View_alpha:
3777                    setAlpha(a.getFloat(attr, 1f));
3778                    break;
3779                case com.android.internal.R.styleable.View_transformPivotX:
3780                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3781                    break;
3782                case com.android.internal.R.styleable.View_transformPivotY:
3783                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3784                    break;
3785                case com.android.internal.R.styleable.View_translationX:
3786                    tx = a.getDimensionPixelOffset(attr, 0);
3787                    transformSet = true;
3788                    break;
3789                case com.android.internal.R.styleable.View_translationY:
3790                    ty = a.getDimensionPixelOffset(attr, 0);
3791                    transformSet = true;
3792                    break;
3793                case com.android.internal.R.styleable.View_translationZ:
3794                    tz = a.getDimensionPixelOffset(attr, 0);
3795                    transformSet = true;
3796                    break;
3797                case com.android.internal.R.styleable.View_elevation:
3798                    elevation = a.getDimensionPixelOffset(attr, 0);
3799                    transformSet = true;
3800                    break;
3801                case com.android.internal.R.styleable.View_rotation:
3802                    rotation = a.getFloat(attr, 0);
3803                    transformSet = true;
3804                    break;
3805                case com.android.internal.R.styleable.View_rotationX:
3806                    rotationX = a.getFloat(attr, 0);
3807                    transformSet = true;
3808                    break;
3809                case com.android.internal.R.styleable.View_rotationY:
3810                    rotationY = a.getFloat(attr, 0);
3811                    transformSet = true;
3812                    break;
3813                case com.android.internal.R.styleable.View_scaleX:
3814                    sx = a.getFloat(attr, 1f);
3815                    transformSet = true;
3816                    break;
3817                case com.android.internal.R.styleable.View_scaleY:
3818                    sy = a.getFloat(attr, 1f);
3819                    transformSet = true;
3820                    break;
3821                case com.android.internal.R.styleable.View_id:
3822                    mID = a.getResourceId(attr, NO_ID);
3823                    break;
3824                case com.android.internal.R.styleable.View_tag:
3825                    mTag = a.getText(attr);
3826                    break;
3827                case com.android.internal.R.styleable.View_fitsSystemWindows:
3828                    if (a.getBoolean(attr, false)) {
3829                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3830                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3831                    }
3832                    break;
3833                case com.android.internal.R.styleable.View_focusable:
3834                    if (a.getBoolean(attr, false)) {
3835                        viewFlagValues |= FOCUSABLE;
3836                        viewFlagMasks |= FOCUSABLE_MASK;
3837                    }
3838                    break;
3839                case com.android.internal.R.styleable.View_focusableInTouchMode:
3840                    if (a.getBoolean(attr, false)) {
3841                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3842                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3843                    }
3844                    break;
3845                case com.android.internal.R.styleable.View_clickable:
3846                    if (a.getBoolean(attr, false)) {
3847                        viewFlagValues |= CLICKABLE;
3848                        viewFlagMasks |= CLICKABLE;
3849                    }
3850                    break;
3851                case com.android.internal.R.styleable.View_longClickable:
3852                    if (a.getBoolean(attr, false)) {
3853                        viewFlagValues |= LONG_CLICKABLE;
3854                        viewFlagMasks |= LONG_CLICKABLE;
3855                    }
3856                    break;
3857                case com.android.internal.R.styleable.View_saveEnabled:
3858                    if (!a.getBoolean(attr, true)) {
3859                        viewFlagValues |= SAVE_DISABLED;
3860                        viewFlagMasks |= SAVE_DISABLED_MASK;
3861                    }
3862                    break;
3863                case com.android.internal.R.styleable.View_duplicateParentState:
3864                    if (a.getBoolean(attr, false)) {
3865                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3866                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3867                    }
3868                    break;
3869                case com.android.internal.R.styleable.View_visibility:
3870                    final int visibility = a.getInt(attr, 0);
3871                    if (visibility != 0) {
3872                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3873                        viewFlagMasks |= VISIBILITY_MASK;
3874                    }
3875                    break;
3876                case com.android.internal.R.styleable.View_layoutDirection:
3877                    // Clear any layout direction flags (included resolved bits) already set
3878                    mPrivateFlags2 &=
3879                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3880                    // Set the layout direction flags depending on the value of the attribute
3881                    final int layoutDirection = a.getInt(attr, -1);
3882                    final int value = (layoutDirection != -1) ?
3883                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3884                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3885                    break;
3886                case com.android.internal.R.styleable.View_drawingCacheQuality:
3887                    final int cacheQuality = a.getInt(attr, 0);
3888                    if (cacheQuality != 0) {
3889                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3890                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3891                    }
3892                    break;
3893                case com.android.internal.R.styleable.View_contentDescription:
3894                    setContentDescription(a.getString(attr));
3895                    break;
3896                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3897                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3898                    break;
3899                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3900                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3901                    break;
3902                case com.android.internal.R.styleable.View_labelFor:
3903                    setLabelFor(a.getResourceId(attr, NO_ID));
3904                    break;
3905                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3906                    if (!a.getBoolean(attr, true)) {
3907                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3908                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3909                    }
3910                    break;
3911                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3912                    if (!a.getBoolean(attr, true)) {
3913                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3914                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3915                    }
3916                    break;
3917                case R.styleable.View_scrollbars:
3918                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3919                    if (scrollbars != SCROLLBARS_NONE) {
3920                        viewFlagValues |= scrollbars;
3921                        viewFlagMasks |= SCROLLBARS_MASK;
3922                        initializeScrollbars = true;
3923                    }
3924                    break;
3925                //noinspection deprecation
3926                case R.styleable.View_fadingEdge:
3927                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3928                        // Ignore the attribute starting with ICS
3929                        break;
3930                    }
3931                    // With builds < ICS, fall through and apply fading edges
3932                case R.styleable.View_requiresFadingEdge:
3933                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3934                    if (fadingEdge != FADING_EDGE_NONE) {
3935                        viewFlagValues |= fadingEdge;
3936                        viewFlagMasks |= FADING_EDGE_MASK;
3937                        initializeFadingEdgeInternal(a);
3938                    }
3939                    break;
3940                case R.styleable.View_scrollbarStyle:
3941                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3942                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3943                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3944                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3945                    }
3946                    break;
3947                case R.styleable.View_isScrollContainer:
3948                    setScrollContainer = true;
3949                    if (a.getBoolean(attr, false)) {
3950                        setScrollContainer(true);
3951                    }
3952                    break;
3953                case com.android.internal.R.styleable.View_keepScreenOn:
3954                    if (a.getBoolean(attr, false)) {
3955                        viewFlagValues |= KEEP_SCREEN_ON;
3956                        viewFlagMasks |= KEEP_SCREEN_ON;
3957                    }
3958                    break;
3959                case R.styleable.View_filterTouchesWhenObscured:
3960                    if (a.getBoolean(attr, false)) {
3961                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3962                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3963                    }
3964                    break;
3965                case R.styleable.View_nextFocusLeft:
3966                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3967                    break;
3968                case R.styleable.View_nextFocusRight:
3969                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3970                    break;
3971                case R.styleable.View_nextFocusUp:
3972                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3973                    break;
3974                case R.styleable.View_nextFocusDown:
3975                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3976                    break;
3977                case R.styleable.View_nextFocusForward:
3978                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3979                    break;
3980                case R.styleable.View_minWidth:
3981                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3982                    break;
3983                case R.styleable.View_minHeight:
3984                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3985                    break;
3986                case R.styleable.View_onClick:
3987                    if (context.isRestricted()) {
3988                        throw new IllegalStateException("The android:onClick attribute cannot "
3989                                + "be used within a restricted context");
3990                    }
3991
3992                    final String handlerName = a.getString(attr);
3993                    if (handlerName != null) {
3994                        setOnClickListener(new OnClickListener() {
3995                            private Method mHandler;
3996
3997                            public void onClick(View v) {
3998                                if (mHandler == null) {
3999                                    try {
4000                                        mHandler = getContext().getClass().getMethod(handlerName,
4001                                                View.class);
4002                                    } catch (NoSuchMethodException e) {
4003                                        int id = getId();
4004                                        String idText = id == NO_ID ? "" : " with id '"
4005                                                + getContext().getResources().getResourceEntryName(
4006                                                    id) + "'";
4007                                        throw new IllegalStateException("Could not find a method " +
4008                                                handlerName + "(View) in the activity "
4009                                                + getContext().getClass() + " for onClick handler"
4010                                                + " on view " + View.this.getClass() + idText, e);
4011                                    }
4012                                }
4013
4014                                try {
4015                                    mHandler.invoke(getContext(), View.this);
4016                                } catch (IllegalAccessException e) {
4017                                    throw new IllegalStateException("Could not execute non "
4018                                            + "public method of the activity", e);
4019                                } catch (InvocationTargetException e) {
4020                                    throw new IllegalStateException("Could not execute "
4021                                            + "method of the activity", e);
4022                                }
4023                            }
4024                        });
4025                    }
4026                    break;
4027                case R.styleable.View_overScrollMode:
4028                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4029                    break;
4030                case R.styleable.View_verticalScrollbarPosition:
4031                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4032                    break;
4033                case R.styleable.View_layerType:
4034                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4035                    break;
4036                case R.styleable.View_textDirection:
4037                    // Clear any text direction flag already set
4038                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4039                    // Set the text direction flags depending on the value of the attribute
4040                    final int textDirection = a.getInt(attr, -1);
4041                    if (textDirection != -1) {
4042                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4043                    }
4044                    break;
4045                case R.styleable.View_textAlignment:
4046                    // Clear any text alignment flag already set
4047                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4048                    // Set the text alignment flag depending on the value of the attribute
4049                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4050                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4051                    break;
4052                case R.styleable.View_importantForAccessibility:
4053                    setImportantForAccessibility(a.getInt(attr,
4054                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4055                    break;
4056                case R.styleable.View_accessibilityLiveRegion:
4057                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4058                    break;
4059                case R.styleable.View_transitionName:
4060                    setTransitionName(a.getString(attr));
4061                    break;
4062                case R.styleable.View_nestedScrollingEnabled:
4063                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4064                    break;
4065                case R.styleable.View_stateListAnimator:
4066                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4067                            a.getResourceId(attr, 0)));
4068                    break;
4069                case R.styleable.View_backgroundTint:
4070                    // This will get applied later during setBackground().
4071                    if (mBackgroundTint == null) {
4072                        mBackgroundTint = new TintInfo();
4073                    }
4074                    mBackgroundTint.mTintList = a.getColorStateList(
4075                            R.styleable.View_backgroundTint);
4076                    mBackgroundTint.mHasTintList = true;
4077                    break;
4078                case R.styleable.View_backgroundTintMode:
4079                    // This will get applied later during setBackground().
4080                    if (mBackgroundTint == null) {
4081                        mBackgroundTint = new TintInfo();
4082                    }
4083                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4084                            R.styleable.View_backgroundTintMode, -1), null);
4085                    mBackgroundTint.mHasTintMode = true;
4086                    break;
4087                case R.styleable.View_outlineProvider:
4088                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4089                            PROVIDER_BACKGROUND));
4090                    break;
4091            }
4092        }
4093
4094        setOverScrollMode(overScrollMode);
4095
4096        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4097        // the resolved layout direction). Those cached values will be used later during padding
4098        // resolution.
4099        mUserPaddingStart = startPadding;
4100        mUserPaddingEnd = endPadding;
4101
4102        if (background != null) {
4103            setBackground(background);
4104        }
4105
4106        // setBackground above will record that padding is currently provided by the background.
4107        // If we have padding specified via xml, record that here instead and use it.
4108        mLeftPaddingDefined = leftPaddingDefined;
4109        mRightPaddingDefined = rightPaddingDefined;
4110
4111        if (padding >= 0) {
4112            leftPadding = padding;
4113            topPadding = padding;
4114            rightPadding = padding;
4115            bottomPadding = padding;
4116            mUserPaddingLeftInitial = padding;
4117            mUserPaddingRightInitial = padding;
4118        }
4119
4120        if (isRtlCompatibilityMode()) {
4121            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4122            // left / right padding are used if defined (meaning here nothing to do). If they are not
4123            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4124            // start / end and resolve them as left / right (layout direction is not taken into account).
4125            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4126            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4127            // defined.
4128            if (!mLeftPaddingDefined && startPaddingDefined) {
4129                leftPadding = startPadding;
4130            }
4131            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4132            if (!mRightPaddingDefined && endPaddingDefined) {
4133                rightPadding = endPadding;
4134            }
4135            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4136        } else {
4137            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4138            // values defined. Otherwise, left /right values are used.
4139            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4140            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4141            // defined.
4142            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4143
4144            if (mLeftPaddingDefined && !hasRelativePadding) {
4145                mUserPaddingLeftInitial = leftPadding;
4146            }
4147            if (mRightPaddingDefined && !hasRelativePadding) {
4148                mUserPaddingRightInitial = rightPadding;
4149            }
4150        }
4151
4152        internalSetPadding(
4153                mUserPaddingLeftInitial,
4154                topPadding >= 0 ? topPadding : mPaddingTop,
4155                mUserPaddingRightInitial,
4156                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4157
4158        if (viewFlagMasks != 0) {
4159            setFlags(viewFlagValues, viewFlagMasks);
4160        }
4161
4162        if (initializeScrollbars) {
4163            initializeScrollbarsInternal(a);
4164        }
4165
4166        a.recycle();
4167
4168        // Needs to be called after mViewFlags is set
4169        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4170            recomputePadding();
4171        }
4172
4173        if (x != 0 || y != 0) {
4174            scrollTo(x, y);
4175        }
4176
4177        if (transformSet) {
4178            setTranslationX(tx);
4179            setTranslationY(ty);
4180            setTranslationZ(tz);
4181            setElevation(elevation);
4182            setRotation(rotation);
4183            setRotationX(rotationX);
4184            setRotationY(rotationY);
4185            setScaleX(sx);
4186            setScaleY(sy);
4187        }
4188
4189        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4190            setScrollContainer(true);
4191        }
4192
4193        computeOpaqueFlags();
4194    }
4195
4196    /**
4197     * Non-public constructor for use in testing
4198     */
4199    View() {
4200        mResources = null;
4201        mRenderNode = RenderNode.create(getClass().getName(), this);
4202    }
4203
4204    private static SparseArray<String> getAttributeMap() {
4205        if (mAttributeMap == null) {
4206            mAttributeMap = new SparseArray<String>();
4207        }
4208        return mAttributeMap;
4209    }
4210
4211    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4212        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4213        mAttributes = new String[length];
4214
4215        int i = 0;
4216        if (attrs != null) {
4217            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4218                mAttributes[i] = attrs.getAttributeName(i);
4219                mAttributes[i + 1] = attrs.getAttributeValue(i);
4220            }
4221
4222        }
4223
4224        SparseArray<String> attributeMap = getAttributeMap();
4225        for (int j = 0; j < a.length(); ++j) {
4226            if (a.hasValue(j)) {
4227                try {
4228                    int resourceId = a.getResourceId(j, 0);
4229                    if (resourceId == 0) {
4230                        continue;
4231                    }
4232
4233                    String resourceName = attributeMap.get(resourceId);
4234                    if (resourceName == null) {
4235                        resourceName = a.getResources().getResourceName(resourceId);
4236                        attributeMap.put(resourceId, resourceName);
4237                    }
4238
4239                    mAttributes[i] = resourceName;
4240                    mAttributes[i + 1] = a.getText(j).toString();
4241                    i += 2;
4242                } catch (Resources.NotFoundException e) {
4243                    // if we can't get the resource name, we just ignore it
4244                }
4245            }
4246        }
4247    }
4248
4249    public String toString() {
4250        StringBuilder out = new StringBuilder(128);
4251        out.append(getClass().getName());
4252        out.append('{');
4253        out.append(Integer.toHexString(System.identityHashCode(this)));
4254        out.append(' ');
4255        switch (mViewFlags&VISIBILITY_MASK) {
4256            case VISIBLE: out.append('V'); break;
4257            case INVISIBLE: out.append('I'); break;
4258            case GONE: out.append('G'); break;
4259            default: out.append('.'); break;
4260        }
4261        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4262        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4263        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4264        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4265        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4266        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4267        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4268        out.append(' ');
4269        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4270        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4271        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4272        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4273            out.append('p');
4274        } else {
4275            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4276        }
4277        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4278        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4279        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4280        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4281        out.append(' ');
4282        out.append(mLeft);
4283        out.append(',');
4284        out.append(mTop);
4285        out.append('-');
4286        out.append(mRight);
4287        out.append(',');
4288        out.append(mBottom);
4289        final int id = getId();
4290        if (id != NO_ID) {
4291            out.append(" #");
4292            out.append(Integer.toHexString(id));
4293            final Resources r = mResources;
4294            if (Resources.resourceHasPackage(id) && r != null) {
4295                try {
4296                    String pkgname;
4297                    switch (id&0xff000000) {
4298                        case 0x7f000000:
4299                            pkgname="app";
4300                            break;
4301                        case 0x01000000:
4302                            pkgname="android";
4303                            break;
4304                        default:
4305                            pkgname = r.getResourcePackageName(id);
4306                            break;
4307                    }
4308                    String typename = r.getResourceTypeName(id);
4309                    String entryname = r.getResourceEntryName(id);
4310                    out.append(" ");
4311                    out.append(pkgname);
4312                    out.append(":");
4313                    out.append(typename);
4314                    out.append("/");
4315                    out.append(entryname);
4316                } catch (Resources.NotFoundException e) {
4317                }
4318            }
4319        }
4320        out.append("}");
4321        return out.toString();
4322    }
4323
4324    /**
4325     * <p>
4326     * Initializes the fading edges from a given set of styled attributes. This
4327     * method should be called by subclasses that need fading edges and when an
4328     * instance of these subclasses is created programmatically rather than
4329     * being inflated from XML. This method is automatically called when the XML
4330     * is inflated.
4331     * </p>
4332     *
4333     * @param a the styled attributes set to initialize the fading edges from
4334     *
4335     * @removed
4336     */
4337    protected void initializeFadingEdge(TypedArray a) {
4338        // This method probably shouldn't have been included in the SDK to begin with.
4339        // It relies on 'a' having been initialized using an attribute filter array that is
4340        // not publicly available to the SDK. The old method has been renamed
4341        // to initializeFadingEdgeInternal and hidden for framework use only;
4342        // this one initializes using defaults to make it safe to call for apps.
4343
4344        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4345
4346        initializeFadingEdgeInternal(arr);
4347
4348        arr.recycle();
4349    }
4350
4351    /**
4352     * <p>
4353     * Initializes the fading edges from a given set of styled attributes. This
4354     * method should be called by subclasses that need fading edges and when an
4355     * instance of these subclasses is created programmatically rather than
4356     * being inflated from XML. This method is automatically called when the XML
4357     * is inflated.
4358     * </p>
4359     *
4360     * @param a the styled attributes set to initialize the fading edges from
4361     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4362     */
4363    protected void initializeFadingEdgeInternal(TypedArray a) {
4364        initScrollCache();
4365
4366        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4367                R.styleable.View_fadingEdgeLength,
4368                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4369    }
4370
4371    /**
4372     * Returns the size of the vertical faded edges used to indicate that more
4373     * content in this view is visible.
4374     *
4375     * @return The size in pixels of the vertical faded edge or 0 if vertical
4376     *         faded edges are not enabled for this view.
4377     * @attr ref android.R.styleable#View_fadingEdgeLength
4378     */
4379    public int getVerticalFadingEdgeLength() {
4380        if (isVerticalFadingEdgeEnabled()) {
4381            ScrollabilityCache cache = mScrollCache;
4382            if (cache != null) {
4383                return cache.fadingEdgeLength;
4384            }
4385        }
4386        return 0;
4387    }
4388
4389    /**
4390     * Set the size of the faded edge used to indicate that more content in this
4391     * view is available.  Will not change whether the fading edge is enabled; use
4392     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4393     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4394     * for the vertical or horizontal fading edges.
4395     *
4396     * @param length The size in pixels of the faded edge used to indicate that more
4397     *        content in this view is visible.
4398     */
4399    public void setFadingEdgeLength(int length) {
4400        initScrollCache();
4401        mScrollCache.fadingEdgeLength = length;
4402    }
4403
4404    /**
4405     * Returns the size of the horizontal faded edges used to indicate that more
4406     * content in this view is visible.
4407     *
4408     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4409     *         faded edges are not enabled for this view.
4410     * @attr ref android.R.styleable#View_fadingEdgeLength
4411     */
4412    public int getHorizontalFadingEdgeLength() {
4413        if (isHorizontalFadingEdgeEnabled()) {
4414            ScrollabilityCache cache = mScrollCache;
4415            if (cache != null) {
4416                return cache.fadingEdgeLength;
4417            }
4418        }
4419        return 0;
4420    }
4421
4422    /**
4423     * Returns the width of the vertical scrollbar.
4424     *
4425     * @return The width in pixels of the vertical scrollbar or 0 if there
4426     *         is no vertical scrollbar.
4427     */
4428    public int getVerticalScrollbarWidth() {
4429        ScrollabilityCache cache = mScrollCache;
4430        if (cache != null) {
4431            ScrollBarDrawable scrollBar = cache.scrollBar;
4432            if (scrollBar != null) {
4433                int size = scrollBar.getSize(true);
4434                if (size <= 0) {
4435                    size = cache.scrollBarSize;
4436                }
4437                return size;
4438            }
4439            return 0;
4440        }
4441        return 0;
4442    }
4443
4444    /**
4445     * Returns the height of the horizontal scrollbar.
4446     *
4447     * @return The height in pixels of the horizontal scrollbar or 0 if
4448     *         there is no horizontal scrollbar.
4449     */
4450    protected int getHorizontalScrollbarHeight() {
4451        ScrollabilityCache cache = mScrollCache;
4452        if (cache != null) {
4453            ScrollBarDrawable scrollBar = cache.scrollBar;
4454            if (scrollBar != null) {
4455                int size = scrollBar.getSize(false);
4456                if (size <= 0) {
4457                    size = cache.scrollBarSize;
4458                }
4459                return size;
4460            }
4461            return 0;
4462        }
4463        return 0;
4464    }
4465
4466    /**
4467     * <p>
4468     * Initializes the scrollbars from a given set of styled attributes. This
4469     * method should be called by subclasses that need scrollbars and when an
4470     * instance of these subclasses is created programmatically rather than
4471     * being inflated from XML. This method is automatically called when the XML
4472     * is inflated.
4473     * </p>
4474     *
4475     * @param a the styled attributes set to initialize the scrollbars from
4476     *
4477     * @removed
4478     */
4479    protected void initializeScrollbars(TypedArray a) {
4480        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4481        // using the View filter array which is not available to the SDK. As such, internal
4482        // framework usage now uses initializeScrollbarsInternal and we grab a default
4483        // TypedArray with the right filter instead here.
4484        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4485
4486        initializeScrollbarsInternal(arr);
4487
4488        // We ignored the method parameter. Recycle the one we actually did use.
4489        arr.recycle();
4490    }
4491
4492    /**
4493     * <p>
4494     * Initializes the scrollbars from a given set of styled attributes. This
4495     * method should be called by subclasses that need scrollbars and when an
4496     * instance of these subclasses is created programmatically rather than
4497     * being inflated from XML. This method is automatically called when the XML
4498     * is inflated.
4499     * </p>
4500     *
4501     * @param a the styled attributes set to initialize the scrollbars from
4502     * @hide
4503     */
4504    protected void initializeScrollbarsInternal(TypedArray a) {
4505        initScrollCache();
4506
4507        final ScrollabilityCache scrollabilityCache = mScrollCache;
4508
4509        if (scrollabilityCache.scrollBar == null) {
4510            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4511        }
4512
4513        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4514
4515        if (!fadeScrollbars) {
4516            scrollabilityCache.state = ScrollabilityCache.ON;
4517        }
4518        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4519
4520
4521        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4522                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4523                        .getScrollBarFadeDuration());
4524        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4525                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4526                ViewConfiguration.getScrollDefaultDelay());
4527
4528
4529        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4530                com.android.internal.R.styleable.View_scrollbarSize,
4531                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4532
4533        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4534        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4535
4536        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4537        if (thumb != null) {
4538            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4539        }
4540
4541        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4542                false);
4543        if (alwaysDraw) {
4544            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4545        }
4546
4547        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4548        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4549
4550        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4551        if (thumb != null) {
4552            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4553        }
4554
4555        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4556                false);
4557        if (alwaysDraw) {
4558            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4559        }
4560
4561        // Apply layout direction to the new Drawables if needed
4562        final int layoutDirection = getLayoutDirection();
4563        if (track != null) {
4564            track.setLayoutDirection(layoutDirection);
4565        }
4566        if (thumb != null) {
4567            thumb.setLayoutDirection(layoutDirection);
4568        }
4569
4570        // Re-apply user/background padding so that scrollbar(s) get added
4571        resolvePadding();
4572    }
4573
4574    /**
4575     * <p>
4576     * Initalizes the scrollability cache if necessary.
4577     * </p>
4578     */
4579    private void initScrollCache() {
4580        if (mScrollCache == null) {
4581            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4582        }
4583    }
4584
4585    private ScrollabilityCache getScrollCache() {
4586        initScrollCache();
4587        return mScrollCache;
4588    }
4589
4590    /**
4591     * Set the position of the vertical scroll bar. Should be one of
4592     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4593     * {@link #SCROLLBAR_POSITION_RIGHT}.
4594     *
4595     * @param position Where the vertical scroll bar should be positioned.
4596     */
4597    public void setVerticalScrollbarPosition(int position) {
4598        if (mVerticalScrollbarPosition != position) {
4599            mVerticalScrollbarPosition = position;
4600            computeOpaqueFlags();
4601            resolvePadding();
4602        }
4603    }
4604
4605    /**
4606     * @return The position where the vertical scroll bar will show, if applicable.
4607     * @see #setVerticalScrollbarPosition(int)
4608     */
4609    public int getVerticalScrollbarPosition() {
4610        return mVerticalScrollbarPosition;
4611    }
4612
4613    ListenerInfo getListenerInfo() {
4614        if (mListenerInfo != null) {
4615            return mListenerInfo;
4616        }
4617        mListenerInfo = new ListenerInfo();
4618        return mListenerInfo;
4619    }
4620
4621    /**
4622     * Register a callback to be invoked when the scroll position of this view
4623     * changed.
4624     *
4625     * @param l The callback that will run.
4626     * @hide Only used internally.
4627     */
4628    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4629        getListenerInfo().mOnScrollChangeListener = l;
4630    }
4631
4632    /**
4633     * Register a callback to be invoked when focus of this view changed.
4634     *
4635     * @param l The callback that will run.
4636     */
4637    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4638        getListenerInfo().mOnFocusChangeListener = l;
4639    }
4640
4641    /**
4642     * Add a listener that will be called when the bounds of the view change due to
4643     * layout processing.
4644     *
4645     * @param listener The listener that will be called when layout bounds change.
4646     */
4647    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4648        ListenerInfo li = getListenerInfo();
4649        if (li.mOnLayoutChangeListeners == null) {
4650            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4651        }
4652        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4653            li.mOnLayoutChangeListeners.add(listener);
4654        }
4655    }
4656
4657    /**
4658     * Remove a listener for layout changes.
4659     *
4660     * @param listener The listener for layout bounds change.
4661     */
4662    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4663        ListenerInfo li = mListenerInfo;
4664        if (li == null || li.mOnLayoutChangeListeners == null) {
4665            return;
4666        }
4667        li.mOnLayoutChangeListeners.remove(listener);
4668    }
4669
4670    /**
4671     * Add a listener for attach state changes.
4672     *
4673     * This listener will be called whenever this view is attached or detached
4674     * from a window. Remove the listener using
4675     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4676     *
4677     * @param listener Listener to attach
4678     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4679     */
4680    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4681        ListenerInfo li = getListenerInfo();
4682        if (li.mOnAttachStateChangeListeners == null) {
4683            li.mOnAttachStateChangeListeners
4684                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4685        }
4686        li.mOnAttachStateChangeListeners.add(listener);
4687    }
4688
4689    /**
4690     * Remove a listener for attach state changes. The listener will receive no further
4691     * notification of window attach/detach events.
4692     *
4693     * @param listener Listener to remove
4694     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4695     */
4696    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4697        ListenerInfo li = mListenerInfo;
4698        if (li == null || li.mOnAttachStateChangeListeners == null) {
4699            return;
4700        }
4701        li.mOnAttachStateChangeListeners.remove(listener);
4702    }
4703
4704    /**
4705     * Returns the focus-change callback registered for this view.
4706     *
4707     * @return The callback, or null if one is not registered.
4708     */
4709    public OnFocusChangeListener getOnFocusChangeListener() {
4710        ListenerInfo li = mListenerInfo;
4711        return li != null ? li.mOnFocusChangeListener : null;
4712    }
4713
4714    /**
4715     * Register a callback to be invoked when this view is clicked. If this view is not
4716     * clickable, it becomes clickable.
4717     *
4718     * @param l The callback that will run
4719     *
4720     * @see #setClickable(boolean)
4721     */
4722    public void setOnClickListener(OnClickListener l) {
4723        if (!isClickable()) {
4724            setClickable(true);
4725        }
4726        getListenerInfo().mOnClickListener = l;
4727    }
4728
4729    /**
4730     * Return whether this view has an attached OnClickListener.  Returns
4731     * true if there is a listener, false if there is none.
4732     */
4733    public boolean hasOnClickListeners() {
4734        ListenerInfo li = mListenerInfo;
4735        return (li != null && li.mOnClickListener != null);
4736    }
4737
4738    /**
4739     * Register a callback to be invoked when this view is clicked and held. If this view is not
4740     * long clickable, it becomes long clickable.
4741     *
4742     * @param l The callback that will run
4743     *
4744     * @see #setLongClickable(boolean)
4745     */
4746    public void setOnLongClickListener(OnLongClickListener l) {
4747        if (!isLongClickable()) {
4748            setLongClickable(true);
4749        }
4750        getListenerInfo().mOnLongClickListener = l;
4751    }
4752
4753    /**
4754     * Register a callback to be invoked when the context menu for this view is
4755     * being built. If this view is not long clickable, it becomes long clickable.
4756     *
4757     * @param l The callback that will run
4758     *
4759     */
4760    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4761        if (!isLongClickable()) {
4762            setLongClickable(true);
4763        }
4764        getListenerInfo().mOnCreateContextMenuListener = l;
4765    }
4766
4767    /**
4768     * Call this view's OnClickListener, if it is defined.  Performs all normal
4769     * actions associated with clicking: reporting accessibility event, playing
4770     * a sound, etc.
4771     *
4772     * @return True there was an assigned OnClickListener that was called, false
4773     *         otherwise is returned.
4774     */
4775    public boolean performClick() {
4776        final boolean result;
4777        final ListenerInfo li = mListenerInfo;
4778        if (li != null && li.mOnClickListener != null) {
4779            playSoundEffect(SoundEffectConstants.CLICK);
4780            li.mOnClickListener.onClick(this);
4781            result = true;
4782        } else {
4783            result = false;
4784        }
4785
4786        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4787        return result;
4788    }
4789
4790    /**
4791     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4792     * this only calls the listener, and does not do any associated clicking
4793     * actions like reporting an accessibility event.
4794     *
4795     * @return True there was an assigned OnClickListener that was called, false
4796     *         otherwise is returned.
4797     */
4798    public boolean callOnClick() {
4799        ListenerInfo li = mListenerInfo;
4800        if (li != null && li.mOnClickListener != null) {
4801            li.mOnClickListener.onClick(this);
4802            return true;
4803        }
4804        return false;
4805    }
4806
4807    /**
4808     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4809     * OnLongClickListener did not consume the event.
4810     *
4811     * @return True if one of the above receivers consumed the event, false otherwise.
4812     */
4813    public boolean performLongClick() {
4814        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4815
4816        boolean handled = false;
4817        ListenerInfo li = mListenerInfo;
4818        if (li != null && li.mOnLongClickListener != null) {
4819            handled = li.mOnLongClickListener.onLongClick(View.this);
4820        }
4821        if (!handled) {
4822            handled = showContextMenu();
4823        }
4824        if (handled) {
4825            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4826        }
4827        return handled;
4828    }
4829
4830    /**
4831     * Performs button-related actions during a touch down event.
4832     *
4833     * @param event The event.
4834     * @return True if the down was consumed.
4835     *
4836     * @hide
4837     */
4838    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4839        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4840            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4841                return true;
4842            }
4843        }
4844        return false;
4845    }
4846
4847    /**
4848     * Bring up the context menu for this view.
4849     *
4850     * @return Whether a context menu was displayed.
4851     */
4852    public boolean showContextMenu() {
4853        return getParent().showContextMenuForChild(this);
4854    }
4855
4856    /**
4857     * Bring up the context menu for this view, referring to the item under the specified point.
4858     *
4859     * @param x The referenced x coordinate.
4860     * @param y The referenced y coordinate.
4861     * @param metaState The keyboard modifiers that were pressed.
4862     * @return Whether a context menu was displayed.
4863     *
4864     * @hide
4865     */
4866    public boolean showContextMenu(float x, float y, int metaState) {
4867        return showContextMenu();
4868    }
4869
4870    /**
4871     * Start an action mode.
4872     *
4873     * @param callback Callback that will control the lifecycle of the action mode
4874     * @return The new action mode if it is started, null otherwise
4875     *
4876     * @see ActionMode
4877     */
4878    public ActionMode startActionMode(ActionMode.Callback callback) {
4879        ViewParent parent = getParent();
4880        if (parent == null) return null;
4881        return parent.startActionModeForChild(this, callback);
4882    }
4883
4884    /**
4885     * Register a callback to be invoked when a hardware key is pressed in this view.
4886     * Key presses in software input methods will generally not trigger the methods of
4887     * this listener.
4888     * @param l the key listener to attach to this view
4889     */
4890    public void setOnKeyListener(OnKeyListener l) {
4891        getListenerInfo().mOnKeyListener = l;
4892    }
4893
4894    /**
4895     * Register a callback to be invoked when a touch event is sent to this view.
4896     * @param l the touch listener to attach to this view
4897     */
4898    public void setOnTouchListener(OnTouchListener l) {
4899        getListenerInfo().mOnTouchListener = l;
4900    }
4901
4902    /**
4903     * Register a callback to be invoked when a generic motion event is sent to this view.
4904     * @param l the generic motion listener to attach to this view
4905     */
4906    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4907        getListenerInfo().mOnGenericMotionListener = l;
4908    }
4909
4910    /**
4911     * Register a callback to be invoked when a hover event is sent to this view.
4912     * @param l the hover listener to attach to this view
4913     */
4914    public void setOnHoverListener(OnHoverListener l) {
4915        getListenerInfo().mOnHoverListener = l;
4916    }
4917
4918    /**
4919     * Register a drag event listener callback object for this View. The parameter is
4920     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4921     * View, the system calls the
4922     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4923     * @param l An implementation of {@link android.view.View.OnDragListener}.
4924     */
4925    public void setOnDragListener(OnDragListener l) {
4926        getListenerInfo().mOnDragListener = l;
4927    }
4928
4929    /**
4930     * Give this view focus. This will cause
4931     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4932     *
4933     * Note: this does not check whether this {@link View} should get focus, it just
4934     * gives it focus no matter what.  It should only be called internally by framework
4935     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4936     *
4937     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4938     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4939     *        focus moved when requestFocus() is called. It may not always
4940     *        apply, in which case use the default View.FOCUS_DOWN.
4941     * @param previouslyFocusedRect The rectangle of the view that had focus
4942     *        prior in this View's coordinate system.
4943     */
4944    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4945        if (DBG) {
4946            System.out.println(this + " requestFocus()");
4947        }
4948
4949        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4950            mPrivateFlags |= PFLAG_FOCUSED;
4951
4952            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4953
4954            if (mParent != null) {
4955                mParent.requestChildFocus(this, this);
4956            }
4957
4958            if (mAttachInfo != null) {
4959                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4960            }
4961
4962            onFocusChanged(true, direction, previouslyFocusedRect);
4963            refreshDrawableState();
4964        }
4965    }
4966
4967    /**
4968     * Populates <code>outRect</code> with the hotspot bounds. By default,
4969     * the hotspot bounds are identical to the screen bounds.
4970     *
4971     * @param outRect rect to populate with hotspot bounds
4972     * @hide Only for internal use by views and widgets.
4973     */
4974    public void getHotspotBounds(Rect outRect) {
4975        final Drawable background = getBackground();
4976        if (background != null) {
4977            background.getHotspotBounds(outRect);
4978        } else {
4979            getBoundsOnScreen(outRect);
4980        }
4981    }
4982
4983    /**
4984     * Request that a rectangle of this view be visible on the screen,
4985     * scrolling if necessary just enough.
4986     *
4987     * <p>A View should call this if it maintains some notion of which part
4988     * of its content is interesting.  For example, a text editing view
4989     * should call this when its cursor moves.
4990     *
4991     * @param rectangle The rectangle.
4992     * @return Whether any parent scrolled.
4993     */
4994    public boolean requestRectangleOnScreen(Rect rectangle) {
4995        return requestRectangleOnScreen(rectangle, false);
4996    }
4997
4998    /**
4999     * Request that a rectangle of this view be visible on the screen,
5000     * scrolling if necessary just enough.
5001     *
5002     * <p>A View should call this if it maintains some notion of which part
5003     * of its content is interesting.  For example, a text editing view
5004     * should call this when its cursor moves.
5005     *
5006     * <p>When <code>immediate</code> is set to true, scrolling will not be
5007     * animated.
5008     *
5009     * @param rectangle The rectangle.
5010     * @param immediate True to forbid animated scrolling, false otherwise
5011     * @return Whether any parent scrolled.
5012     */
5013    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5014        if (mParent == null) {
5015            return false;
5016        }
5017
5018        View child = this;
5019
5020        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5021        position.set(rectangle);
5022
5023        ViewParent parent = mParent;
5024        boolean scrolled = false;
5025        while (parent != null) {
5026            rectangle.set((int) position.left, (int) position.top,
5027                    (int) position.right, (int) position.bottom);
5028
5029            scrolled |= parent.requestChildRectangleOnScreen(child,
5030                    rectangle, immediate);
5031
5032            if (!child.hasIdentityMatrix()) {
5033                child.getMatrix().mapRect(position);
5034            }
5035
5036            position.offset(child.mLeft, child.mTop);
5037
5038            if (!(parent instanceof View)) {
5039                break;
5040            }
5041
5042            View parentView = (View) parent;
5043
5044            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5045
5046            child = parentView;
5047            parent = child.getParent();
5048        }
5049
5050        return scrolled;
5051    }
5052
5053    /**
5054     * Called when this view wants to give up focus. If focus is cleared
5055     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5056     * <p>
5057     * <strong>Note:</strong> When a View clears focus the framework is trying
5058     * to give focus to the first focusable View from the top. Hence, if this
5059     * View is the first from the top that can take focus, then all callbacks
5060     * related to clearing focus will be invoked after which the framework will
5061     * give focus to this view.
5062     * </p>
5063     */
5064    public void clearFocus() {
5065        if (DBG) {
5066            System.out.println(this + " clearFocus()");
5067        }
5068
5069        clearFocusInternal(null, true, true);
5070    }
5071
5072    /**
5073     * Clears focus from the view, optionally propagating the change up through
5074     * the parent hierarchy and requesting that the root view place new focus.
5075     *
5076     * @param propagate whether to propagate the change up through the parent
5077     *            hierarchy
5078     * @param refocus when propagate is true, specifies whether to request the
5079     *            root view place new focus
5080     */
5081    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5082        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5083            mPrivateFlags &= ~PFLAG_FOCUSED;
5084
5085            if (propagate && mParent != null) {
5086                mParent.clearChildFocus(this);
5087            }
5088
5089            onFocusChanged(false, 0, null);
5090            refreshDrawableState();
5091
5092            if (propagate && (!refocus || !rootViewRequestFocus())) {
5093                notifyGlobalFocusCleared(this);
5094            }
5095        }
5096    }
5097
5098    void notifyGlobalFocusCleared(View oldFocus) {
5099        if (oldFocus != null && mAttachInfo != null) {
5100            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5101        }
5102    }
5103
5104    boolean rootViewRequestFocus() {
5105        final View root = getRootView();
5106        return root != null && root.requestFocus();
5107    }
5108
5109    /**
5110     * Called internally by the view system when a new view is getting focus.
5111     * This is what clears the old focus.
5112     * <p>
5113     * <b>NOTE:</b> The parent view's focused child must be updated manually
5114     * after calling this method. Otherwise, the view hierarchy may be left in
5115     * an inconstent state.
5116     */
5117    void unFocus(View focused) {
5118        if (DBG) {
5119            System.out.println(this + " unFocus()");
5120        }
5121
5122        clearFocusInternal(focused, false, false);
5123    }
5124
5125    /**
5126     * Returns true if this view has focus iteself, or is the ancestor of the
5127     * view that has focus.
5128     *
5129     * @return True if this view has or contains focus, false otherwise.
5130     */
5131    @ViewDebug.ExportedProperty(category = "focus")
5132    public boolean hasFocus() {
5133        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5134    }
5135
5136    /**
5137     * Returns true if this view is focusable or if it contains a reachable View
5138     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5139     * is a View whose parents do not block descendants focus.
5140     *
5141     * Only {@link #VISIBLE} views are considered focusable.
5142     *
5143     * @return True if the view is focusable or if the view contains a focusable
5144     *         View, false otherwise.
5145     *
5146     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5147     * @see ViewGroup#getTouchscreenBlocksFocus()
5148     */
5149    public boolean hasFocusable() {
5150        if (!isFocusableInTouchMode()) {
5151            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5152                final ViewGroup g = (ViewGroup) p;
5153                if (g.shouldBlockFocusForTouchscreen()) {
5154                    return false;
5155                }
5156            }
5157        }
5158        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5159    }
5160
5161    /**
5162     * Called by the view system when the focus state of this view changes.
5163     * When the focus change event is caused by directional navigation, direction
5164     * and previouslyFocusedRect provide insight into where the focus is coming from.
5165     * When overriding, be sure to call up through to the super class so that
5166     * the standard focus handling will occur.
5167     *
5168     * @param gainFocus True if the View has focus; false otherwise.
5169     * @param direction The direction focus has moved when requestFocus()
5170     *                  is called to give this view focus. Values are
5171     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5172     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5173     *                  It may not always apply, in which case use the default.
5174     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5175     *        system, of the previously focused view.  If applicable, this will be
5176     *        passed in as finer grained information about where the focus is coming
5177     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5178     */
5179    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5180            @Nullable Rect previouslyFocusedRect) {
5181        if (gainFocus) {
5182            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5183        } else {
5184            notifyViewAccessibilityStateChangedIfNeeded(
5185                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5186        }
5187
5188        InputMethodManager imm = InputMethodManager.peekInstance();
5189        if (!gainFocus) {
5190            if (isPressed()) {
5191                setPressed(false);
5192            }
5193            if (imm != null && mAttachInfo != null
5194                    && mAttachInfo.mHasWindowFocus) {
5195                imm.focusOut(this);
5196            }
5197            onFocusLost();
5198        } else if (imm != null && mAttachInfo != null
5199                && mAttachInfo.mHasWindowFocus) {
5200            imm.focusIn(this);
5201        }
5202
5203        invalidate(true);
5204        ListenerInfo li = mListenerInfo;
5205        if (li != null && li.mOnFocusChangeListener != null) {
5206            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5207        }
5208
5209        if (mAttachInfo != null) {
5210            mAttachInfo.mKeyDispatchState.reset(this);
5211        }
5212    }
5213
5214    /**
5215     * Sends an accessibility event of the given type. If accessibility is
5216     * not enabled this method has no effect. The default implementation calls
5217     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5218     * to populate information about the event source (this View), then calls
5219     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5220     * populate the text content of the event source including its descendants,
5221     * and last calls
5222     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5223     * on its parent to resuest sending of the event to interested parties.
5224     * <p>
5225     * If an {@link AccessibilityDelegate} has been specified via calling
5226     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5227     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5228     * responsible for handling this call.
5229     * </p>
5230     *
5231     * @param eventType The type of the event to send, as defined by several types from
5232     * {@link android.view.accessibility.AccessibilityEvent}, such as
5233     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5234     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5235     *
5236     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5237     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5238     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5239     * @see AccessibilityDelegate
5240     */
5241    public void sendAccessibilityEvent(int eventType) {
5242        if (mAccessibilityDelegate != null) {
5243            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5244        } else {
5245            sendAccessibilityEventInternal(eventType);
5246        }
5247    }
5248
5249    /**
5250     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5251     * {@link AccessibilityEvent} to make an announcement which is related to some
5252     * sort of a context change for which none of the events representing UI transitions
5253     * is a good fit. For example, announcing a new page in a book. If accessibility
5254     * is not enabled this method does nothing.
5255     *
5256     * @param text The announcement text.
5257     */
5258    public void announceForAccessibility(CharSequence text) {
5259        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5260            AccessibilityEvent event = AccessibilityEvent.obtain(
5261                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5262            onInitializeAccessibilityEvent(event);
5263            event.getText().add(text);
5264            event.setContentDescription(null);
5265            mParent.requestSendAccessibilityEvent(this, event);
5266        }
5267    }
5268
5269    /**
5270     * @see #sendAccessibilityEvent(int)
5271     *
5272     * Note: Called from the default {@link AccessibilityDelegate}.
5273     */
5274    void sendAccessibilityEventInternal(int eventType) {
5275        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5276            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5277        }
5278    }
5279
5280    /**
5281     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5282     * takes as an argument an empty {@link AccessibilityEvent} and does not
5283     * perform a check whether accessibility is enabled.
5284     * <p>
5285     * If an {@link AccessibilityDelegate} has been specified via calling
5286     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5287     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5288     * is responsible for handling this call.
5289     * </p>
5290     *
5291     * @param event The event to send.
5292     *
5293     * @see #sendAccessibilityEvent(int)
5294     */
5295    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5296        if (mAccessibilityDelegate != null) {
5297            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5298        } else {
5299            sendAccessibilityEventUncheckedInternal(event);
5300        }
5301    }
5302
5303    /**
5304     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5305     *
5306     * Note: Called from the default {@link AccessibilityDelegate}.
5307     */
5308    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5309        if (!isShown()) {
5310            return;
5311        }
5312        onInitializeAccessibilityEvent(event);
5313        // Only a subset of accessibility events populates text content.
5314        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5315            dispatchPopulateAccessibilityEvent(event);
5316        }
5317        // In the beginning we called #isShown(), so we know that getParent() is not null.
5318        getParent().requestSendAccessibilityEvent(this, event);
5319    }
5320
5321    /**
5322     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5323     * to its children for adding their text content to the event. Note that the
5324     * event text is populated in a separate dispatch path since we add to the
5325     * event not only the text of the source but also the text of all its descendants.
5326     * A typical implementation will call
5327     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5328     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5329     * on each child. Override this method if custom population of the event text
5330     * content is required.
5331     * <p>
5332     * If an {@link AccessibilityDelegate} has been specified via calling
5333     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5334     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5335     * is responsible for handling this call.
5336     * </p>
5337     * <p>
5338     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5339     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5340     * </p>
5341     *
5342     * @param event The event.
5343     *
5344     * @return True if the event population was completed.
5345     */
5346    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5347        if (mAccessibilityDelegate != null) {
5348            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5349        } else {
5350            return dispatchPopulateAccessibilityEventInternal(event);
5351        }
5352    }
5353
5354    /**
5355     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5356     *
5357     * Note: Called from the default {@link AccessibilityDelegate}.
5358     */
5359    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5360        onPopulateAccessibilityEvent(event);
5361        return false;
5362    }
5363
5364    /**
5365     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5366     * giving a chance to this View to populate the accessibility event with its
5367     * text content. While this method is free to modify event
5368     * attributes other than text content, doing so should normally be performed in
5369     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5370     * <p>
5371     * Example: Adding formatted date string to an accessibility event in addition
5372     *          to the text added by the super implementation:
5373     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5374     *     super.onPopulateAccessibilityEvent(event);
5375     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5376     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5377     *         mCurrentDate.getTimeInMillis(), flags);
5378     *     event.getText().add(selectedDateUtterance);
5379     * }</pre>
5380     * <p>
5381     * If an {@link AccessibilityDelegate} has been specified via calling
5382     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5383     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5384     * is responsible for handling this call.
5385     * </p>
5386     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5387     * information to the event, in case the default implementation has basic information to add.
5388     * </p>
5389     *
5390     * @param event The accessibility event which to populate.
5391     *
5392     * @see #sendAccessibilityEvent(int)
5393     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5394     */
5395    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5396        if (mAccessibilityDelegate != null) {
5397            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5398        } else {
5399            onPopulateAccessibilityEventInternal(event);
5400        }
5401    }
5402
5403    /**
5404     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5405     *
5406     * Note: Called from the default {@link AccessibilityDelegate}.
5407     */
5408    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5409    }
5410
5411    /**
5412     * Initializes an {@link AccessibilityEvent} with information about
5413     * this View which is the event source. In other words, the source of
5414     * an accessibility event is the view whose state change triggered firing
5415     * the event.
5416     * <p>
5417     * Example: Setting the password property of an event in addition
5418     *          to properties set by the super implementation:
5419     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5420     *     super.onInitializeAccessibilityEvent(event);
5421     *     event.setPassword(true);
5422     * }</pre>
5423     * <p>
5424     * If an {@link AccessibilityDelegate} has been specified via calling
5425     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5426     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5427     * is responsible for handling this call.
5428     * </p>
5429     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5430     * information to the event, in case the default implementation has basic information to add.
5431     * </p>
5432     * @param event The event to initialize.
5433     *
5434     * @see #sendAccessibilityEvent(int)
5435     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5436     */
5437    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5438        if (mAccessibilityDelegate != null) {
5439            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5440        } else {
5441            onInitializeAccessibilityEventInternal(event);
5442        }
5443    }
5444
5445    /**
5446     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5447     *
5448     * Note: Called from the default {@link AccessibilityDelegate}.
5449     */
5450    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5451        event.setSource(this);
5452        event.setClassName(View.class.getName());
5453        event.setPackageName(getContext().getPackageName());
5454        event.setEnabled(isEnabled());
5455        event.setContentDescription(mContentDescription);
5456
5457        switch (event.getEventType()) {
5458            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5459                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5460                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5461                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5462                event.setItemCount(focusablesTempList.size());
5463                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5464                if (mAttachInfo != null) {
5465                    focusablesTempList.clear();
5466                }
5467            } break;
5468            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5469                CharSequence text = getIterableTextForAccessibility();
5470                if (text != null && text.length() > 0) {
5471                    event.setFromIndex(getAccessibilitySelectionStart());
5472                    event.setToIndex(getAccessibilitySelectionEnd());
5473                    event.setItemCount(text.length());
5474                }
5475            } break;
5476        }
5477    }
5478
5479    /**
5480     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5481     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5482     * This method is responsible for obtaining an accessibility node info from a
5483     * pool of reusable instances and calling
5484     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5485     * initialize the former.
5486     * <p>
5487     * Note: The client is responsible for recycling the obtained instance by calling
5488     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5489     * </p>
5490     *
5491     * @return A populated {@link AccessibilityNodeInfo}.
5492     *
5493     * @see AccessibilityNodeInfo
5494     */
5495    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5496        if (mAccessibilityDelegate != null) {
5497            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5498        } else {
5499            return createAccessibilityNodeInfoInternal();
5500        }
5501    }
5502
5503    /**
5504     * @see #createAccessibilityNodeInfo()
5505     */
5506    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5507        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5508        if (provider != null) {
5509            return provider.createAccessibilityNodeInfo(View.NO_ID);
5510        } else {
5511            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5512            onInitializeAccessibilityNodeInfo(info);
5513            return info;
5514        }
5515    }
5516
5517    /**
5518     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5519     * The base implementation sets:
5520     * <ul>
5521     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5522     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5523     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5524     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5525     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5526     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5527     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5528     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5529     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5530     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5531     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5532     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5533     * </ul>
5534     * <p>
5535     * Subclasses should override this method, call the super implementation,
5536     * and set additional attributes.
5537     * </p>
5538     * <p>
5539     * If an {@link AccessibilityDelegate} has been specified via calling
5540     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5541     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5542     * is responsible for handling this call.
5543     * </p>
5544     *
5545     * @param info The instance to initialize.
5546     */
5547    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5548        if (mAccessibilityDelegate != null) {
5549            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5550        } else {
5551            onInitializeAccessibilityNodeInfoInternal(info);
5552        }
5553    }
5554
5555    /**
5556     * Gets the location of this view in screen coordintates.
5557     *
5558     * @param outRect The output location
5559     * @hide
5560     */
5561    public void getBoundsOnScreen(Rect outRect) {
5562        if (mAttachInfo == null) {
5563            return;
5564        }
5565
5566        RectF position = mAttachInfo.mTmpTransformRect;
5567        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5568
5569        if (!hasIdentityMatrix()) {
5570            getMatrix().mapRect(position);
5571        }
5572
5573        position.offset(mLeft, mTop);
5574
5575        ViewParent parent = mParent;
5576        while (parent instanceof View) {
5577            View parentView = (View) parent;
5578
5579            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5580
5581            if (!parentView.hasIdentityMatrix()) {
5582                parentView.getMatrix().mapRect(position);
5583            }
5584
5585            position.offset(parentView.mLeft, parentView.mTop);
5586
5587            parent = parentView.mParent;
5588        }
5589
5590        if (parent instanceof ViewRootImpl) {
5591            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5592            position.offset(0, -viewRootImpl.mCurScrollY);
5593        }
5594
5595        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5596
5597        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5598                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5599    }
5600
5601    /**
5602     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5603     *
5604     * Note: Called from the default {@link AccessibilityDelegate}.
5605     */
5606    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5607        Rect bounds = mAttachInfo.mTmpInvalRect;
5608
5609        getDrawingRect(bounds);
5610        info.setBoundsInParent(bounds);
5611
5612        getBoundsOnScreen(bounds);
5613        info.setBoundsInScreen(bounds);
5614
5615        ViewParent parent = getParentForAccessibility();
5616        if (parent instanceof View) {
5617            info.setParent((View) parent);
5618        }
5619
5620        if (mID != View.NO_ID) {
5621            View rootView = getRootView();
5622            if (rootView == null) {
5623                rootView = this;
5624            }
5625
5626            View label = rootView.findLabelForView(this, mID);
5627            if (label != null) {
5628                info.setLabeledBy(label);
5629            }
5630
5631            if ((mAttachInfo.mAccessibilityFetchFlags
5632                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5633                    && Resources.resourceHasPackage(mID)) {
5634                try {
5635                    String viewId = getResources().getResourceName(mID);
5636                    info.setViewIdResourceName(viewId);
5637                } catch (Resources.NotFoundException nfe) {
5638                    /* ignore */
5639                }
5640            }
5641        }
5642
5643        if (mLabelForId != View.NO_ID) {
5644            View rootView = getRootView();
5645            if (rootView == null) {
5646                rootView = this;
5647            }
5648            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5649            if (labeled != null) {
5650                info.setLabelFor(labeled);
5651            }
5652        }
5653
5654        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5655            View rootView = getRootView();
5656            if (rootView == null) {
5657                rootView = this;
5658            }
5659            View next = rootView.findViewInsideOutShouldExist(this,
5660                    mAccessibilityTraversalBeforeId);
5661            if (next != null) {
5662                info.setTraversalBefore(next);
5663            }
5664        }
5665
5666        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5667            View rootView = getRootView();
5668            if (rootView == null) {
5669                rootView = this;
5670            }
5671            View next = rootView.findViewInsideOutShouldExist(this,
5672                    mAccessibilityTraversalAfterId);
5673            if (next != null) {
5674                info.setTraversalAfter(next);
5675            }
5676        }
5677
5678        info.setVisibleToUser(isVisibleToUser());
5679
5680        info.setPackageName(mContext.getPackageName());
5681        info.setClassName(View.class.getName());
5682        info.setContentDescription(getContentDescription());
5683
5684        info.setEnabled(isEnabled());
5685        info.setClickable(isClickable());
5686        info.setFocusable(isFocusable());
5687        info.setFocused(isFocused());
5688        info.setAccessibilityFocused(isAccessibilityFocused());
5689        info.setSelected(isSelected());
5690        info.setLongClickable(isLongClickable());
5691        info.setLiveRegion(getAccessibilityLiveRegion());
5692
5693        // TODO: These make sense only if we are in an AdapterView but all
5694        // views can be selected. Maybe from accessibility perspective
5695        // we should report as selectable view in an AdapterView.
5696        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5697        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5698
5699        if (isFocusable()) {
5700            if (isFocused()) {
5701                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5702            } else {
5703                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5704            }
5705        }
5706
5707        if (!isAccessibilityFocused()) {
5708            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5709        } else {
5710            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5711        }
5712
5713        if (isClickable() && isEnabled()) {
5714            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5715        }
5716
5717        if (isLongClickable() && isEnabled()) {
5718            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5719        }
5720
5721        CharSequence text = getIterableTextForAccessibility();
5722        if (text != null && text.length() > 0) {
5723            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5724
5725            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5726            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5727            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5728            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5729                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5730                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5731        }
5732    }
5733
5734    private View findLabelForView(View view, int labeledId) {
5735        if (mMatchLabelForPredicate == null) {
5736            mMatchLabelForPredicate = new MatchLabelForPredicate();
5737        }
5738        mMatchLabelForPredicate.mLabeledId = labeledId;
5739        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5740    }
5741
5742    /**
5743     * Computes whether this view is visible to the user. Such a view is
5744     * attached, visible, all its predecessors are visible, it is not clipped
5745     * entirely by its predecessors, and has an alpha greater than zero.
5746     *
5747     * @return Whether the view is visible on the screen.
5748     *
5749     * @hide
5750     */
5751    protected boolean isVisibleToUser() {
5752        return isVisibleToUser(null);
5753    }
5754
5755    /**
5756     * Computes whether the given portion of this view is visible to the user.
5757     * Such a view is attached, visible, all its predecessors are visible,
5758     * has an alpha greater than zero, and the specified portion is not
5759     * clipped entirely by its predecessors.
5760     *
5761     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5762     *                    <code>null</code>, and the entire view will be tested in this case.
5763     *                    When <code>true</code> is returned by the function, the actual visible
5764     *                    region will be stored in this parameter; that is, if boundInView is fully
5765     *                    contained within the view, no modification will be made, otherwise regions
5766     *                    outside of the visible area of the view will be clipped.
5767     *
5768     * @return Whether the specified portion of the view is visible on the screen.
5769     *
5770     * @hide
5771     */
5772    protected boolean isVisibleToUser(Rect boundInView) {
5773        if (mAttachInfo != null) {
5774            // Attached to invisible window means this view is not visible.
5775            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5776                return false;
5777            }
5778            // An invisible predecessor or one with alpha zero means
5779            // that this view is not visible to the user.
5780            Object current = this;
5781            while (current instanceof View) {
5782                View view = (View) current;
5783                // We have attach info so this view is attached and there is no
5784                // need to check whether we reach to ViewRootImpl on the way up.
5785                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5786                        view.getVisibility() != VISIBLE) {
5787                    return false;
5788                }
5789                current = view.mParent;
5790            }
5791            // Check if the view is entirely covered by its predecessors.
5792            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5793            Point offset = mAttachInfo.mPoint;
5794            if (!getGlobalVisibleRect(visibleRect, offset)) {
5795                return false;
5796            }
5797            // Check if the visible portion intersects the rectangle of interest.
5798            if (boundInView != null) {
5799                visibleRect.offset(-offset.x, -offset.y);
5800                return boundInView.intersect(visibleRect);
5801            }
5802            return true;
5803        }
5804        return false;
5805    }
5806
5807    /**
5808     * Computes a point on which a sequence of a down/up event can be sent to
5809     * trigger clicking this view. This method is for the exclusive use by the
5810     * accessibility layer to determine where to send a click event in explore
5811     * by touch mode.
5812     *
5813     * @param interactiveRegion The interactive portion of this window.
5814     * @param outPoint The point to populate.
5815     * @return True of such a point exists.
5816     */
5817    boolean computeClickPointInScreenForAccessibility(Region interactiveRegion,
5818            Point outPoint) {
5819        // Since the interactive portion of the view is a region but as a view
5820        // may have a transformation matrix which cannot be applied to a
5821        // region we compute the view bounds rectangle and all interactive
5822        // predecessor's and sibling's (siblings of predecessors included)
5823        // rectangles that intersect the view bounds. At the
5824        // end if the view was partially covered by another interactive
5825        // view we compute the view's interactive region and pick a point
5826        // on its boundary path as regions do not offer APIs to get inner
5827        // points. Note that the the code is optimized to fail early and
5828        // avoid unnecessary allocations plus computations.
5829
5830        // The current approach has edge cases that may produce false
5831        // positives or false negatives. For example, a portion of the
5832        // view may be covered by an interactive descendant of a
5833        // predecessor, which we do not compute. Also a view may be handling
5834        // raw touch events instead registering click listeners, which
5835        // we cannot compute. Despite these limitations this approach will
5836        // work most of the time and it is a huge improvement over just
5837        // blindly sending the down and up events in the center of the
5838        // view.
5839
5840        // Cannot click on an unattached view.
5841        if (mAttachInfo == null) {
5842            return false;
5843        }
5844
5845        // Attached to an invisible window means this view is not visible.
5846        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5847            return false;
5848        }
5849
5850        RectF bounds = mAttachInfo.mTmpTransformRect;
5851        bounds.set(0, 0, getWidth(), getHeight());
5852        List<RectF> intersections = mAttachInfo.mTmpRectList;
5853        intersections.clear();
5854
5855        if (mParent instanceof ViewGroup) {
5856            ViewGroup parentGroup = (ViewGroup) mParent;
5857            if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates(
5858                    this, bounds, intersections)) {
5859                intersections.clear();
5860                return false;
5861            }
5862        }
5863
5864        // Take into account the window location.
5865        final int dx = mAttachInfo.mWindowLeft;
5866        final int dy = mAttachInfo.mWindowTop;
5867        bounds.offset(dx, dy);
5868        offsetRects(intersections, dx, dy);
5869
5870        if (intersections.isEmpty() && interactiveRegion == null) {
5871            outPoint.set((int) bounds.centerX(), (int) bounds.centerY());
5872        } else {
5873            // This view is partially covered by other views, then compute
5874            // the not covered region and pick a point on its boundary.
5875            Region region = new Region();
5876            region.set((int) bounds.left, (int) bounds.top,
5877                    (int) bounds.right, (int) bounds.bottom);
5878
5879            final int intersectionCount = intersections.size();
5880            for (int i = intersectionCount - 1; i >= 0; i--) {
5881                RectF intersection = intersections.remove(i);
5882                region.op((int) intersection.left, (int) intersection.top,
5883                        (int) intersection.right, (int) intersection.bottom,
5884                        Region.Op.DIFFERENCE);
5885            }
5886
5887            // If the view is completely covered, done.
5888            if (region.isEmpty()) {
5889                return false;
5890            }
5891
5892            // Take into account the interactive portion of the window
5893            // as the rest is covered by other windows. If no such a region
5894            // then the whole window is interactive.
5895            if (interactiveRegion != null) {
5896                region.op(interactiveRegion, Region.Op.INTERSECT);
5897            }
5898
5899            // Take into account the window bounds.
5900            final View root = getRootView();
5901            if (root != null) {
5902                region.op(dx, dy, root.getWidth() + dx, root.getHeight() + dy, Region.Op.INTERSECT);
5903            }
5904
5905            // If the view is completely covered, done.
5906            if (region.isEmpty()) {
5907                return false;
5908            }
5909
5910            // Try a shortcut here.
5911            if (region.isRect()) {
5912                Rect regionBounds = mAttachInfo.mTmpInvalRect;
5913                region.getBounds(regionBounds);
5914                outPoint.set(regionBounds.centerX(), regionBounds.centerY());
5915                return true;
5916            }
5917
5918            // Get the a point on the region boundary path.
5919            Path path = region.getBoundaryPath();
5920            PathMeasure pathMeasure = new PathMeasure(path, false);
5921            final float[] coordinates = mAttachInfo.mTmpTransformLocation;
5922
5923            // Without loss of generality pick a point.
5924            final float point = pathMeasure.getLength() * 0.01f;
5925            if (!pathMeasure.getPosTan(point, coordinates, null)) {
5926                return false;
5927            }
5928
5929            outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1]));
5930        }
5931
5932        return true;
5933    }
5934
5935    /**
5936     * Adds the clickable rectangles withing the bounds of this view. They
5937     * may overlap. This method is intended for use only by the accessibility
5938     * layer.
5939     *
5940     * @param outRects List to which to add clickable areas.
5941     */
5942    void addClickableRectsForAccessibility(List<RectF> outRects) {
5943        if (isClickable() || isLongClickable()) {
5944            RectF bounds = new RectF();
5945            bounds.set(0, 0, getWidth(), getHeight());
5946            outRects.add(bounds);
5947        }
5948    }
5949
5950    static void offsetRects(List<RectF> rects, float offsetX, float offsetY) {
5951        final int rectCount = rects.size();
5952        for (int i = 0; i < rectCount; i++) {
5953            RectF intersection = rects.get(i);
5954            intersection.offset(offsetX, offsetY);
5955        }
5956    }
5957
5958    /**
5959     * Returns the delegate for implementing accessibility support via
5960     * composition. For more details see {@link AccessibilityDelegate}.
5961     *
5962     * @return The delegate, or null if none set.
5963     *
5964     * @hide
5965     */
5966    public AccessibilityDelegate getAccessibilityDelegate() {
5967        return mAccessibilityDelegate;
5968    }
5969
5970    /**
5971     * Sets a delegate for implementing accessibility support via composition as
5972     * opposed to inheritance. The delegate's primary use is for implementing
5973     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5974     *
5975     * @param delegate The delegate instance.
5976     *
5977     * @see AccessibilityDelegate
5978     */
5979    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5980        mAccessibilityDelegate = delegate;
5981    }
5982
5983    /**
5984     * Gets the provider for managing a virtual view hierarchy rooted at this View
5985     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5986     * that explore the window content.
5987     * <p>
5988     * If this method returns an instance, this instance is responsible for managing
5989     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5990     * View including the one representing the View itself. Similarly the returned
5991     * instance is responsible for performing accessibility actions on any virtual
5992     * view or the root view itself.
5993     * </p>
5994     * <p>
5995     * If an {@link AccessibilityDelegate} has been specified via calling
5996     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5997     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5998     * is responsible for handling this call.
5999     * </p>
6000     *
6001     * @return The provider.
6002     *
6003     * @see AccessibilityNodeProvider
6004     */
6005    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6006        if (mAccessibilityDelegate != null) {
6007            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6008        } else {
6009            return null;
6010        }
6011    }
6012
6013    /**
6014     * Gets the unique identifier of this view on the screen for accessibility purposes.
6015     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6016     *
6017     * @return The view accessibility id.
6018     *
6019     * @hide
6020     */
6021    public int getAccessibilityViewId() {
6022        if (mAccessibilityViewId == NO_ID) {
6023            mAccessibilityViewId = sNextAccessibilityViewId++;
6024        }
6025        return mAccessibilityViewId;
6026    }
6027
6028    /**
6029     * Gets the unique identifier of the window in which this View reseides.
6030     *
6031     * @return The window accessibility id.
6032     *
6033     * @hide
6034     */
6035    public int getAccessibilityWindowId() {
6036        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6037                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6038    }
6039
6040    /**
6041     * Gets the {@link View} description. It briefly describes the view and is
6042     * primarily used for accessibility support. Set this property to enable
6043     * better accessibility support for your application. This is especially
6044     * true for views that do not have textual representation (For example,
6045     * ImageButton).
6046     *
6047     * @return The content description.
6048     *
6049     * @attr ref android.R.styleable#View_contentDescription
6050     */
6051    @ViewDebug.ExportedProperty(category = "accessibility")
6052    public CharSequence getContentDescription() {
6053        return mContentDescription;
6054    }
6055
6056    /**
6057     * Sets the {@link View} description. It briefly describes the view and is
6058     * primarily used for accessibility support. Set this property to enable
6059     * better accessibility support for your application. This is especially
6060     * true for views that do not have textual representation (For example,
6061     * ImageButton).
6062     *
6063     * @param contentDescription The content description.
6064     *
6065     * @attr ref android.R.styleable#View_contentDescription
6066     */
6067    @RemotableViewMethod
6068    public void setContentDescription(CharSequence contentDescription) {
6069        if (mContentDescription == null) {
6070            if (contentDescription == null) {
6071                return;
6072            }
6073        } else if (mContentDescription.equals(contentDescription)) {
6074            return;
6075        }
6076        mContentDescription = contentDescription;
6077        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6078        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6079            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6080            notifySubtreeAccessibilityStateChangedIfNeeded();
6081        } else {
6082            notifyViewAccessibilityStateChangedIfNeeded(
6083                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6084        }
6085    }
6086
6087    /**
6088     * Sets the id of a view before which this one is visited in accessibility traversal.
6089     * A screen-reader must visit the content of this view before the content of the one
6090     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6091     * will traverse the entire content of B before traversing the entire content of A,
6092     * regardles of what traversal strategy it is using.
6093     * <p>
6094     * Views that do not have specified before/after relationships are traversed in order
6095     * determined by the screen-reader.
6096     * </p>
6097     * <p>
6098     * Setting that this view is before a view that is not important for accessibility
6099     * or if this view is not important for accessibility will have no effect as the
6100     * screen-reader is not aware of unimportant views.
6101     * </p>
6102     *
6103     * @param beforeId The id of a view this one precedes in accessibility traversal.
6104     *
6105     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6106     *
6107     * @see #setImportantForAccessibility(int)
6108     */
6109    @RemotableViewMethod
6110    public void setAccessibilityTraversalBefore(int beforeId) {
6111        if (mAccessibilityTraversalBeforeId == beforeId) {
6112            return;
6113        }
6114        mAccessibilityTraversalBeforeId = beforeId;
6115        notifyViewAccessibilityStateChangedIfNeeded(
6116                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6117    }
6118
6119    /**
6120     * Gets the id of a view before which this one is visited in accessibility traversal.
6121     *
6122     * @return The id of a view this one precedes in accessibility traversal if
6123     *         specified, otherwise {@link #NO_ID}.
6124     *
6125     * @see #setAccessibilityTraversalBefore(int)
6126     */
6127    public int getAccessibilityTraversalBefore() {
6128        return mAccessibilityTraversalBeforeId;
6129    }
6130
6131    /**
6132     * Sets the id of a view after which this one is visited in accessibility traversal.
6133     * A screen-reader must visit the content of the other view before the content of this
6134     * one. For example, if view B is set to be after view A, then a screen-reader
6135     * will traverse the entire content of A before traversing the entire content of B,
6136     * regardles of what traversal strategy it is using.
6137     * <p>
6138     * Views that do not have specified before/after relationships are traversed in order
6139     * determined by the screen-reader.
6140     * </p>
6141     * <p>
6142     * Setting that this view is after a view that is not important for accessibility
6143     * or if this view is not important for accessibility will have no effect as the
6144     * screen-reader is not aware of unimportant views.
6145     * </p>
6146     *
6147     * @param afterId The id of a view this one succedees in accessibility traversal.
6148     *
6149     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6150     *
6151     * @see #setImportantForAccessibility(int)
6152     */
6153    @RemotableViewMethod
6154    public void setAccessibilityTraversalAfter(int afterId) {
6155        if (mAccessibilityTraversalAfterId == afterId) {
6156            return;
6157        }
6158        mAccessibilityTraversalAfterId = afterId;
6159        notifyViewAccessibilityStateChangedIfNeeded(
6160                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6161    }
6162
6163    /**
6164     * Gets the id of a view after which this one is visited in accessibility traversal.
6165     *
6166     * @return The id of a view this one succeedes in accessibility traversal if
6167     *         specified, otherwise {@link #NO_ID}.
6168     *
6169     * @see #setAccessibilityTraversalAfter(int)
6170     */
6171    public int getAccessibilityTraversalAfter() {
6172        return mAccessibilityTraversalAfterId;
6173    }
6174
6175    /**
6176     * Gets the id of a view for which this view serves as a label for
6177     * accessibility purposes.
6178     *
6179     * @return The labeled view id.
6180     */
6181    @ViewDebug.ExportedProperty(category = "accessibility")
6182    public int getLabelFor() {
6183        return mLabelForId;
6184    }
6185
6186    /**
6187     * Sets the id of a view for which this view serves as a label for
6188     * accessibility purposes.
6189     *
6190     * @param id The labeled view id.
6191     */
6192    @RemotableViewMethod
6193    public void setLabelFor(int id) {
6194        if (mLabelForId == id) {
6195            return;
6196        }
6197        mLabelForId = id;
6198        if (mLabelForId != View.NO_ID
6199                && mID == View.NO_ID) {
6200            mID = generateViewId();
6201        }
6202        notifyViewAccessibilityStateChangedIfNeeded(
6203                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6204    }
6205
6206    /**
6207     * Invoked whenever this view loses focus, either by losing window focus or by losing
6208     * focus within its window. This method can be used to clear any state tied to the
6209     * focus. For instance, if a button is held pressed with the trackball and the window
6210     * loses focus, this method can be used to cancel the press.
6211     *
6212     * Subclasses of View overriding this method should always call super.onFocusLost().
6213     *
6214     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6215     * @see #onWindowFocusChanged(boolean)
6216     *
6217     * @hide pending API council approval
6218     */
6219    protected void onFocusLost() {
6220        resetPressedState();
6221    }
6222
6223    private void resetPressedState() {
6224        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6225            return;
6226        }
6227
6228        if (isPressed()) {
6229            setPressed(false);
6230
6231            if (!mHasPerformedLongPress) {
6232                removeLongPressCallback();
6233            }
6234        }
6235    }
6236
6237    /**
6238     * Returns true if this view has focus
6239     *
6240     * @return True if this view has focus, false otherwise.
6241     */
6242    @ViewDebug.ExportedProperty(category = "focus")
6243    public boolean isFocused() {
6244        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6245    }
6246
6247    /**
6248     * Find the view in the hierarchy rooted at this view that currently has
6249     * focus.
6250     *
6251     * @return The view that currently has focus, or null if no focused view can
6252     *         be found.
6253     */
6254    public View findFocus() {
6255        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6256    }
6257
6258    /**
6259     * Indicates whether this view is one of the set of scrollable containers in
6260     * its window.
6261     *
6262     * @return whether this view is one of the set of scrollable containers in
6263     * its window
6264     *
6265     * @attr ref android.R.styleable#View_isScrollContainer
6266     */
6267    public boolean isScrollContainer() {
6268        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6269    }
6270
6271    /**
6272     * Change whether this view is one of the set of scrollable containers in
6273     * its window.  This will be used to determine whether the window can
6274     * resize or must pan when a soft input area is open -- scrollable
6275     * containers allow the window to use resize mode since the container
6276     * will appropriately shrink.
6277     *
6278     * @attr ref android.R.styleable#View_isScrollContainer
6279     */
6280    public void setScrollContainer(boolean isScrollContainer) {
6281        if (isScrollContainer) {
6282            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6283                mAttachInfo.mScrollContainers.add(this);
6284                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6285            }
6286            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6287        } else {
6288            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6289                mAttachInfo.mScrollContainers.remove(this);
6290            }
6291            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6292        }
6293    }
6294
6295    /**
6296     * Returns the quality of the drawing cache.
6297     *
6298     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6299     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6300     *
6301     * @see #setDrawingCacheQuality(int)
6302     * @see #setDrawingCacheEnabled(boolean)
6303     * @see #isDrawingCacheEnabled()
6304     *
6305     * @attr ref android.R.styleable#View_drawingCacheQuality
6306     */
6307    @DrawingCacheQuality
6308    public int getDrawingCacheQuality() {
6309        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6310    }
6311
6312    /**
6313     * Set the drawing cache quality of this view. This value is used only when the
6314     * drawing cache is enabled
6315     *
6316     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6317     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6318     *
6319     * @see #getDrawingCacheQuality()
6320     * @see #setDrawingCacheEnabled(boolean)
6321     * @see #isDrawingCacheEnabled()
6322     *
6323     * @attr ref android.R.styleable#View_drawingCacheQuality
6324     */
6325    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6326        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6327    }
6328
6329    /**
6330     * Returns whether the screen should remain on, corresponding to the current
6331     * value of {@link #KEEP_SCREEN_ON}.
6332     *
6333     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6334     *
6335     * @see #setKeepScreenOn(boolean)
6336     *
6337     * @attr ref android.R.styleable#View_keepScreenOn
6338     */
6339    public boolean getKeepScreenOn() {
6340        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6341    }
6342
6343    /**
6344     * Controls whether the screen should remain on, modifying the
6345     * value of {@link #KEEP_SCREEN_ON}.
6346     *
6347     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6348     *
6349     * @see #getKeepScreenOn()
6350     *
6351     * @attr ref android.R.styleable#View_keepScreenOn
6352     */
6353    public void setKeepScreenOn(boolean keepScreenOn) {
6354        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6355    }
6356
6357    /**
6358     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6359     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6360     *
6361     * @attr ref android.R.styleable#View_nextFocusLeft
6362     */
6363    public int getNextFocusLeftId() {
6364        return mNextFocusLeftId;
6365    }
6366
6367    /**
6368     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6369     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6370     * decide automatically.
6371     *
6372     * @attr ref android.R.styleable#View_nextFocusLeft
6373     */
6374    public void setNextFocusLeftId(int nextFocusLeftId) {
6375        mNextFocusLeftId = nextFocusLeftId;
6376    }
6377
6378    /**
6379     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6380     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6381     *
6382     * @attr ref android.R.styleable#View_nextFocusRight
6383     */
6384    public int getNextFocusRightId() {
6385        return mNextFocusRightId;
6386    }
6387
6388    /**
6389     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6390     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6391     * decide automatically.
6392     *
6393     * @attr ref android.R.styleable#View_nextFocusRight
6394     */
6395    public void setNextFocusRightId(int nextFocusRightId) {
6396        mNextFocusRightId = nextFocusRightId;
6397    }
6398
6399    /**
6400     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6401     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6402     *
6403     * @attr ref android.R.styleable#View_nextFocusUp
6404     */
6405    public int getNextFocusUpId() {
6406        return mNextFocusUpId;
6407    }
6408
6409    /**
6410     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6411     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6412     * decide automatically.
6413     *
6414     * @attr ref android.R.styleable#View_nextFocusUp
6415     */
6416    public void setNextFocusUpId(int nextFocusUpId) {
6417        mNextFocusUpId = nextFocusUpId;
6418    }
6419
6420    /**
6421     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6422     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6423     *
6424     * @attr ref android.R.styleable#View_nextFocusDown
6425     */
6426    public int getNextFocusDownId() {
6427        return mNextFocusDownId;
6428    }
6429
6430    /**
6431     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6432     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6433     * decide automatically.
6434     *
6435     * @attr ref android.R.styleable#View_nextFocusDown
6436     */
6437    public void setNextFocusDownId(int nextFocusDownId) {
6438        mNextFocusDownId = nextFocusDownId;
6439    }
6440
6441    /**
6442     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6443     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6444     *
6445     * @attr ref android.R.styleable#View_nextFocusForward
6446     */
6447    public int getNextFocusForwardId() {
6448        return mNextFocusForwardId;
6449    }
6450
6451    /**
6452     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6453     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6454     * decide automatically.
6455     *
6456     * @attr ref android.R.styleable#View_nextFocusForward
6457     */
6458    public void setNextFocusForwardId(int nextFocusForwardId) {
6459        mNextFocusForwardId = nextFocusForwardId;
6460    }
6461
6462    /**
6463     * Returns the visibility of this view and all of its ancestors
6464     *
6465     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6466     */
6467    public boolean isShown() {
6468        View current = this;
6469        //noinspection ConstantConditions
6470        do {
6471            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6472                return false;
6473            }
6474            ViewParent parent = current.mParent;
6475            if (parent == null) {
6476                return false; // We are not attached to the view root
6477            }
6478            if (!(parent instanceof View)) {
6479                return true;
6480            }
6481            current = (View) parent;
6482        } while (current != null);
6483
6484        return false;
6485    }
6486
6487    /**
6488     * Called by the view hierarchy when the content insets for a window have
6489     * changed, to allow it to adjust its content to fit within those windows.
6490     * The content insets tell you the space that the status bar, input method,
6491     * and other system windows infringe on the application's window.
6492     *
6493     * <p>You do not normally need to deal with this function, since the default
6494     * window decoration given to applications takes care of applying it to the
6495     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6496     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6497     * and your content can be placed under those system elements.  You can then
6498     * use this method within your view hierarchy if you have parts of your UI
6499     * which you would like to ensure are not being covered.
6500     *
6501     * <p>The default implementation of this method simply applies the content
6502     * insets to the view's padding, consuming that content (modifying the
6503     * insets to be 0), and returning true.  This behavior is off by default, but can
6504     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6505     *
6506     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6507     * insets object is propagated down the hierarchy, so any changes made to it will
6508     * be seen by all following views (including potentially ones above in
6509     * the hierarchy since this is a depth-first traversal).  The first view
6510     * that returns true will abort the entire traversal.
6511     *
6512     * <p>The default implementation works well for a situation where it is
6513     * used with a container that covers the entire window, allowing it to
6514     * apply the appropriate insets to its content on all edges.  If you need
6515     * a more complicated layout (such as two different views fitting system
6516     * windows, one on the top of the window, and one on the bottom),
6517     * you can override the method and handle the insets however you would like.
6518     * Note that the insets provided by the framework are always relative to the
6519     * far edges of the window, not accounting for the location of the called view
6520     * within that window.  (In fact when this method is called you do not yet know
6521     * where the layout will place the view, as it is done before layout happens.)
6522     *
6523     * <p>Note: unlike many View methods, there is no dispatch phase to this
6524     * call.  If you are overriding it in a ViewGroup and want to allow the
6525     * call to continue to your children, you must be sure to call the super
6526     * implementation.
6527     *
6528     * <p>Here is a sample layout that makes use of fitting system windows
6529     * to have controls for a video view placed inside of the window decorations
6530     * that it hides and shows.  This can be used with code like the second
6531     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6532     *
6533     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6534     *
6535     * @param insets Current content insets of the window.  Prior to
6536     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6537     * the insets or else you and Android will be unhappy.
6538     *
6539     * @return {@code true} if this view applied the insets and it should not
6540     * continue propagating further down the hierarchy, {@code false} otherwise.
6541     * @see #getFitsSystemWindows()
6542     * @see #setFitsSystemWindows(boolean)
6543     * @see #setSystemUiVisibility(int)
6544     *
6545     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6546     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6547     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6548     * to implement handling their own insets.
6549     */
6550    protected boolean fitSystemWindows(Rect insets) {
6551        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6552            if (insets == null) {
6553                // Null insets by definition have already been consumed.
6554                // This call cannot apply insets since there are none to apply,
6555                // so return false.
6556                return false;
6557            }
6558            // If we're not in the process of dispatching the newer apply insets call,
6559            // that means we're not in the compatibility path. Dispatch into the newer
6560            // apply insets path and take things from there.
6561            try {
6562                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6563                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6564            } finally {
6565                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6566            }
6567        } else {
6568            // We're being called from the newer apply insets path.
6569            // Perform the standard fallback behavior.
6570            return fitSystemWindowsInt(insets);
6571        }
6572    }
6573
6574    private boolean fitSystemWindowsInt(Rect insets) {
6575        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6576            mUserPaddingStart = UNDEFINED_PADDING;
6577            mUserPaddingEnd = UNDEFINED_PADDING;
6578            Rect localInsets = sThreadLocal.get();
6579            if (localInsets == null) {
6580                localInsets = new Rect();
6581                sThreadLocal.set(localInsets);
6582            }
6583            boolean res = computeFitSystemWindows(insets, localInsets);
6584            mUserPaddingLeftInitial = localInsets.left;
6585            mUserPaddingRightInitial = localInsets.right;
6586            internalSetPadding(localInsets.left, localInsets.top,
6587                    localInsets.right, localInsets.bottom);
6588            return res;
6589        }
6590        return false;
6591    }
6592
6593    /**
6594     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6595     *
6596     * <p>This method should be overridden by views that wish to apply a policy different from or
6597     * in addition to the default behavior. Clients that wish to force a view subtree
6598     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6599     *
6600     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6601     * it will be called during dispatch instead of this method. The listener may optionally
6602     * call this method from its own implementation if it wishes to apply the view's default
6603     * insets policy in addition to its own.</p>
6604     *
6605     * <p>Implementations of this method should either return the insets parameter unchanged
6606     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6607     * that this view applied itself. This allows new inset types added in future platform
6608     * versions to pass through existing implementations unchanged without being erroneously
6609     * consumed.</p>
6610     *
6611     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6612     * property is set then the view will consume the system window insets and apply them
6613     * as padding for the view.</p>
6614     *
6615     * @param insets Insets to apply
6616     * @return The supplied insets with any applied insets consumed
6617     */
6618    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6619        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6620            // We weren't called from within a direct call to fitSystemWindows,
6621            // call into it as a fallback in case we're in a class that overrides it
6622            // and has logic to perform.
6623            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6624                return insets.consumeSystemWindowInsets();
6625            }
6626        } else {
6627            // We were called from within a direct call to fitSystemWindows.
6628            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6629                return insets.consumeSystemWindowInsets();
6630            }
6631        }
6632        return insets;
6633    }
6634
6635    /**
6636     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6637     * window insets to this view. The listener's
6638     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6639     * method will be called instead of the view's
6640     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6641     *
6642     * @param listener Listener to set
6643     *
6644     * @see #onApplyWindowInsets(WindowInsets)
6645     */
6646    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6647        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6648    }
6649
6650    /**
6651     * Request to apply the given window insets to this view or another view in its subtree.
6652     *
6653     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6654     * obscured by window decorations or overlays. This can include the status and navigation bars,
6655     * action bars, input methods and more. New inset categories may be added in the future.
6656     * The method returns the insets provided minus any that were applied by this view or its
6657     * children.</p>
6658     *
6659     * <p>Clients wishing to provide custom behavior should override the
6660     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6661     * {@link OnApplyWindowInsetsListener} via the
6662     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6663     * method.</p>
6664     *
6665     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6666     * </p>
6667     *
6668     * @param insets Insets to apply
6669     * @return The provided insets minus the insets that were consumed
6670     */
6671    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6672        try {
6673            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6674            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6675                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6676            } else {
6677                return onApplyWindowInsets(insets);
6678            }
6679        } finally {
6680            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6681        }
6682    }
6683
6684    /**
6685     * @hide Compute the insets that should be consumed by this view and the ones
6686     * that should propagate to those under it.
6687     */
6688    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6689        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6690                || mAttachInfo == null
6691                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6692                        && !mAttachInfo.mOverscanRequested)) {
6693            outLocalInsets.set(inoutInsets);
6694            inoutInsets.set(0, 0, 0, 0);
6695            return true;
6696        } else {
6697            // The application wants to take care of fitting system window for
6698            // the content...  however we still need to take care of any overscan here.
6699            final Rect overscan = mAttachInfo.mOverscanInsets;
6700            outLocalInsets.set(overscan);
6701            inoutInsets.left -= overscan.left;
6702            inoutInsets.top -= overscan.top;
6703            inoutInsets.right -= overscan.right;
6704            inoutInsets.bottom -= overscan.bottom;
6705            return false;
6706        }
6707    }
6708
6709    /**
6710     * Compute insets that should be consumed by this view and the ones that should propagate
6711     * to those under it.
6712     *
6713     * @param in Insets currently being processed by this View, likely received as a parameter
6714     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6715     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6716     *                       by this view
6717     * @return Insets that should be passed along to views under this one
6718     */
6719    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6720        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6721                || mAttachInfo == null
6722                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6723            outLocalInsets.set(in.getSystemWindowInsets());
6724            return in.consumeSystemWindowInsets();
6725        } else {
6726            outLocalInsets.set(0, 0, 0, 0);
6727            return in;
6728        }
6729    }
6730
6731    /**
6732     * Sets whether or not this view should account for system screen decorations
6733     * such as the status bar and inset its content; that is, controlling whether
6734     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6735     * executed.  See that method for more details.
6736     *
6737     * <p>Note that if you are providing your own implementation of
6738     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6739     * flag to true -- your implementation will be overriding the default
6740     * implementation that checks this flag.
6741     *
6742     * @param fitSystemWindows If true, then the default implementation of
6743     * {@link #fitSystemWindows(Rect)} will be executed.
6744     *
6745     * @attr ref android.R.styleable#View_fitsSystemWindows
6746     * @see #getFitsSystemWindows()
6747     * @see #fitSystemWindows(Rect)
6748     * @see #setSystemUiVisibility(int)
6749     */
6750    public void setFitsSystemWindows(boolean fitSystemWindows) {
6751        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6752    }
6753
6754    /**
6755     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6756     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6757     * will be executed.
6758     *
6759     * @return {@code true} if the default implementation of
6760     * {@link #fitSystemWindows(Rect)} will be executed.
6761     *
6762     * @attr ref android.R.styleable#View_fitsSystemWindows
6763     * @see #setFitsSystemWindows(boolean)
6764     * @see #fitSystemWindows(Rect)
6765     * @see #setSystemUiVisibility(int)
6766     */
6767    @ViewDebug.ExportedProperty
6768    public boolean getFitsSystemWindows() {
6769        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6770    }
6771
6772    /** @hide */
6773    public boolean fitsSystemWindows() {
6774        return getFitsSystemWindows();
6775    }
6776
6777    /**
6778     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6779     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6780     */
6781    public void requestFitSystemWindows() {
6782        if (mParent != null) {
6783            mParent.requestFitSystemWindows();
6784        }
6785    }
6786
6787    /**
6788     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6789     */
6790    public void requestApplyInsets() {
6791        requestFitSystemWindows();
6792    }
6793
6794    /**
6795     * For use by PhoneWindow to make its own system window fitting optional.
6796     * @hide
6797     */
6798    public void makeOptionalFitsSystemWindows() {
6799        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6800    }
6801
6802    /**
6803     * Returns the visibility status for this view.
6804     *
6805     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6806     * @attr ref android.R.styleable#View_visibility
6807     */
6808    @ViewDebug.ExportedProperty(mapping = {
6809        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6810        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6811        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6812    })
6813    @Visibility
6814    public int getVisibility() {
6815        return mViewFlags & VISIBILITY_MASK;
6816    }
6817
6818    /**
6819     * Set the enabled state of this view.
6820     *
6821     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6822     * @attr ref android.R.styleable#View_visibility
6823     */
6824    @RemotableViewMethod
6825    public void setVisibility(@Visibility int visibility) {
6826        setFlags(visibility, VISIBILITY_MASK);
6827        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6828    }
6829
6830    /**
6831     * Returns the enabled status for this view. The interpretation of the
6832     * enabled state varies by subclass.
6833     *
6834     * @return True if this view is enabled, false otherwise.
6835     */
6836    @ViewDebug.ExportedProperty
6837    public boolean isEnabled() {
6838        return (mViewFlags & ENABLED_MASK) == ENABLED;
6839    }
6840
6841    /**
6842     * Set the enabled state of this view. The interpretation of the enabled
6843     * state varies by subclass.
6844     *
6845     * @param enabled True if this view is enabled, false otherwise.
6846     */
6847    @RemotableViewMethod
6848    public void setEnabled(boolean enabled) {
6849        if (enabled == isEnabled()) return;
6850
6851        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6852
6853        /*
6854         * The View most likely has to change its appearance, so refresh
6855         * the drawable state.
6856         */
6857        refreshDrawableState();
6858
6859        // Invalidate too, since the default behavior for views is to be
6860        // be drawn at 50% alpha rather than to change the drawable.
6861        invalidate(true);
6862
6863        if (!enabled) {
6864            cancelPendingInputEvents();
6865        }
6866    }
6867
6868    /**
6869     * Set whether this view can receive the focus.
6870     *
6871     * Setting this to false will also ensure that this view is not focusable
6872     * in touch mode.
6873     *
6874     * @param focusable If true, this view can receive the focus.
6875     *
6876     * @see #setFocusableInTouchMode(boolean)
6877     * @attr ref android.R.styleable#View_focusable
6878     */
6879    public void setFocusable(boolean focusable) {
6880        if (!focusable) {
6881            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6882        }
6883        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6884    }
6885
6886    /**
6887     * Set whether this view can receive focus while in touch mode.
6888     *
6889     * Setting this to true will also ensure that this view is focusable.
6890     *
6891     * @param focusableInTouchMode If true, this view can receive the focus while
6892     *   in touch mode.
6893     *
6894     * @see #setFocusable(boolean)
6895     * @attr ref android.R.styleable#View_focusableInTouchMode
6896     */
6897    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6898        // Focusable in touch mode should always be set before the focusable flag
6899        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6900        // which, in touch mode, will not successfully request focus on this view
6901        // because the focusable in touch mode flag is not set
6902        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6903        if (focusableInTouchMode) {
6904            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6905        }
6906    }
6907
6908    /**
6909     * Set whether this view should have sound effects enabled for events such as
6910     * clicking and touching.
6911     *
6912     * <p>You may wish to disable sound effects for a view if you already play sounds,
6913     * for instance, a dial key that plays dtmf tones.
6914     *
6915     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6916     * @see #isSoundEffectsEnabled()
6917     * @see #playSoundEffect(int)
6918     * @attr ref android.R.styleable#View_soundEffectsEnabled
6919     */
6920    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6921        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6922    }
6923
6924    /**
6925     * @return whether this view should have sound effects enabled for events such as
6926     *     clicking and touching.
6927     *
6928     * @see #setSoundEffectsEnabled(boolean)
6929     * @see #playSoundEffect(int)
6930     * @attr ref android.R.styleable#View_soundEffectsEnabled
6931     */
6932    @ViewDebug.ExportedProperty
6933    public boolean isSoundEffectsEnabled() {
6934        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6935    }
6936
6937    /**
6938     * Set whether this view should have haptic feedback for events such as
6939     * long presses.
6940     *
6941     * <p>You may wish to disable haptic feedback if your view already controls
6942     * its own haptic feedback.
6943     *
6944     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6945     * @see #isHapticFeedbackEnabled()
6946     * @see #performHapticFeedback(int)
6947     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6948     */
6949    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6950        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6951    }
6952
6953    /**
6954     * @return whether this view should have haptic feedback enabled for events
6955     * long presses.
6956     *
6957     * @see #setHapticFeedbackEnabled(boolean)
6958     * @see #performHapticFeedback(int)
6959     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6960     */
6961    @ViewDebug.ExportedProperty
6962    public boolean isHapticFeedbackEnabled() {
6963        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6964    }
6965
6966    /**
6967     * Returns the layout direction for this view.
6968     *
6969     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6970     *   {@link #LAYOUT_DIRECTION_RTL},
6971     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6972     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6973     *
6974     * @attr ref android.R.styleable#View_layoutDirection
6975     *
6976     * @hide
6977     */
6978    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6979        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6980        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6981        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6982        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6983    })
6984    @LayoutDir
6985    public int getRawLayoutDirection() {
6986        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6987    }
6988
6989    /**
6990     * Set the layout direction for this view. This will propagate a reset of layout direction
6991     * resolution to the view's children and resolve layout direction for this view.
6992     *
6993     * @param layoutDirection the layout direction to set. Should be one of:
6994     *
6995     * {@link #LAYOUT_DIRECTION_LTR},
6996     * {@link #LAYOUT_DIRECTION_RTL},
6997     * {@link #LAYOUT_DIRECTION_INHERIT},
6998     * {@link #LAYOUT_DIRECTION_LOCALE}.
6999     *
7000     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7001     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7002     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7003     *
7004     * @attr ref android.R.styleable#View_layoutDirection
7005     */
7006    @RemotableViewMethod
7007    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7008        if (getRawLayoutDirection() != layoutDirection) {
7009            // Reset the current layout direction and the resolved one
7010            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7011            resetRtlProperties();
7012            // Set the new layout direction (filtered)
7013            mPrivateFlags2 |=
7014                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7015            // We need to resolve all RTL properties as they all depend on layout direction
7016            resolveRtlPropertiesIfNeeded();
7017            requestLayout();
7018            invalidate(true);
7019        }
7020    }
7021
7022    /**
7023     * Returns the resolved layout direction for this view.
7024     *
7025     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7026     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7027     *
7028     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7029     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7030     *
7031     * @attr ref android.R.styleable#View_layoutDirection
7032     */
7033    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7034        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7035        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7036    })
7037    @ResolvedLayoutDir
7038    public int getLayoutDirection() {
7039        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7040        if (targetSdkVersion < JELLY_BEAN_MR1) {
7041            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7042            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7043        }
7044        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7045                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7046    }
7047
7048    /**
7049     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7050     * layout attribute and/or the inherited value from the parent
7051     *
7052     * @return true if the layout is right-to-left.
7053     *
7054     * @hide
7055     */
7056    @ViewDebug.ExportedProperty(category = "layout")
7057    public boolean isLayoutRtl() {
7058        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7059    }
7060
7061    /**
7062     * Indicates whether the view is currently tracking transient state that the
7063     * app should not need to concern itself with saving and restoring, but that
7064     * the framework should take special note to preserve when possible.
7065     *
7066     * <p>A view with transient state cannot be trivially rebound from an external
7067     * data source, such as an adapter binding item views in a list. This may be
7068     * because the view is performing an animation, tracking user selection
7069     * of content, or similar.</p>
7070     *
7071     * @return true if the view has transient state
7072     */
7073    @ViewDebug.ExportedProperty(category = "layout")
7074    public boolean hasTransientState() {
7075        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7076    }
7077
7078    /**
7079     * Set whether this view is currently tracking transient state that the
7080     * framework should attempt to preserve when possible. This flag is reference counted,
7081     * so every call to setHasTransientState(true) should be paired with a later call
7082     * to setHasTransientState(false).
7083     *
7084     * <p>A view with transient state cannot be trivially rebound from an external
7085     * data source, such as an adapter binding item views in a list. This may be
7086     * because the view is performing an animation, tracking user selection
7087     * of content, or similar.</p>
7088     *
7089     * @param hasTransientState true if this view has transient state
7090     */
7091    public void setHasTransientState(boolean hasTransientState) {
7092        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7093                mTransientStateCount - 1;
7094        if (mTransientStateCount < 0) {
7095            mTransientStateCount = 0;
7096            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7097                    "unmatched pair of setHasTransientState calls");
7098        } else if ((hasTransientState && mTransientStateCount == 1) ||
7099                (!hasTransientState && mTransientStateCount == 0)) {
7100            // update flag if we've just incremented up from 0 or decremented down to 0
7101            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7102                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7103            if (mParent != null) {
7104                try {
7105                    mParent.childHasTransientStateChanged(this, hasTransientState);
7106                } catch (AbstractMethodError e) {
7107                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7108                            " does not fully implement ViewParent", e);
7109                }
7110            }
7111        }
7112    }
7113
7114    /**
7115     * Returns true if this view is currently attached to a window.
7116     */
7117    public boolean isAttachedToWindow() {
7118        return mAttachInfo != null;
7119    }
7120
7121    /**
7122     * Returns true if this view has been through at least one layout since it
7123     * was last attached to or detached from a window.
7124     */
7125    public boolean isLaidOut() {
7126        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7127    }
7128
7129    /**
7130     * If this view doesn't do any drawing on its own, set this flag to
7131     * allow further optimizations. By default, this flag is not set on
7132     * View, but could be set on some View subclasses such as ViewGroup.
7133     *
7134     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7135     * you should clear this flag.
7136     *
7137     * @param willNotDraw whether or not this View draw on its own
7138     */
7139    public void setWillNotDraw(boolean willNotDraw) {
7140        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7141    }
7142
7143    /**
7144     * Returns whether or not this View draws on its own.
7145     *
7146     * @return true if this view has nothing to draw, false otherwise
7147     */
7148    @ViewDebug.ExportedProperty(category = "drawing")
7149    public boolean willNotDraw() {
7150        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7151    }
7152
7153    /**
7154     * When a View's drawing cache is enabled, drawing is redirected to an
7155     * offscreen bitmap. Some views, like an ImageView, must be able to
7156     * bypass this mechanism if they already draw a single bitmap, to avoid
7157     * unnecessary usage of the memory.
7158     *
7159     * @param willNotCacheDrawing true if this view does not cache its
7160     *        drawing, false otherwise
7161     */
7162    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7163        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7164    }
7165
7166    /**
7167     * Returns whether or not this View can cache its drawing or not.
7168     *
7169     * @return true if this view does not cache its drawing, false otherwise
7170     */
7171    @ViewDebug.ExportedProperty(category = "drawing")
7172    public boolean willNotCacheDrawing() {
7173        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7174    }
7175
7176    /**
7177     * Indicates whether this view reacts to click events or not.
7178     *
7179     * @return true if the view is clickable, false otherwise
7180     *
7181     * @see #setClickable(boolean)
7182     * @attr ref android.R.styleable#View_clickable
7183     */
7184    @ViewDebug.ExportedProperty
7185    public boolean isClickable() {
7186        return (mViewFlags & CLICKABLE) == CLICKABLE;
7187    }
7188
7189    /**
7190     * Enables or disables click events for this view. When a view
7191     * is clickable it will change its state to "pressed" on every click.
7192     * Subclasses should set the view clickable to visually react to
7193     * user's clicks.
7194     *
7195     * @param clickable true to make the view clickable, false otherwise
7196     *
7197     * @see #isClickable()
7198     * @attr ref android.R.styleable#View_clickable
7199     */
7200    public void setClickable(boolean clickable) {
7201        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7202    }
7203
7204    /**
7205     * Indicates whether this view reacts to long click events or not.
7206     *
7207     * @return true if the view is long clickable, false otherwise
7208     *
7209     * @see #setLongClickable(boolean)
7210     * @attr ref android.R.styleable#View_longClickable
7211     */
7212    public boolean isLongClickable() {
7213        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7214    }
7215
7216    /**
7217     * Enables or disables long click events for this view. When a view is long
7218     * clickable it reacts to the user holding down the button for a longer
7219     * duration than a tap. This event can either launch the listener or a
7220     * context menu.
7221     *
7222     * @param longClickable true to make the view long clickable, false otherwise
7223     * @see #isLongClickable()
7224     * @attr ref android.R.styleable#View_longClickable
7225     */
7226    public void setLongClickable(boolean longClickable) {
7227        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7228    }
7229
7230    /**
7231     * Sets the pressed state for this view and provides a touch coordinate for
7232     * animation hinting.
7233     *
7234     * @param pressed Pass true to set the View's internal state to "pressed",
7235     *            or false to reverts the View's internal state from a
7236     *            previously set "pressed" state.
7237     * @param x The x coordinate of the touch that caused the press
7238     * @param y The y coordinate of the touch that caused the press
7239     */
7240    private void setPressed(boolean pressed, float x, float y) {
7241        if (pressed) {
7242            drawableHotspotChanged(x, y);
7243        }
7244
7245        setPressed(pressed);
7246    }
7247
7248    /**
7249     * Sets the pressed state for this view.
7250     *
7251     * @see #isClickable()
7252     * @see #setClickable(boolean)
7253     *
7254     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7255     *        the View's internal state from a previously set "pressed" state.
7256     */
7257    public void setPressed(boolean pressed) {
7258        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7259
7260        if (pressed) {
7261            mPrivateFlags |= PFLAG_PRESSED;
7262        } else {
7263            mPrivateFlags &= ~PFLAG_PRESSED;
7264        }
7265
7266        if (needsRefresh) {
7267            refreshDrawableState();
7268        }
7269        dispatchSetPressed(pressed);
7270    }
7271
7272    /**
7273     * Dispatch setPressed to all of this View's children.
7274     *
7275     * @see #setPressed(boolean)
7276     *
7277     * @param pressed The new pressed state
7278     */
7279    protected void dispatchSetPressed(boolean pressed) {
7280    }
7281
7282    /**
7283     * Indicates whether the view is currently in pressed state. Unless
7284     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7285     * the pressed state.
7286     *
7287     * @see #setPressed(boolean)
7288     * @see #isClickable()
7289     * @see #setClickable(boolean)
7290     *
7291     * @return true if the view is currently pressed, false otherwise
7292     */
7293    @ViewDebug.ExportedProperty
7294    public boolean isPressed() {
7295        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7296    }
7297
7298    /**
7299     * Indicates whether this view will save its state (that is,
7300     * whether its {@link #onSaveInstanceState} method will be called).
7301     *
7302     * @return Returns true if the view state saving is enabled, else false.
7303     *
7304     * @see #setSaveEnabled(boolean)
7305     * @attr ref android.R.styleable#View_saveEnabled
7306     */
7307    public boolean isSaveEnabled() {
7308        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7309    }
7310
7311    /**
7312     * Controls whether the saving of this view's state is
7313     * enabled (that is, whether its {@link #onSaveInstanceState} method
7314     * will be called).  Note that even if freezing is enabled, the
7315     * view still must have an id assigned to it (via {@link #setId(int)})
7316     * for its state to be saved.  This flag can only disable the
7317     * saving of this view; any child views may still have their state saved.
7318     *
7319     * @param enabled Set to false to <em>disable</em> state saving, or true
7320     * (the default) to allow it.
7321     *
7322     * @see #isSaveEnabled()
7323     * @see #setId(int)
7324     * @see #onSaveInstanceState()
7325     * @attr ref android.R.styleable#View_saveEnabled
7326     */
7327    public void setSaveEnabled(boolean enabled) {
7328        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7329    }
7330
7331    /**
7332     * Gets whether the framework should discard touches when the view's
7333     * window is obscured by another visible window.
7334     * Refer to the {@link View} security documentation for more details.
7335     *
7336     * @return True if touch filtering is enabled.
7337     *
7338     * @see #setFilterTouchesWhenObscured(boolean)
7339     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7340     */
7341    @ViewDebug.ExportedProperty
7342    public boolean getFilterTouchesWhenObscured() {
7343        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7344    }
7345
7346    /**
7347     * Sets whether the framework should discard touches when the view's
7348     * window is obscured by another visible window.
7349     * Refer to the {@link View} security documentation for more details.
7350     *
7351     * @param enabled True if touch filtering should be enabled.
7352     *
7353     * @see #getFilterTouchesWhenObscured
7354     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7355     */
7356    public void setFilterTouchesWhenObscured(boolean enabled) {
7357        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7358                FILTER_TOUCHES_WHEN_OBSCURED);
7359    }
7360
7361    /**
7362     * Indicates whether the entire hierarchy under this view will save its
7363     * state when a state saving traversal occurs from its parent.  The default
7364     * is true; if false, these views will not be saved unless
7365     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7366     *
7367     * @return Returns true if the view state saving from parent is enabled, else false.
7368     *
7369     * @see #setSaveFromParentEnabled(boolean)
7370     */
7371    public boolean isSaveFromParentEnabled() {
7372        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7373    }
7374
7375    /**
7376     * Controls whether the entire hierarchy under this view will save its
7377     * state when a state saving traversal occurs from its parent.  The default
7378     * is true; if false, these views will not be saved unless
7379     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7380     *
7381     * @param enabled Set to false to <em>disable</em> state saving, or true
7382     * (the default) to allow it.
7383     *
7384     * @see #isSaveFromParentEnabled()
7385     * @see #setId(int)
7386     * @see #onSaveInstanceState()
7387     */
7388    public void setSaveFromParentEnabled(boolean enabled) {
7389        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7390    }
7391
7392
7393    /**
7394     * Returns whether this View is able to take focus.
7395     *
7396     * @return True if this view can take focus, or false otherwise.
7397     * @attr ref android.R.styleable#View_focusable
7398     */
7399    @ViewDebug.ExportedProperty(category = "focus")
7400    public final boolean isFocusable() {
7401        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7402    }
7403
7404    /**
7405     * When a view is focusable, it may not want to take focus when in touch mode.
7406     * For example, a button would like focus when the user is navigating via a D-pad
7407     * so that the user can click on it, but once the user starts touching the screen,
7408     * the button shouldn't take focus
7409     * @return Whether the view is focusable in touch mode.
7410     * @attr ref android.R.styleable#View_focusableInTouchMode
7411     */
7412    @ViewDebug.ExportedProperty
7413    public final boolean isFocusableInTouchMode() {
7414        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7415    }
7416
7417    /**
7418     * Find the nearest view in the specified direction that can take focus.
7419     * This does not actually give focus to that view.
7420     *
7421     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7422     *
7423     * @return The nearest focusable in the specified direction, or null if none
7424     *         can be found.
7425     */
7426    public View focusSearch(@FocusRealDirection int direction) {
7427        if (mParent != null) {
7428            return mParent.focusSearch(this, direction);
7429        } else {
7430            return null;
7431        }
7432    }
7433
7434    /**
7435     * This method is the last chance for the focused view and its ancestors to
7436     * respond to an arrow key. This is called when the focused view did not
7437     * consume the key internally, nor could the view system find a new view in
7438     * the requested direction to give focus to.
7439     *
7440     * @param focused The currently focused view.
7441     * @param direction The direction focus wants to move. One of FOCUS_UP,
7442     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7443     * @return True if the this view consumed this unhandled move.
7444     */
7445    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7446        return false;
7447    }
7448
7449    /**
7450     * If a user manually specified the next view id for a particular direction,
7451     * use the root to look up the view.
7452     * @param root The root view of the hierarchy containing this view.
7453     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7454     * or FOCUS_BACKWARD.
7455     * @return The user specified next view, or null if there is none.
7456     */
7457    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7458        switch (direction) {
7459            case FOCUS_LEFT:
7460                if (mNextFocusLeftId == View.NO_ID) return null;
7461                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7462            case FOCUS_RIGHT:
7463                if (mNextFocusRightId == View.NO_ID) return null;
7464                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7465            case FOCUS_UP:
7466                if (mNextFocusUpId == View.NO_ID) return null;
7467                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7468            case FOCUS_DOWN:
7469                if (mNextFocusDownId == View.NO_ID) return null;
7470                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7471            case FOCUS_FORWARD:
7472                if (mNextFocusForwardId == View.NO_ID) return null;
7473                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7474            case FOCUS_BACKWARD: {
7475                if (mID == View.NO_ID) return null;
7476                final int id = mID;
7477                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7478                    @Override
7479                    public boolean apply(View t) {
7480                        return t.mNextFocusForwardId == id;
7481                    }
7482                });
7483            }
7484        }
7485        return null;
7486    }
7487
7488    private View findViewInsideOutShouldExist(View root, int id) {
7489        if (mMatchIdPredicate == null) {
7490            mMatchIdPredicate = new MatchIdPredicate();
7491        }
7492        mMatchIdPredicate.mId = id;
7493        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7494        if (result == null) {
7495            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7496        }
7497        return result;
7498    }
7499
7500    /**
7501     * Find and return all focusable views that are descendants of this view,
7502     * possibly including this view if it is focusable itself.
7503     *
7504     * @param direction The direction of the focus
7505     * @return A list of focusable views
7506     */
7507    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7508        ArrayList<View> result = new ArrayList<View>(24);
7509        addFocusables(result, direction);
7510        return result;
7511    }
7512
7513    /**
7514     * Add any focusable views that are descendants of this view (possibly
7515     * including this view if it is focusable itself) to views.  If we are in touch mode,
7516     * only add views that are also focusable in touch mode.
7517     *
7518     * @param views Focusable views found so far
7519     * @param direction The direction of the focus
7520     */
7521    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7522        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7523    }
7524
7525    /**
7526     * Adds any focusable views that are descendants of this view (possibly
7527     * including this view if it is focusable itself) to views. This method
7528     * adds all focusable views regardless if we are in touch mode or
7529     * only views focusable in touch mode if we are in touch mode or
7530     * only views that can take accessibility focus if accessibility is enabeld
7531     * depending on the focusable mode paramater.
7532     *
7533     * @param views Focusable views found so far or null if all we are interested is
7534     *        the number of focusables.
7535     * @param direction The direction of the focus.
7536     * @param focusableMode The type of focusables to be added.
7537     *
7538     * @see #FOCUSABLES_ALL
7539     * @see #FOCUSABLES_TOUCH_MODE
7540     */
7541    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7542            @FocusableMode int focusableMode) {
7543        if (views == null) {
7544            return;
7545        }
7546        if (!isFocusable()) {
7547            return;
7548        }
7549        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7550                && isInTouchMode() && !isFocusableInTouchMode()) {
7551            return;
7552        }
7553        views.add(this);
7554    }
7555
7556    /**
7557     * Finds the Views that contain given text. The containment is case insensitive.
7558     * The search is performed by either the text that the View renders or the content
7559     * description that describes the view for accessibility purposes and the view does
7560     * not render or both. Clients can specify how the search is to be performed via
7561     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7562     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7563     *
7564     * @param outViews The output list of matching Views.
7565     * @param searched The text to match against.
7566     *
7567     * @see #FIND_VIEWS_WITH_TEXT
7568     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7569     * @see #setContentDescription(CharSequence)
7570     */
7571    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7572            @FindViewFlags int flags) {
7573        if (getAccessibilityNodeProvider() != null) {
7574            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7575                outViews.add(this);
7576            }
7577        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7578                && (searched != null && searched.length() > 0)
7579                && (mContentDescription != null && mContentDescription.length() > 0)) {
7580            String searchedLowerCase = searched.toString().toLowerCase();
7581            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7582            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7583                outViews.add(this);
7584            }
7585        }
7586    }
7587
7588    /**
7589     * Find and return all touchable views that are descendants of this view,
7590     * possibly including this view if it is touchable itself.
7591     *
7592     * @return A list of touchable views
7593     */
7594    public ArrayList<View> getTouchables() {
7595        ArrayList<View> result = new ArrayList<View>();
7596        addTouchables(result);
7597        return result;
7598    }
7599
7600    /**
7601     * Add any touchable views that are descendants of this view (possibly
7602     * including this view if it is touchable itself) to views.
7603     *
7604     * @param views Touchable views found so far
7605     */
7606    public void addTouchables(ArrayList<View> views) {
7607        final int viewFlags = mViewFlags;
7608
7609        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7610                && (viewFlags & ENABLED_MASK) == ENABLED) {
7611            views.add(this);
7612        }
7613    }
7614
7615    /**
7616     * Returns whether this View is accessibility focused.
7617     *
7618     * @return True if this View is accessibility focused.
7619     */
7620    public boolean isAccessibilityFocused() {
7621        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7622    }
7623
7624    /**
7625     * Call this to try to give accessibility focus to this view.
7626     *
7627     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7628     * returns false or the view is no visible or the view already has accessibility
7629     * focus.
7630     *
7631     * See also {@link #focusSearch(int)}, which is what you call to say that you
7632     * have focus, and you want your parent to look for the next one.
7633     *
7634     * @return Whether this view actually took accessibility focus.
7635     *
7636     * @hide
7637     */
7638    public boolean requestAccessibilityFocus() {
7639        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7640        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7641            return false;
7642        }
7643        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7644            return false;
7645        }
7646        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7647            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7648            ViewRootImpl viewRootImpl = getViewRootImpl();
7649            if (viewRootImpl != null) {
7650                viewRootImpl.setAccessibilityFocus(this, null);
7651            }
7652            invalidate();
7653            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7654            return true;
7655        }
7656        return false;
7657    }
7658
7659    /**
7660     * Call this to try to clear accessibility focus of this view.
7661     *
7662     * See also {@link #focusSearch(int)}, which is what you call to say that you
7663     * have focus, and you want your parent to look for the next one.
7664     *
7665     * @hide
7666     */
7667    public void clearAccessibilityFocus() {
7668        clearAccessibilityFocusNoCallbacks();
7669        // Clear the global reference of accessibility focus if this
7670        // view or any of its descendants had accessibility focus.
7671        ViewRootImpl viewRootImpl = getViewRootImpl();
7672        if (viewRootImpl != null) {
7673            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7674            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7675                viewRootImpl.setAccessibilityFocus(null, null);
7676            }
7677        }
7678    }
7679
7680    private void sendAccessibilityHoverEvent(int eventType) {
7681        // Since we are not delivering to a client accessibility events from not
7682        // important views (unless the clinet request that) we need to fire the
7683        // event from the deepest view exposed to the client. As a consequence if
7684        // the user crosses a not exposed view the client will see enter and exit
7685        // of the exposed predecessor followed by and enter and exit of that same
7686        // predecessor when entering and exiting the not exposed descendant. This
7687        // is fine since the client has a clear idea which view is hovered at the
7688        // price of a couple more events being sent. This is a simple and
7689        // working solution.
7690        View source = this;
7691        while (true) {
7692            if (source.includeForAccessibility()) {
7693                source.sendAccessibilityEvent(eventType);
7694                return;
7695            }
7696            ViewParent parent = source.getParent();
7697            if (parent instanceof View) {
7698                source = (View) parent;
7699            } else {
7700                return;
7701            }
7702        }
7703    }
7704
7705    /**
7706     * Clears accessibility focus without calling any callback methods
7707     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7708     * is used for clearing accessibility focus when giving this focus to
7709     * another view.
7710     */
7711    void clearAccessibilityFocusNoCallbacks() {
7712        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7713            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7714            invalidate();
7715            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7716        }
7717    }
7718
7719    /**
7720     * Call this to try to give focus to a specific view or to one of its
7721     * descendants.
7722     *
7723     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7724     * false), or if it is focusable and it is not focusable in touch mode
7725     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7726     *
7727     * See also {@link #focusSearch(int)}, which is what you call to say that you
7728     * have focus, and you want your parent to look for the next one.
7729     *
7730     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7731     * {@link #FOCUS_DOWN} and <code>null</code>.
7732     *
7733     * @return Whether this view or one of its descendants actually took focus.
7734     */
7735    public final boolean requestFocus() {
7736        return requestFocus(View.FOCUS_DOWN);
7737    }
7738
7739    /**
7740     * Call this to try to give focus to a specific view or to one of its
7741     * descendants and give it a hint about what direction focus is heading.
7742     *
7743     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7744     * false), or if it is focusable and it is not focusable in touch mode
7745     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7746     *
7747     * See also {@link #focusSearch(int)}, which is what you call to say that you
7748     * have focus, and you want your parent to look for the next one.
7749     *
7750     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7751     * <code>null</code> set for the previously focused rectangle.
7752     *
7753     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7754     * @return Whether this view or one of its descendants actually took focus.
7755     */
7756    public final boolean requestFocus(int direction) {
7757        return requestFocus(direction, null);
7758    }
7759
7760    /**
7761     * Call this to try to give focus to a specific view or to one of its descendants
7762     * and give it hints about the direction and a specific rectangle that the focus
7763     * is coming from.  The rectangle can help give larger views a finer grained hint
7764     * about where focus is coming from, and therefore, where to show selection, or
7765     * forward focus change internally.
7766     *
7767     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7768     * false), or if it is focusable and it is not focusable in touch mode
7769     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7770     *
7771     * A View will not take focus if it is not visible.
7772     *
7773     * A View will not take focus if one of its parents has
7774     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7775     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7776     *
7777     * See also {@link #focusSearch(int)}, which is what you call to say that you
7778     * have focus, and you want your parent to look for the next one.
7779     *
7780     * You may wish to override this method if your custom {@link View} has an internal
7781     * {@link View} that it wishes to forward the request to.
7782     *
7783     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7784     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7785     *        to give a finer grained hint about where focus is coming from.  May be null
7786     *        if there is no hint.
7787     * @return Whether this view or one of its descendants actually took focus.
7788     */
7789    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7790        return requestFocusNoSearch(direction, previouslyFocusedRect);
7791    }
7792
7793    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7794        // need to be focusable
7795        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7796                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7797            return false;
7798        }
7799
7800        // need to be focusable in touch mode if in touch mode
7801        if (isInTouchMode() &&
7802            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7803               return false;
7804        }
7805
7806        // need to not have any parents blocking us
7807        if (hasAncestorThatBlocksDescendantFocus()) {
7808            return false;
7809        }
7810
7811        handleFocusGainInternal(direction, previouslyFocusedRect);
7812        return true;
7813    }
7814
7815    /**
7816     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7817     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7818     * touch mode to request focus when they are touched.
7819     *
7820     * @return Whether this view or one of its descendants actually took focus.
7821     *
7822     * @see #isInTouchMode()
7823     *
7824     */
7825    public final boolean requestFocusFromTouch() {
7826        // Leave touch mode if we need to
7827        if (isInTouchMode()) {
7828            ViewRootImpl viewRoot = getViewRootImpl();
7829            if (viewRoot != null) {
7830                viewRoot.ensureTouchMode(false);
7831            }
7832        }
7833        return requestFocus(View.FOCUS_DOWN);
7834    }
7835
7836    /**
7837     * @return Whether any ancestor of this view blocks descendant focus.
7838     */
7839    private boolean hasAncestorThatBlocksDescendantFocus() {
7840        final boolean focusableInTouchMode = isFocusableInTouchMode();
7841        ViewParent ancestor = mParent;
7842        while (ancestor instanceof ViewGroup) {
7843            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7844            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7845                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7846                return true;
7847            } else {
7848                ancestor = vgAncestor.getParent();
7849            }
7850        }
7851        return false;
7852    }
7853
7854    /**
7855     * Gets the mode for determining whether this View is important for accessibility
7856     * which is if it fires accessibility events and if it is reported to
7857     * accessibility services that query the screen.
7858     *
7859     * @return The mode for determining whether a View is important for accessibility.
7860     *
7861     * @attr ref android.R.styleable#View_importantForAccessibility
7862     *
7863     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7864     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7865     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7866     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7867     */
7868    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7869            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7870            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7871            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7872            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7873                    to = "noHideDescendants")
7874        })
7875    public int getImportantForAccessibility() {
7876        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7877                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7878    }
7879
7880    /**
7881     * Sets the live region mode for this view. This indicates to accessibility
7882     * services whether they should automatically notify the user about changes
7883     * to the view's content description or text, or to the content descriptions
7884     * or text of the view's children (where applicable).
7885     * <p>
7886     * For example, in a login screen with a TextView that displays an "incorrect
7887     * password" notification, that view should be marked as a live region with
7888     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7889     * <p>
7890     * To disable change notifications for this view, use
7891     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7892     * mode for most views.
7893     * <p>
7894     * To indicate that the user should be notified of changes, use
7895     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7896     * <p>
7897     * If the view's changes should interrupt ongoing speech and notify the user
7898     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7899     *
7900     * @param mode The live region mode for this view, one of:
7901     *        <ul>
7902     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7903     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7904     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7905     *        </ul>
7906     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7907     */
7908    public void setAccessibilityLiveRegion(int mode) {
7909        if (mode != getAccessibilityLiveRegion()) {
7910            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7911            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7912                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7913            notifyViewAccessibilityStateChangedIfNeeded(
7914                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7915        }
7916    }
7917
7918    /**
7919     * Gets the live region mode for this View.
7920     *
7921     * @return The live region mode for the view.
7922     *
7923     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7924     *
7925     * @see #setAccessibilityLiveRegion(int)
7926     */
7927    public int getAccessibilityLiveRegion() {
7928        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7929                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7930    }
7931
7932    /**
7933     * Sets how to determine whether this view is important for accessibility
7934     * which is if it fires accessibility events and if it is reported to
7935     * accessibility services that query the screen.
7936     *
7937     * @param mode How to determine whether this view is important for accessibility.
7938     *
7939     * @attr ref android.R.styleable#View_importantForAccessibility
7940     *
7941     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7942     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7943     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7944     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7945     */
7946    public void setImportantForAccessibility(int mode) {
7947        final int oldMode = getImportantForAccessibility();
7948        if (mode != oldMode) {
7949            // If we're moving between AUTO and another state, we might not need
7950            // to send a subtree changed notification. We'll store the computed
7951            // importance, since we'll need to check it later to make sure.
7952            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7953                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7954            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7955            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7956            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7957                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7958            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7959                notifySubtreeAccessibilityStateChangedIfNeeded();
7960            } else {
7961                notifyViewAccessibilityStateChangedIfNeeded(
7962                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7963            }
7964        }
7965    }
7966
7967    /**
7968     * Computes whether this view should be exposed for accessibility. In
7969     * general, views that are interactive or provide information are exposed
7970     * while views that serve only as containers are hidden.
7971     * <p>
7972     * If an ancestor of this view has importance
7973     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7974     * returns <code>false</code>.
7975     * <p>
7976     * Otherwise, the value is computed according to the view's
7977     * {@link #getImportantForAccessibility()} value:
7978     * <ol>
7979     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7980     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7981     * </code>
7982     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7983     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7984     * view satisfies any of the following:
7985     * <ul>
7986     * <li>Is actionable, e.g. {@link #isClickable()},
7987     * {@link #isLongClickable()}, or {@link #isFocusable()}
7988     * <li>Has an {@link AccessibilityDelegate}
7989     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7990     * {@link OnKeyListener}, etc.
7991     * <li>Is an accessibility live region, e.g.
7992     * {@link #getAccessibilityLiveRegion()} is not
7993     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7994     * </ul>
7995     * </ol>
7996     *
7997     * @return Whether the view is exposed for accessibility.
7998     * @see #setImportantForAccessibility(int)
7999     * @see #getImportantForAccessibility()
8000     */
8001    public boolean isImportantForAccessibility() {
8002        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8003                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8004        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8005                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8006            return false;
8007        }
8008
8009        // Check parent mode to ensure we're not hidden.
8010        ViewParent parent = mParent;
8011        while (parent instanceof View) {
8012            if (((View) parent).getImportantForAccessibility()
8013                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8014                return false;
8015            }
8016            parent = parent.getParent();
8017        }
8018
8019        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8020                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8021                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8022    }
8023
8024    /**
8025     * Gets the parent for accessibility purposes. Note that the parent for
8026     * accessibility is not necessary the immediate parent. It is the first
8027     * predecessor that is important for accessibility.
8028     *
8029     * @return The parent for accessibility purposes.
8030     */
8031    public ViewParent getParentForAccessibility() {
8032        if (mParent instanceof View) {
8033            View parentView = (View) mParent;
8034            if (parentView.includeForAccessibility()) {
8035                return mParent;
8036            } else {
8037                return mParent.getParentForAccessibility();
8038            }
8039        }
8040        return null;
8041    }
8042
8043    /**
8044     * Adds the children of a given View for accessibility. Since some Views are
8045     * not important for accessibility the children for accessibility are not
8046     * necessarily direct children of the view, rather they are the first level of
8047     * descendants important for accessibility.
8048     *
8049     * @param children The list of children for accessibility.
8050     */
8051    public void addChildrenForAccessibility(ArrayList<View> children) {
8052
8053    }
8054
8055    /**
8056     * Whether to regard this view for accessibility. A view is regarded for
8057     * accessibility if it is important for accessibility or the querying
8058     * accessibility service has explicitly requested that view not
8059     * important for accessibility are regarded.
8060     *
8061     * @return Whether to regard the view for accessibility.
8062     *
8063     * @hide
8064     */
8065    public boolean includeForAccessibility() {
8066        if (mAttachInfo != null) {
8067            return (mAttachInfo.mAccessibilityFetchFlags
8068                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8069                    || isImportantForAccessibility();
8070        }
8071        return false;
8072    }
8073
8074    /**
8075     * Returns whether the View is considered actionable from
8076     * accessibility perspective. Such view are important for
8077     * accessibility.
8078     *
8079     * @return True if the view is actionable for accessibility.
8080     *
8081     * @hide
8082     */
8083    public boolean isActionableForAccessibility() {
8084        return (isClickable() || isLongClickable() || isFocusable());
8085    }
8086
8087    /**
8088     * Returns whether the View has registered callbacks which makes it
8089     * important for accessibility.
8090     *
8091     * @return True if the view is actionable for accessibility.
8092     */
8093    private boolean hasListenersForAccessibility() {
8094        ListenerInfo info = getListenerInfo();
8095        return mTouchDelegate != null || info.mOnKeyListener != null
8096                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8097                || info.mOnHoverListener != null || info.mOnDragListener != null;
8098    }
8099
8100    /**
8101     * Notifies that the accessibility state of this view changed. The change
8102     * is local to this view and does not represent structural changes such
8103     * as children and parent. For example, the view became focusable. The
8104     * notification is at at most once every
8105     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8106     * to avoid unnecessary load to the system. Also once a view has a pending
8107     * notification this method is a NOP until the notification has been sent.
8108     *
8109     * @hide
8110     */
8111    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8112        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8113            return;
8114        }
8115        if (mSendViewStateChangedAccessibilityEvent == null) {
8116            mSendViewStateChangedAccessibilityEvent =
8117                    new SendViewStateChangedAccessibilityEvent();
8118        }
8119        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8120    }
8121
8122    /**
8123     * Notifies that the accessibility state of this view changed. The change
8124     * is *not* local to this view and does represent structural changes such
8125     * as children and parent. For example, the view size changed. The
8126     * notification is at at most once every
8127     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8128     * to avoid unnecessary load to the system. Also once a view has a pending
8129     * notification this method is a NOP until the notification has been sent.
8130     *
8131     * @hide
8132     */
8133    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8134        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8135            return;
8136        }
8137        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8138            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8139            if (mParent != null) {
8140                try {
8141                    mParent.notifySubtreeAccessibilityStateChanged(
8142                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8143                } catch (AbstractMethodError e) {
8144                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8145                            " does not fully implement ViewParent", e);
8146                }
8147            }
8148        }
8149    }
8150
8151    /**
8152     * Reset the flag indicating the accessibility state of the subtree rooted
8153     * at this view changed.
8154     */
8155    void resetSubtreeAccessibilityStateChanged() {
8156        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8157    }
8158
8159    /**
8160     * Performs the specified accessibility action on the view. For
8161     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8162     * <p>
8163     * If an {@link AccessibilityDelegate} has been specified via calling
8164     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8165     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8166     * is responsible for handling this call.
8167     * </p>
8168     *
8169     * @param action The action to perform.
8170     * @param arguments Optional action arguments.
8171     * @return Whether the action was performed.
8172     */
8173    public boolean performAccessibilityAction(int action, Bundle arguments) {
8174      if (mAccessibilityDelegate != null) {
8175          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8176      } else {
8177          return performAccessibilityActionInternal(action, arguments);
8178      }
8179    }
8180
8181   /**
8182    * @see #performAccessibilityAction(int, Bundle)
8183    *
8184    * Note: Called from the default {@link AccessibilityDelegate}.
8185    */
8186    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8187        switch (action) {
8188            case AccessibilityNodeInfo.ACTION_CLICK: {
8189                if (isClickable()) {
8190                    performClick();
8191                    return true;
8192                }
8193            } break;
8194            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8195                if (isLongClickable()) {
8196                    performLongClick();
8197                    return true;
8198                }
8199            } break;
8200            case AccessibilityNodeInfo.ACTION_FOCUS: {
8201                if (!hasFocus()) {
8202                    // Get out of touch mode since accessibility
8203                    // wants to move focus around.
8204                    getViewRootImpl().ensureTouchMode(false);
8205                    return requestFocus();
8206                }
8207            } break;
8208            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8209                if (hasFocus()) {
8210                    clearFocus();
8211                    return !isFocused();
8212                }
8213            } break;
8214            case AccessibilityNodeInfo.ACTION_SELECT: {
8215                if (!isSelected()) {
8216                    setSelected(true);
8217                    return isSelected();
8218                }
8219            } break;
8220            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8221                if (isSelected()) {
8222                    setSelected(false);
8223                    return !isSelected();
8224                }
8225            } break;
8226            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8227                if (!isAccessibilityFocused()) {
8228                    return requestAccessibilityFocus();
8229                }
8230            } break;
8231            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8232                if (isAccessibilityFocused()) {
8233                    clearAccessibilityFocus();
8234                    return true;
8235                }
8236            } break;
8237            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8238                if (arguments != null) {
8239                    final int granularity = arguments.getInt(
8240                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8241                    final boolean extendSelection = arguments.getBoolean(
8242                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8243                    return traverseAtGranularity(granularity, true, extendSelection);
8244                }
8245            } break;
8246            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8247                if (arguments != null) {
8248                    final int granularity = arguments.getInt(
8249                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8250                    final boolean extendSelection = arguments.getBoolean(
8251                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8252                    return traverseAtGranularity(granularity, false, extendSelection);
8253                }
8254            } break;
8255            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8256                CharSequence text = getIterableTextForAccessibility();
8257                if (text == null) {
8258                    return false;
8259                }
8260                final int start = (arguments != null) ? arguments.getInt(
8261                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8262                final int end = (arguments != null) ? arguments.getInt(
8263                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8264                // Only cursor position can be specified (selection length == 0)
8265                if ((getAccessibilitySelectionStart() != start
8266                        || getAccessibilitySelectionEnd() != end)
8267                        && (start == end)) {
8268                    setAccessibilitySelection(start, end);
8269                    notifyViewAccessibilityStateChangedIfNeeded(
8270                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8271                    return true;
8272                }
8273            } break;
8274        }
8275        return false;
8276    }
8277
8278    private boolean traverseAtGranularity(int granularity, boolean forward,
8279            boolean extendSelection) {
8280        CharSequence text = getIterableTextForAccessibility();
8281        if (text == null || text.length() == 0) {
8282            return false;
8283        }
8284        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8285        if (iterator == null) {
8286            return false;
8287        }
8288        int current = getAccessibilitySelectionEnd();
8289        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8290            current = forward ? 0 : text.length();
8291        }
8292        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8293        if (range == null) {
8294            return false;
8295        }
8296        final int segmentStart = range[0];
8297        final int segmentEnd = range[1];
8298        int selectionStart;
8299        int selectionEnd;
8300        if (extendSelection && isAccessibilitySelectionExtendable()) {
8301            selectionStart = getAccessibilitySelectionStart();
8302            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8303                selectionStart = forward ? segmentStart : segmentEnd;
8304            }
8305            selectionEnd = forward ? segmentEnd : segmentStart;
8306        } else {
8307            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8308        }
8309        setAccessibilitySelection(selectionStart, selectionEnd);
8310        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8311                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8312        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8313        return true;
8314    }
8315
8316    /**
8317     * Gets the text reported for accessibility purposes.
8318     *
8319     * @return The accessibility text.
8320     *
8321     * @hide
8322     */
8323    public CharSequence getIterableTextForAccessibility() {
8324        return getContentDescription();
8325    }
8326
8327    /**
8328     * Gets whether accessibility selection can be extended.
8329     *
8330     * @return If selection is extensible.
8331     *
8332     * @hide
8333     */
8334    public boolean isAccessibilitySelectionExtendable() {
8335        return false;
8336    }
8337
8338    /**
8339     * @hide
8340     */
8341    public int getAccessibilitySelectionStart() {
8342        return mAccessibilityCursorPosition;
8343    }
8344
8345    /**
8346     * @hide
8347     */
8348    public int getAccessibilitySelectionEnd() {
8349        return getAccessibilitySelectionStart();
8350    }
8351
8352    /**
8353     * @hide
8354     */
8355    public void setAccessibilitySelection(int start, int end) {
8356        if (start ==  end && end == mAccessibilityCursorPosition) {
8357            return;
8358        }
8359        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8360            mAccessibilityCursorPosition = start;
8361        } else {
8362            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8363        }
8364        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8365    }
8366
8367    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8368            int fromIndex, int toIndex) {
8369        if (mParent == null) {
8370            return;
8371        }
8372        AccessibilityEvent event = AccessibilityEvent.obtain(
8373                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8374        onInitializeAccessibilityEvent(event);
8375        onPopulateAccessibilityEvent(event);
8376        event.setFromIndex(fromIndex);
8377        event.setToIndex(toIndex);
8378        event.setAction(action);
8379        event.setMovementGranularity(granularity);
8380        mParent.requestSendAccessibilityEvent(this, event);
8381    }
8382
8383    /**
8384     * @hide
8385     */
8386    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8387        switch (granularity) {
8388            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8389                CharSequence text = getIterableTextForAccessibility();
8390                if (text != null && text.length() > 0) {
8391                    CharacterTextSegmentIterator iterator =
8392                        CharacterTextSegmentIterator.getInstance(
8393                                mContext.getResources().getConfiguration().locale);
8394                    iterator.initialize(text.toString());
8395                    return iterator;
8396                }
8397            } break;
8398            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8399                CharSequence text = getIterableTextForAccessibility();
8400                if (text != null && text.length() > 0) {
8401                    WordTextSegmentIterator iterator =
8402                        WordTextSegmentIterator.getInstance(
8403                                mContext.getResources().getConfiguration().locale);
8404                    iterator.initialize(text.toString());
8405                    return iterator;
8406                }
8407            } break;
8408            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8409                CharSequence text = getIterableTextForAccessibility();
8410                if (text != null && text.length() > 0) {
8411                    ParagraphTextSegmentIterator iterator =
8412                        ParagraphTextSegmentIterator.getInstance();
8413                    iterator.initialize(text.toString());
8414                    return iterator;
8415                }
8416            } break;
8417        }
8418        return null;
8419    }
8420
8421    /**
8422     * @hide
8423     */
8424    public void dispatchStartTemporaryDetach() {
8425        onStartTemporaryDetach();
8426    }
8427
8428    /**
8429     * This is called when a container is going to temporarily detach a child, with
8430     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8431     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8432     * {@link #onDetachedFromWindow()} when the container is done.
8433     */
8434    public void onStartTemporaryDetach() {
8435        removeUnsetPressCallback();
8436        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8437    }
8438
8439    /**
8440     * @hide
8441     */
8442    public void dispatchFinishTemporaryDetach() {
8443        onFinishTemporaryDetach();
8444    }
8445
8446    /**
8447     * Called after {@link #onStartTemporaryDetach} when the container is done
8448     * changing the view.
8449     */
8450    public void onFinishTemporaryDetach() {
8451    }
8452
8453    /**
8454     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8455     * for this view's window.  Returns null if the view is not currently attached
8456     * to the window.  Normally you will not need to use this directly, but
8457     * just use the standard high-level event callbacks like
8458     * {@link #onKeyDown(int, KeyEvent)}.
8459     */
8460    public KeyEvent.DispatcherState getKeyDispatcherState() {
8461        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8462    }
8463
8464    /**
8465     * Dispatch a key event before it is processed by any input method
8466     * associated with the view hierarchy.  This can be used to intercept
8467     * key events in special situations before the IME consumes them; a
8468     * typical example would be handling the BACK key to update the application's
8469     * UI instead of allowing the IME to see it and close itself.
8470     *
8471     * @param event The key event to be dispatched.
8472     * @return True if the event was handled, false otherwise.
8473     */
8474    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8475        return onKeyPreIme(event.getKeyCode(), event);
8476    }
8477
8478    /**
8479     * Dispatch a key event to the next view on the focus path. This path runs
8480     * from the top of the view tree down to the currently focused view. If this
8481     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8482     * the next node down the focus path. This method also fires any key
8483     * listeners.
8484     *
8485     * @param event The key event to be dispatched.
8486     * @return True if the event was handled, false otherwise.
8487     */
8488    public boolean dispatchKeyEvent(KeyEvent event) {
8489        if (mInputEventConsistencyVerifier != null) {
8490            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8491        }
8492
8493        // Give any attached key listener a first crack at the event.
8494        //noinspection SimplifiableIfStatement
8495        ListenerInfo li = mListenerInfo;
8496        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8497                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8498            return true;
8499        }
8500
8501        if (event.dispatch(this, mAttachInfo != null
8502                ? mAttachInfo.mKeyDispatchState : null, this)) {
8503            return true;
8504        }
8505
8506        if (mInputEventConsistencyVerifier != null) {
8507            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8508        }
8509        return false;
8510    }
8511
8512    /**
8513     * Dispatches a key shortcut event.
8514     *
8515     * @param event The key event to be dispatched.
8516     * @return True if the event was handled by the view, false otherwise.
8517     */
8518    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8519        return onKeyShortcut(event.getKeyCode(), event);
8520    }
8521
8522    /**
8523     * Pass the touch screen motion event down to the target view, or this
8524     * view if it is the target.
8525     *
8526     * @param event The motion event to be dispatched.
8527     * @return True if the event was handled by the view, false otherwise.
8528     */
8529    public boolean dispatchTouchEvent(MotionEvent event) {
8530        boolean result = false;
8531
8532        if (mInputEventConsistencyVerifier != null) {
8533            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8534        }
8535
8536        final int actionMasked = event.getActionMasked();
8537        if (actionMasked == MotionEvent.ACTION_DOWN) {
8538            // Defensive cleanup for new gesture
8539            stopNestedScroll();
8540        }
8541
8542        if (onFilterTouchEventForSecurity(event)) {
8543            //noinspection SimplifiableIfStatement
8544            ListenerInfo li = mListenerInfo;
8545            if (li != null && li.mOnTouchListener != null
8546                    && (mViewFlags & ENABLED_MASK) == ENABLED
8547                    && li.mOnTouchListener.onTouch(this, event)) {
8548                result = true;
8549            }
8550
8551            if (!result && onTouchEvent(event)) {
8552                result = true;
8553            }
8554        }
8555
8556        if (!result && mInputEventConsistencyVerifier != null) {
8557            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8558        }
8559
8560        // Clean up after nested scrolls if this is the end of a gesture;
8561        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8562        // of the gesture.
8563        if (actionMasked == MotionEvent.ACTION_UP ||
8564                actionMasked == MotionEvent.ACTION_CANCEL ||
8565                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8566            stopNestedScroll();
8567        }
8568
8569        return result;
8570    }
8571
8572    /**
8573     * Filter the touch event to apply security policies.
8574     *
8575     * @param event The motion event to be filtered.
8576     * @return True if the event should be dispatched, false if the event should be dropped.
8577     *
8578     * @see #getFilterTouchesWhenObscured
8579     */
8580    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8581        //noinspection RedundantIfStatement
8582        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8583                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8584            // Window is obscured, drop this touch.
8585            return false;
8586        }
8587        return true;
8588    }
8589
8590    /**
8591     * Pass a trackball motion event down to the focused view.
8592     *
8593     * @param event The motion event to be dispatched.
8594     * @return True if the event was handled by the view, false otherwise.
8595     */
8596    public boolean dispatchTrackballEvent(MotionEvent event) {
8597        if (mInputEventConsistencyVerifier != null) {
8598            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8599        }
8600
8601        return onTrackballEvent(event);
8602    }
8603
8604    /**
8605     * Dispatch a generic motion event.
8606     * <p>
8607     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8608     * are delivered to the view under the pointer.  All other generic motion events are
8609     * delivered to the focused view.  Hover events are handled specially and are delivered
8610     * to {@link #onHoverEvent(MotionEvent)}.
8611     * </p>
8612     *
8613     * @param event The motion event to be dispatched.
8614     * @return True if the event was handled by the view, false otherwise.
8615     */
8616    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8617        if (mInputEventConsistencyVerifier != null) {
8618            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8619        }
8620
8621        final int source = event.getSource();
8622        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8623            final int action = event.getAction();
8624            if (action == MotionEvent.ACTION_HOVER_ENTER
8625                    || action == MotionEvent.ACTION_HOVER_MOVE
8626                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8627                if (dispatchHoverEvent(event)) {
8628                    return true;
8629                }
8630            } else if (dispatchGenericPointerEvent(event)) {
8631                return true;
8632            }
8633        } else if (dispatchGenericFocusedEvent(event)) {
8634            return true;
8635        }
8636
8637        if (dispatchGenericMotionEventInternal(event)) {
8638            return true;
8639        }
8640
8641        if (mInputEventConsistencyVerifier != null) {
8642            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8643        }
8644        return false;
8645    }
8646
8647    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8648        //noinspection SimplifiableIfStatement
8649        ListenerInfo li = mListenerInfo;
8650        if (li != null && li.mOnGenericMotionListener != null
8651                && (mViewFlags & ENABLED_MASK) == ENABLED
8652                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8653            return true;
8654        }
8655
8656        if (onGenericMotionEvent(event)) {
8657            return true;
8658        }
8659
8660        if (mInputEventConsistencyVerifier != null) {
8661            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8662        }
8663        return false;
8664    }
8665
8666    /**
8667     * Dispatch a hover event.
8668     * <p>
8669     * Do not call this method directly.
8670     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8671     * </p>
8672     *
8673     * @param event The motion event to be dispatched.
8674     * @return True if the event was handled by the view, false otherwise.
8675     */
8676    protected boolean dispatchHoverEvent(MotionEvent event) {
8677        ListenerInfo li = mListenerInfo;
8678        //noinspection SimplifiableIfStatement
8679        if (li != null && li.mOnHoverListener != null
8680                && (mViewFlags & ENABLED_MASK) == ENABLED
8681                && li.mOnHoverListener.onHover(this, event)) {
8682            return true;
8683        }
8684
8685        return onHoverEvent(event);
8686    }
8687
8688    /**
8689     * Returns true if the view has a child to which it has recently sent
8690     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8691     * it does not have a hovered child, then it must be the innermost hovered view.
8692     * @hide
8693     */
8694    protected boolean hasHoveredChild() {
8695        return false;
8696    }
8697
8698    /**
8699     * Dispatch a generic motion event to the view under the first pointer.
8700     * <p>
8701     * Do not call this method directly.
8702     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8703     * </p>
8704     *
8705     * @param event The motion event to be dispatched.
8706     * @return True if the event was handled by the view, false otherwise.
8707     */
8708    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8709        return false;
8710    }
8711
8712    /**
8713     * Dispatch a generic motion event to the currently focused view.
8714     * <p>
8715     * Do not call this method directly.
8716     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8717     * </p>
8718     *
8719     * @param event The motion event to be dispatched.
8720     * @return True if the event was handled by the view, false otherwise.
8721     */
8722    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8723        return false;
8724    }
8725
8726    /**
8727     * Dispatch a pointer event.
8728     * <p>
8729     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8730     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8731     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8732     * and should not be expected to handle other pointing device features.
8733     * </p>
8734     *
8735     * @param event The motion event to be dispatched.
8736     * @return True if the event was handled by the view, false otherwise.
8737     * @hide
8738     */
8739    public final boolean dispatchPointerEvent(MotionEvent event) {
8740        if (event.isTouchEvent()) {
8741            return dispatchTouchEvent(event);
8742        } else {
8743            return dispatchGenericMotionEvent(event);
8744        }
8745    }
8746
8747    /**
8748     * Called when the window containing this view gains or loses window focus.
8749     * ViewGroups should override to route to their children.
8750     *
8751     * @param hasFocus True if the window containing this view now has focus,
8752     *        false otherwise.
8753     */
8754    public void dispatchWindowFocusChanged(boolean hasFocus) {
8755        onWindowFocusChanged(hasFocus);
8756    }
8757
8758    /**
8759     * Called when the window containing this view gains or loses focus.  Note
8760     * that this is separate from view focus: to receive key events, both
8761     * your view and its window must have focus.  If a window is displayed
8762     * on top of yours that takes input focus, then your own window will lose
8763     * focus but the view focus will remain unchanged.
8764     *
8765     * @param hasWindowFocus True if the window containing this view now has
8766     *        focus, false otherwise.
8767     */
8768    public void onWindowFocusChanged(boolean hasWindowFocus) {
8769        InputMethodManager imm = InputMethodManager.peekInstance();
8770        if (!hasWindowFocus) {
8771            if (isPressed()) {
8772                setPressed(false);
8773            }
8774            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8775                imm.focusOut(this);
8776            }
8777            removeLongPressCallback();
8778            removeTapCallback();
8779            onFocusLost();
8780        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8781            imm.focusIn(this);
8782        }
8783        refreshDrawableState();
8784    }
8785
8786    /**
8787     * Returns true if this view is in a window that currently has window focus.
8788     * Note that this is not the same as the view itself having focus.
8789     *
8790     * @return True if this view is in a window that currently has window focus.
8791     */
8792    public boolean hasWindowFocus() {
8793        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8794    }
8795
8796    /**
8797     * Dispatch a view visibility change down the view hierarchy.
8798     * ViewGroups should override to route to their children.
8799     * @param changedView The view whose visibility changed. Could be 'this' or
8800     * an ancestor view.
8801     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8802     * {@link #INVISIBLE} or {@link #GONE}.
8803     */
8804    protected void dispatchVisibilityChanged(@NonNull View changedView,
8805            @Visibility int visibility) {
8806        onVisibilityChanged(changedView, visibility);
8807    }
8808
8809    /**
8810     * Called when the visibility of the view or an ancestor of the view is changed.
8811     * @param changedView The view whose visibility changed. Could be 'this' or
8812     * an ancestor view.
8813     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8814     * {@link #INVISIBLE} or {@link #GONE}.
8815     */
8816    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8817        if (visibility == VISIBLE) {
8818            if (mAttachInfo != null) {
8819                initialAwakenScrollBars();
8820            } else {
8821                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8822            }
8823        }
8824    }
8825
8826    /**
8827     * Dispatch a hint about whether this view is displayed. For instance, when
8828     * a View moves out of the screen, it might receives a display hint indicating
8829     * the view is not displayed. Applications should not <em>rely</em> on this hint
8830     * as there is no guarantee that they will receive one.
8831     *
8832     * @param hint A hint about whether or not this view is displayed:
8833     * {@link #VISIBLE} or {@link #INVISIBLE}.
8834     */
8835    public void dispatchDisplayHint(@Visibility int hint) {
8836        onDisplayHint(hint);
8837    }
8838
8839    /**
8840     * Gives this view a hint about whether is displayed or not. For instance, when
8841     * a View moves out of the screen, it might receives a display hint indicating
8842     * the view is not displayed. Applications should not <em>rely</em> on this hint
8843     * as there is no guarantee that they will receive one.
8844     *
8845     * @param hint A hint about whether or not this view is displayed:
8846     * {@link #VISIBLE} or {@link #INVISIBLE}.
8847     */
8848    protected void onDisplayHint(@Visibility int hint) {
8849    }
8850
8851    /**
8852     * Dispatch a window visibility change down the view hierarchy.
8853     * ViewGroups should override to route to their children.
8854     *
8855     * @param visibility The new visibility of the window.
8856     *
8857     * @see #onWindowVisibilityChanged(int)
8858     */
8859    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8860        onWindowVisibilityChanged(visibility);
8861    }
8862
8863    /**
8864     * Called when the window containing has change its visibility
8865     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8866     * that this tells you whether or not your window is being made visible
8867     * to the window manager; this does <em>not</em> tell you whether or not
8868     * your window is obscured by other windows on the screen, even if it
8869     * is itself visible.
8870     *
8871     * @param visibility The new visibility of the window.
8872     */
8873    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8874        if (visibility == VISIBLE) {
8875            initialAwakenScrollBars();
8876        }
8877    }
8878
8879    /**
8880     * Returns the current visibility of the window this view is attached to
8881     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8882     *
8883     * @return Returns the current visibility of the view's window.
8884     */
8885    @Visibility
8886    public int getWindowVisibility() {
8887        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8888    }
8889
8890    /**
8891     * Retrieve the overall visible display size in which the window this view is
8892     * attached to has been positioned in.  This takes into account screen
8893     * decorations above the window, for both cases where the window itself
8894     * is being position inside of them or the window is being placed under
8895     * then and covered insets are used for the window to position its content
8896     * inside.  In effect, this tells you the available area where content can
8897     * be placed and remain visible to users.
8898     *
8899     * <p>This function requires an IPC back to the window manager to retrieve
8900     * the requested information, so should not be used in performance critical
8901     * code like drawing.
8902     *
8903     * @param outRect Filled in with the visible display frame.  If the view
8904     * is not attached to a window, this is simply the raw display size.
8905     */
8906    public void getWindowVisibleDisplayFrame(Rect outRect) {
8907        if (mAttachInfo != null) {
8908            try {
8909                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8910            } catch (RemoteException e) {
8911                return;
8912            }
8913            // XXX This is really broken, and probably all needs to be done
8914            // in the window manager, and we need to know more about whether
8915            // we want the area behind or in front of the IME.
8916            final Rect insets = mAttachInfo.mVisibleInsets;
8917            outRect.left += insets.left;
8918            outRect.top += insets.top;
8919            outRect.right -= insets.right;
8920            outRect.bottom -= insets.bottom;
8921            return;
8922        }
8923        // The view is not attached to a display so we don't have a context.
8924        // Make a best guess about the display size.
8925        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8926        d.getRectSize(outRect);
8927    }
8928
8929    /**
8930     * Dispatch a notification about a resource configuration change down
8931     * the view hierarchy.
8932     * ViewGroups should override to route to their children.
8933     *
8934     * @param newConfig The new resource configuration.
8935     *
8936     * @see #onConfigurationChanged(android.content.res.Configuration)
8937     */
8938    public void dispatchConfigurationChanged(Configuration newConfig) {
8939        onConfigurationChanged(newConfig);
8940    }
8941
8942    /**
8943     * Called when the current configuration of the resources being used
8944     * by the application have changed.  You can use this to decide when
8945     * to reload resources that can changed based on orientation and other
8946     * configuration characterstics.  You only need to use this if you are
8947     * not relying on the normal {@link android.app.Activity} mechanism of
8948     * recreating the activity instance upon a configuration change.
8949     *
8950     * @param newConfig The new resource configuration.
8951     */
8952    protected void onConfigurationChanged(Configuration newConfig) {
8953    }
8954
8955    /**
8956     * Private function to aggregate all per-view attributes in to the view
8957     * root.
8958     */
8959    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8960        performCollectViewAttributes(attachInfo, visibility);
8961    }
8962
8963    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8964        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8965            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8966                attachInfo.mKeepScreenOn = true;
8967            }
8968            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8969            ListenerInfo li = mListenerInfo;
8970            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8971                attachInfo.mHasSystemUiListeners = true;
8972            }
8973        }
8974    }
8975
8976    void needGlobalAttributesUpdate(boolean force) {
8977        final AttachInfo ai = mAttachInfo;
8978        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8979            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8980                    || ai.mHasSystemUiListeners) {
8981                ai.mRecomputeGlobalAttributes = true;
8982            }
8983        }
8984    }
8985
8986    /**
8987     * Returns whether the device is currently in touch mode.  Touch mode is entered
8988     * once the user begins interacting with the device by touch, and affects various
8989     * things like whether focus is always visible to the user.
8990     *
8991     * @return Whether the device is in touch mode.
8992     */
8993    @ViewDebug.ExportedProperty
8994    public boolean isInTouchMode() {
8995        if (mAttachInfo != null) {
8996            return mAttachInfo.mInTouchMode;
8997        } else {
8998            return ViewRootImpl.isInTouchMode();
8999        }
9000    }
9001
9002    /**
9003     * Returns the context the view is running in, through which it can
9004     * access the current theme, resources, etc.
9005     *
9006     * @return The view's Context.
9007     */
9008    @ViewDebug.CapturedViewProperty
9009    public final Context getContext() {
9010        return mContext;
9011    }
9012
9013    /**
9014     * Handle a key event before it is processed by any input method
9015     * associated with the view hierarchy.  This can be used to intercept
9016     * key events in special situations before the IME consumes them; a
9017     * typical example would be handling the BACK key to update the application's
9018     * UI instead of allowing the IME to see it and close itself.
9019     *
9020     * @param keyCode The value in event.getKeyCode().
9021     * @param event Description of the key event.
9022     * @return If you handled the event, return true. If you want to allow the
9023     *         event to be handled by the next receiver, return false.
9024     */
9025    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9026        return false;
9027    }
9028
9029    /**
9030     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9031     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9032     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9033     * is released, if the view is enabled and clickable.
9034     *
9035     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9036     * although some may elect to do so in some situations. Do not rely on this to
9037     * catch software key presses.
9038     *
9039     * @param keyCode A key code that represents the button pressed, from
9040     *                {@link android.view.KeyEvent}.
9041     * @param event   The KeyEvent object that defines the button action.
9042     */
9043    public boolean onKeyDown(int keyCode, KeyEvent event) {
9044        boolean result = false;
9045
9046        if (KeyEvent.isConfirmKey(keyCode)) {
9047            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9048                return true;
9049            }
9050            // Long clickable items don't necessarily have to be clickable
9051            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9052                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9053                    (event.getRepeatCount() == 0)) {
9054                setPressed(true);
9055                checkForLongClick(0);
9056                return true;
9057            }
9058        }
9059        return result;
9060    }
9061
9062    /**
9063     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9064     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9065     * the event).
9066     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9067     * although some may elect to do so in some situations. Do not rely on this to
9068     * catch software key presses.
9069     */
9070    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9071        return false;
9072    }
9073
9074    /**
9075     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9076     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9077     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9078     * {@link KeyEvent#KEYCODE_ENTER} is released.
9079     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9080     * although some may elect to do so in some situations. Do not rely on this to
9081     * catch software key presses.
9082     *
9083     * @param keyCode A key code that represents the button pressed, from
9084     *                {@link android.view.KeyEvent}.
9085     * @param event   The KeyEvent object that defines the button action.
9086     */
9087    public boolean onKeyUp(int keyCode, KeyEvent event) {
9088        if (KeyEvent.isConfirmKey(keyCode)) {
9089            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9090                return true;
9091            }
9092            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9093                setPressed(false);
9094
9095                if (!mHasPerformedLongPress) {
9096                    // This is a tap, so remove the longpress check
9097                    removeLongPressCallback();
9098                    return performClick();
9099                }
9100            }
9101        }
9102        return false;
9103    }
9104
9105    /**
9106     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9107     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9108     * the event).
9109     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9110     * although some may elect to do so in some situations. Do not rely on this to
9111     * catch software key presses.
9112     *
9113     * @param keyCode     A key code that represents the button pressed, from
9114     *                    {@link android.view.KeyEvent}.
9115     * @param repeatCount The number of times the action was made.
9116     * @param event       The KeyEvent object that defines the button action.
9117     */
9118    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9119        return false;
9120    }
9121
9122    /**
9123     * Called on the focused view when a key shortcut event is not handled.
9124     * Override this method to implement local key shortcuts for the View.
9125     * Key shortcuts can also be implemented by setting the
9126     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9127     *
9128     * @param keyCode The value in event.getKeyCode().
9129     * @param event Description of the key event.
9130     * @return If you handled the event, return true. If you want to allow the
9131     *         event to be handled by the next receiver, return false.
9132     */
9133    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9134        return false;
9135    }
9136
9137    /**
9138     * Check whether the called view is a text editor, in which case it
9139     * would make sense to automatically display a soft input window for
9140     * it.  Subclasses should override this if they implement
9141     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9142     * a call on that method would return a non-null InputConnection, and
9143     * they are really a first-class editor that the user would normally
9144     * start typing on when the go into a window containing your view.
9145     *
9146     * <p>The default implementation always returns false.  This does
9147     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9148     * will not be called or the user can not otherwise perform edits on your
9149     * view; it is just a hint to the system that this is not the primary
9150     * purpose of this view.
9151     *
9152     * @return Returns true if this view is a text editor, else false.
9153     */
9154    public boolean onCheckIsTextEditor() {
9155        return false;
9156    }
9157
9158    /**
9159     * Create a new InputConnection for an InputMethod to interact
9160     * with the view.  The default implementation returns null, since it doesn't
9161     * support input methods.  You can override this to implement such support.
9162     * This is only needed for views that take focus and text input.
9163     *
9164     * <p>When implementing this, you probably also want to implement
9165     * {@link #onCheckIsTextEditor()} to indicate you will return a
9166     * non-null InputConnection.</p>
9167     *
9168     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9169     * object correctly and in its entirety, so that the connected IME can rely
9170     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9171     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9172     * must be filled in with the correct cursor position for IMEs to work correctly
9173     * with your application.</p>
9174     *
9175     * @param outAttrs Fill in with attribute information about the connection.
9176     */
9177    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9178        return null;
9179    }
9180
9181    /**
9182     * Called by the {@link android.view.inputmethod.InputMethodManager}
9183     * when a view who is not the current
9184     * input connection target is trying to make a call on the manager.  The
9185     * default implementation returns false; you can override this to return
9186     * true for certain views if you are performing InputConnection proxying
9187     * to them.
9188     * @param view The View that is making the InputMethodManager call.
9189     * @return Return true to allow the call, false to reject.
9190     */
9191    public boolean checkInputConnectionProxy(View view) {
9192        return false;
9193    }
9194
9195    /**
9196     * Show the context menu for this view. It is not safe to hold on to the
9197     * menu after returning from this method.
9198     *
9199     * You should normally not overload this method. Overload
9200     * {@link #onCreateContextMenu(ContextMenu)} or define an
9201     * {@link OnCreateContextMenuListener} to add items to the context menu.
9202     *
9203     * @param menu The context menu to populate
9204     */
9205    public void createContextMenu(ContextMenu menu) {
9206        ContextMenuInfo menuInfo = getContextMenuInfo();
9207
9208        // Sets the current menu info so all items added to menu will have
9209        // my extra info set.
9210        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9211
9212        onCreateContextMenu(menu);
9213        ListenerInfo li = mListenerInfo;
9214        if (li != null && li.mOnCreateContextMenuListener != null) {
9215            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9216        }
9217
9218        // Clear the extra information so subsequent items that aren't mine don't
9219        // have my extra info.
9220        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9221
9222        if (mParent != null) {
9223            mParent.createContextMenu(menu);
9224        }
9225    }
9226
9227    /**
9228     * Views should implement this if they have extra information to associate
9229     * with the context menu. The return result is supplied as a parameter to
9230     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9231     * callback.
9232     *
9233     * @return Extra information about the item for which the context menu
9234     *         should be shown. This information will vary across different
9235     *         subclasses of View.
9236     */
9237    protected ContextMenuInfo getContextMenuInfo() {
9238        return null;
9239    }
9240
9241    /**
9242     * Views should implement this if the view itself is going to add items to
9243     * the context menu.
9244     *
9245     * @param menu the context menu to populate
9246     */
9247    protected void onCreateContextMenu(ContextMenu menu) {
9248    }
9249
9250    /**
9251     * Implement this method to handle trackball motion events.  The
9252     * <em>relative</em> movement of the trackball since the last event
9253     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9254     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9255     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9256     * they will often be fractional values, representing the more fine-grained
9257     * movement information available from a trackball).
9258     *
9259     * @param event The motion event.
9260     * @return True if the event was handled, false otherwise.
9261     */
9262    public boolean onTrackballEvent(MotionEvent event) {
9263        return false;
9264    }
9265
9266    /**
9267     * Implement this method to handle generic motion events.
9268     * <p>
9269     * Generic motion events describe joystick movements, mouse hovers, track pad
9270     * touches, scroll wheel movements and other input events.  The
9271     * {@link MotionEvent#getSource() source} of the motion event specifies
9272     * the class of input that was received.  Implementations of this method
9273     * must examine the bits in the source before processing the event.
9274     * The following code example shows how this is done.
9275     * </p><p>
9276     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9277     * are delivered to the view under the pointer.  All other generic motion events are
9278     * delivered to the focused view.
9279     * </p>
9280     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9281     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9282     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9283     *             // process the joystick movement...
9284     *             return true;
9285     *         }
9286     *     }
9287     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9288     *         switch (event.getAction()) {
9289     *             case MotionEvent.ACTION_HOVER_MOVE:
9290     *                 // process the mouse hover movement...
9291     *                 return true;
9292     *             case MotionEvent.ACTION_SCROLL:
9293     *                 // process the scroll wheel movement...
9294     *                 return true;
9295     *         }
9296     *     }
9297     *     return super.onGenericMotionEvent(event);
9298     * }</pre>
9299     *
9300     * @param event The generic motion event being processed.
9301     * @return True if the event was handled, false otherwise.
9302     */
9303    public boolean onGenericMotionEvent(MotionEvent event) {
9304        return false;
9305    }
9306
9307    /**
9308     * Implement this method to handle hover events.
9309     * <p>
9310     * This method is called whenever a pointer is hovering into, over, or out of the
9311     * bounds of a view and the view is not currently being touched.
9312     * Hover events are represented as pointer events with action
9313     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9314     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9315     * </p>
9316     * <ul>
9317     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9318     * when the pointer enters the bounds of the view.</li>
9319     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9320     * when the pointer has already entered the bounds of the view and has moved.</li>
9321     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9322     * when the pointer has exited the bounds of the view or when the pointer is
9323     * about to go down due to a button click, tap, or similar user action that
9324     * causes the view to be touched.</li>
9325     * </ul>
9326     * <p>
9327     * The view should implement this method to return true to indicate that it is
9328     * handling the hover event, such as by changing its drawable state.
9329     * </p><p>
9330     * The default implementation calls {@link #setHovered} to update the hovered state
9331     * of the view when a hover enter or hover exit event is received, if the view
9332     * is enabled and is clickable.  The default implementation also sends hover
9333     * accessibility events.
9334     * </p>
9335     *
9336     * @param event The motion event that describes the hover.
9337     * @return True if the view handled the hover event.
9338     *
9339     * @see #isHovered
9340     * @see #setHovered
9341     * @see #onHoverChanged
9342     */
9343    public boolean onHoverEvent(MotionEvent event) {
9344        // The root view may receive hover (or touch) events that are outside the bounds of
9345        // the window.  This code ensures that we only send accessibility events for
9346        // hovers that are actually within the bounds of the root view.
9347        final int action = event.getActionMasked();
9348        if (!mSendingHoverAccessibilityEvents) {
9349            if ((action == MotionEvent.ACTION_HOVER_ENTER
9350                    || action == MotionEvent.ACTION_HOVER_MOVE)
9351                    && !hasHoveredChild()
9352                    && pointInView(event.getX(), event.getY())) {
9353                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9354                mSendingHoverAccessibilityEvents = true;
9355            }
9356        } else {
9357            if (action == MotionEvent.ACTION_HOVER_EXIT
9358                    || (action == MotionEvent.ACTION_MOVE
9359                            && !pointInView(event.getX(), event.getY()))) {
9360                mSendingHoverAccessibilityEvents = false;
9361                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9362            }
9363        }
9364
9365        if (isHoverable()) {
9366            switch (action) {
9367                case MotionEvent.ACTION_HOVER_ENTER:
9368                    setHovered(true);
9369                    break;
9370                case MotionEvent.ACTION_HOVER_EXIT:
9371                    setHovered(false);
9372                    break;
9373            }
9374
9375            // Dispatch the event to onGenericMotionEvent before returning true.
9376            // This is to provide compatibility with existing applications that
9377            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9378            // break because of the new default handling for hoverable views
9379            // in onHoverEvent.
9380            // Note that onGenericMotionEvent will be called by default when
9381            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9382            dispatchGenericMotionEventInternal(event);
9383            // The event was already handled by calling setHovered(), so always
9384            // return true.
9385            return true;
9386        }
9387
9388        return false;
9389    }
9390
9391    /**
9392     * Returns true if the view should handle {@link #onHoverEvent}
9393     * by calling {@link #setHovered} to change its hovered state.
9394     *
9395     * @return True if the view is hoverable.
9396     */
9397    private boolean isHoverable() {
9398        final int viewFlags = mViewFlags;
9399        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9400            return false;
9401        }
9402
9403        return (viewFlags & CLICKABLE) == CLICKABLE
9404                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9405    }
9406
9407    /**
9408     * Returns true if the view is currently hovered.
9409     *
9410     * @return True if the view is currently hovered.
9411     *
9412     * @see #setHovered
9413     * @see #onHoverChanged
9414     */
9415    @ViewDebug.ExportedProperty
9416    public boolean isHovered() {
9417        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9418    }
9419
9420    /**
9421     * Sets whether the view is currently hovered.
9422     * <p>
9423     * Calling this method also changes the drawable state of the view.  This
9424     * enables the view to react to hover by using different drawable resources
9425     * to change its appearance.
9426     * </p><p>
9427     * The {@link #onHoverChanged} method is called when the hovered state changes.
9428     * </p>
9429     *
9430     * @param hovered True if the view is hovered.
9431     *
9432     * @see #isHovered
9433     * @see #onHoverChanged
9434     */
9435    public void setHovered(boolean hovered) {
9436        if (hovered) {
9437            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9438                mPrivateFlags |= PFLAG_HOVERED;
9439                refreshDrawableState();
9440                onHoverChanged(true);
9441            }
9442        } else {
9443            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9444                mPrivateFlags &= ~PFLAG_HOVERED;
9445                refreshDrawableState();
9446                onHoverChanged(false);
9447            }
9448        }
9449    }
9450
9451    /**
9452     * Implement this method to handle hover state changes.
9453     * <p>
9454     * This method is called whenever the hover state changes as a result of a
9455     * call to {@link #setHovered}.
9456     * </p>
9457     *
9458     * @param hovered The current hover state, as returned by {@link #isHovered}.
9459     *
9460     * @see #isHovered
9461     * @see #setHovered
9462     */
9463    public void onHoverChanged(boolean hovered) {
9464    }
9465
9466    /**
9467     * Implement this method to handle touch screen motion events.
9468     * <p>
9469     * If this method is used to detect click actions, it is recommended that
9470     * the actions be performed by implementing and calling
9471     * {@link #performClick()}. This will ensure consistent system behavior,
9472     * including:
9473     * <ul>
9474     * <li>obeying click sound preferences
9475     * <li>dispatching OnClickListener calls
9476     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9477     * accessibility features are enabled
9478     * </ul>
9479     *
9480     * @param event The motion event.
9481     * @return True if the event was handled, false otherwise.
9482     */
9483    public boolean onTouchEvent(MotionEvent event) {
9484        final float x = event.getX();
9485        final float y = event.getY();
9486        final int viewFlags = mViewFlags;
9487
9488        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9489            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9490                setPressed(false);
9491            }
9492            // A disabled view that is clickable still consumes the touch
9493            // events, it just doesn't respond to them.
9494            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9495                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9496        }
9497
9498        if (mTouchDelegate != null) {
9499            if (mTouchDelegate.onTouchEvent(event)) {
9500                return true;
9501            }
9502        }
9503
9504        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9505                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9506            switch (event.getAction()) {
9507                case MotionEvent.ACTION_UP:
9508                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9509                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9510                        // take focus if we don't have it already and we should in
9511                        // touch mode.
9512                        boolean focusTaken = false;
9513                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9514                            focusTaken = requestFocus();
9515                        }
9516
9517                        if (prepressed) {
9518                            // The button is being released before we actually
9519                            // showed it as pressed.  Make it show the pressed
9520                            // state now (before scheduling the click) to ensure
9521                            // the user sees it.
9522                            setPressed(true, x, y);
9523                       }
9524
9525                        if (!mHasPerformedLongPress) {
9526                            // This is a tap, so remove the longpress check
9527                            removeLongPressCallback();
9528
9529                            // Only perform take click actions if we were in the pressed state
9530                            if (!focusTaken) {
9531                                // Use a Runnable and post this rather than calling
9532                                // performClick directly. This lets other visual state
9533                                // of the view update before click actions start.
9534                                if (mPerformClick == null) {
9535                                    mPerformClick = new PerformClick();
9536                                }
9537                                if (!post(mPerformClick)) {
9538                                    performClick();
9539                                }
9540                            }
9541                        }
9542
9543                        if (mUnsetPressedState == null) {
9544                            mUnsetPressedState = new UnsetPressedState();
9545                        }
9546
9547                        if (prepressed) {
9548                            postDelayed(mUnsetPressedState,
9549                                    ViewConfiguration.getPressedStateDuration());
9550                        } else if (!post(mUnsetPressedState)) {
9551                            // If the post failed, unpress right now
9552                            mUnsetPressedState.run();
9553                        }
9554
9555                        removeTapCallback();
9556                    }
9557                    break;
9558
9559                case MotionEvent.ACTION_DOWN:
9560                    mHasPerformedLongPress = false;
9561
9562                    if (performButtonActionOnTouchDown(event)) {
9563                        break;
9564                    }
9565
9566                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9567                    boolean isInScrollingContainer = isInScrollingContainer();
9568
9569                    // For views inside a scrolling container, delay the pressed feedback for
9570                    // a short period in case this is a scroll.
9571                    if (isInScrollingContainer) {
9572                        mPrivateFlags |= PFLAG_PREPRESSED;
9573                        if (mPendingCheckForTap == null) {
9574                            mPendingCheckForTap = new CheckForTap();
9575                        }
9576                        mPendingCheckForTap.x = event.getX();
9577                        mPendingCheckForTap.y = event.getY();
9578                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9579                    } else {
9580                        // Not inside a scrolling container, so show the feedback right away
9581                        setPressed(true, x, y);
9582                        checkForLongClick(0);
9583                    }
9584                    break;
9585
9586                case MotionEvent.ACTION_CANCEL:
9587                    setPressed(false);
9588                    removeTapCallback();
9589                    removeLongPressCallback();
9590                    break;
9591
9592                case MotionEvent.ACTION_MOVE:
9593                    drawableHotspotChanged(x, y);
9594
9595                    // Be lenient about moving outside of buttons
9596                    if (!pointInView(x, y, mTouchSlop)) {
9597                        // Outside button
9598                        removeTapCallback();
9599                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9600                            // Remove any future long press/tap checks
9601                            removeLongPressCallback();
9602
9603                            setPressed(false);
9604                        }
9605                    }
9606                    break;
9607            }
9608
9609            return true;
9610        }
9611
9612        return false;
9613    }
9614
9615    /**
9616     * @hide
9617     */
9618    public boolean isInScrollingContainer() {
9619        ViewParent p = getParent();
9620        while (p != null && p instanceof ViewGroup) {
9621            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9622                return true;
9623            }
9624            p = p.getParent();
9625        }
9626        return false;
9627    }
9628
9629    /**
9630     * Remove the longpress detection timer.
9631     */
9632    private void removeLongPressCallback() {
9633        if (mPendingCheckForLongPress != null) {
9634          removeCallbacks(mPendingCheckForLongPress);
9635        }
9636    }
9637
9638    /**
9639     * Remove the pending click action
9640     */
9641    private void removePerformClickCallback() {
9642        if (mPerformClick != null) {
9643            removeCallbacks(mPerformClick);
9644        }
9645    }
9646
9647    /**
9648     * Remove the prepress detection timer.
9649     */
9650    private void removeUnsetPressCallback() {
9651        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9652            setPressed(false);
9653            removeCallbacks(mUnsetPressedState);
9654        }
9655    }
9656
9657    /**
9658     * Remove the tap detection timer.
9659     */
9660    private void removeTapCallback() {
9661        if (mPendingCheckForTap != null) {
9662            mPrivateFlags &= ~PFLAG_PREPRESSED;
9663            removeCallbacks(mPendingCheckForTap);
9664        }
9665    }
9666
9667    /**
9668     * Cancels a pending long press.  Your subclass can use this if you
9669     * want the context menu to come up if the user presses and holds
9670     * at the same place, but you don't want it to come up if they press
9671     * and then move around enough to cause scrolling.
9672     */
9673    public void cancelLongPress() {
9674        removeLongPressCallback();
9675
9676        /*
9677         * The prepressed state handled by the tap callback is a display
9678         * construct, but the tap callback will post a long press callback
9679         * less its own timeout. Remove it here.
9680         */
9681        removeTapCallback();
9682    }
9683
9684    /**
9685     * Remove the pending callback for sending a
9686     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9687     */
9688    private void removeSendViewScrolledAccessibilityEventCallback() {
9689        if (mSendViewScrolledAccessibilityEvent != null) {
9690            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9691            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9692        }
9693    }
9694
9695    /**
9696     * Sets the TouchDelegate for this View.
9697     */
9698    public void setTouchDelegate(TouchDelegate delegate) {
9699        mTouchDelegate = delegate;
9700    }
9701
9702    /**
9703     * Gets the TouchDelegate for this View.
9704     */
9705    public TouchDelegate getTouchDelegate() {
9706        return mTouchDelegate;
9707    }
9708
9709    /**
9710     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9711     *
9712     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9713     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9714     * available. This method should only be called for touch events.
9715     *
9716     * <p class="note">This api is not intended for most applications. Buffered dispatch
9717     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9718     * streams will not improve your input latency. Side effects include: increased latency,
9719     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9720     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9721     * you.</p>
9722     */
9723    public final void requestUnbufferedDispatch(MotionEvent event) {
9724        final int action = event.getAction();
9725        if (mAttachInfo == null
9726                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9727                || !event.isTouchEvent()) {
9728            return;
9729        }
9730        mAttachInfo.mUnbufferedDispatchRequested = true;
9731    }
9732
9733    /**
9734     * Set flags controlling behavior of this view.
9735     *
9736     * @param flags Constant indicating the value which should be set
9737     * @param mask Constant indicating the bit range that should be changed
9738     */
9739    void setFlags(int flags, int mask) {
9740        final boolean accessibilityEnabled =
9741                AccessibilityManager.getInstance(mContext).isEnabled();
9742        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9743
9744        int old = mViewFlags;
9745        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9746
9747        int changed = mViewFlags ^ old;
9748        if (changed == 0) {
9749            return;
9750        }
9751        int privateFlags = mPrivateFlags;
9752
9753        /* Check if the FOCUSABLE bit has changed */
9754        if (((changed & FOCUSABLE_MASK) != 0) &&
9755                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9756            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9757                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9758                /* Give up focus if we are no longer focusable */
9759                clearFocus();
9760            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9761                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9762                /*
9763                 * Tell the view system that we are now available to take focus
9764                 * if no one else already has it.
9765                 */
9766                if (mParent != null) mParent.focusableViewAvailable(this);
9767            }
9768        }
9769
9770        final int newVisibility = flags & VISIBILITY_MASK;
9771        if (newVisibility == VISIBLE) {
9772            if ((changed & VISIBILITY_MASK) != 0) {
9773                /*
9774                 * If this view is becoming visible, invalidate it in case it changed while
9775                 * it was not visible. Marking it drawn ensures that the invalidation will
9776                 * go through.
9777                 */
9778                mPrivateFlags |= PFLAG_DRAWN;
9779                invalidate(true);
9780
9781                needGlobalAttributesUpdate(true);
9782
9783                // a view becoming visible is worth notifying the parent
9784                // about in case nothing has focus.  even if this specific view
9785                // isn't focusable, it may contain something that is, so let
9786                // the root view try to give this focus if nothing else does.
9787                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9788                    mParent.focusableViewAvailable(this);
9789                }
9790            }
9791        }
9792
9793        /* Check if the GONE bit has changed */
9794        if ((changed & GONE) != 0) {
9795            needGlobalAttributesUpdate(false);
9796            requestLayout();
9797
9798            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9799                if (hasFocus()) clearFocus();
9800                clearAccessibilityFocus();
9801                destroyDrawingCache();
9802                if (mParent instanceof View) {
9803                    // GONE views noop invalidation, so invalidate the parent
9804                    ((View) mParent).invalidate(true);
9805                }
9806                // Mark the view drawn to ensure that it gets invalidated properly the next
9807                // time it is visible and gets invalidated
9808                mPrivateFlags |= PFLAG_DRAWN;
9809            }
9810            if (mAttachInfo != null) {
9811                mAttachInfo.mViewVisibilityChanged = true;
9812            }
9813        }
9814
9815        /* Check if the VISIBLE bit has changed */
9816        if ((changed & INVISIBLE) != 0) {
9817            needGlobalAttributesUpdate(false);
9818            /*
9819             * If this view is becoming invisible, set the DRAWN flag so that
9820             * the next invalidate() will not be skipped.
9821             */
9822            mPrivateFlags |= PFLAG_DRAWN;
9823
9824            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9825                // root view becoming invisible shouldn't clear focus and accessibility focus
9826                if (getRootView() != this) {
9827                    if (hasFocus()) clearFocus();
9828                    clearAccessibilityFocus();
9829                }
9830            }
9831            if (mAttachInfo != null) {
9832                mAttachInfo.mViewVisibilityChanged = true;
9833            }
9834        }
9835
9836        if ((changed & VISIBILITY_MASK) != 0) {
9837            // If the view is invisible, cleanup its display list to free up resources
9838            if (newVisibility != VISIBLE && mAttachInfo != null) {
9839                cleanupDraw();
9840            }
9841
9842            if (mParent instanceof ViewGroup) {
9843                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9844                        (changed & VISIBILITY_MASK), newVisibility);
9845                ((View) mParent).invalidate(true);
9846            } else if (mParent != null) {
9847                mParent.invalidateChild(this, null);
9848            }
9849            dispatchVisibilityChanged(this, newVisibility);
9850
9851            notifySubtreeAccessibilityStateChangedIfNeeded();
9852        }
9853
9854        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9855            destroyDrawingCache();
9856        }
9857
9858        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9859            destroyDrawingCache();
9860            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9861            invalidateParentCaches();
9862        }
9863
9864        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9865            destroyDrawingCache();
9866            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9867        }
9868
9869        if ((changed & DRAW_MASK) != 0) {
9870            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9871                if (mBackground != null) {
9872                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9873                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9874                } else {
9875                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9876                }
9877            } else {
9878                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9879            }
9880            requestLayout();
9881            invalidate(true);
9882        }
9883
9884        if ((changed & KEEP_SCREEN_ON) != 0) {
9885            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9886                mParent.recomputeViewAttributes(this);
9887            }
9888        }
9889
9890        if (accessibilityEnabled) {
9891            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9892                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9893                if (oldIncludeForAccessibility != includeForAccessibility()) {
9894                    notifySubtreeAccessibilityStateChangedIfNeeded();
9895                } else {
9896                    notifyViewAccessibilityStateChangedIfNeeded(
9897                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9898                }
9899            } else if ((changed & ENABLED_MASK) != 0) {
9900                notifyViewAccessibilityStateChangedIfNeeded(
9901                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9902            }
9903        }
9904    }
9905
9906    /**
9907     * Change the view's z order in the tree, so it's on top of other sibling
9908     * views. This ordering change may affect layout, if the parent container
9909     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9910     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9911     * method should be followed by calls to {@link #requestLayout()} and
9912     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9913     * with the new child ordering.
9914     *
9915     * @see ViewGroup#bringChildToFront(View)
9916     */
9917    public void bringToFront() {
9918        if (mParent != null) {
9919            mParent.bringChildToFront(this);
9920        }
9921    }
9922
9923    /**
9924     * This is called in response to an internal scroll in this view (i.e., the
9925     * view scrolled its own contents). This is typically as a result of
9926     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9927     * called.
9928     *
9929     * @param l Current horizontal scroll origin.
9930     * @param t Current vertical scroll origin.
9931     * @param oldl Previous horizontal scroll origin.
9932     * @param oldt Previous vertical scroll origin.
9933     */
9934    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9935        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9936            postSendViewScrolledAccessibilityEventCallback();
9937        }
9938
9939        mBackgroundSizeChanged = true;
9940
9941        final AttachInfo ai = mAttachInfo;
9942        if (ai != null) {
9943            ai.mViewScrollChanged = true;
9944        }
9945
9946        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
9947            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
9948        }
9949    }
9950
9951    /**
9952     * Interface definition for a callback to be invoked when the scroll
9953     * position of a view changes.
9954     *
9955     * @hide Only used internally.
9956     */
9957    public interface OnScrollChangeListener {
9958        /**
9959         * Called when the scroll position of a view changes.
9960         *
9961         * @param v The view whose scroll position has changed.
9962         * @param scrollX Current horizontal scroll origin.
9963         * @param scrollY Current vertical scroll origin.
9964         * @param oldScrollX Previous horizontal scroll origin.
9965         * @param oldScrollY Previous vertical scroll origin.
9966         */
9967        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
9968    }
9969
9970    /**
9971     * Interface definition for a callback to be invoked when the layout bounds of a view
9972     * changes due to layout processing.
9973     */
9974    public interface OnLayoutChangeListener {
9975        /**
9976         * Called when the layout bounds of a view changes due to layout processing.
9977         *
9978         * @param v The view whose bounds have changed.
9979         * @param left The new value of the view's left property.
9980         * @param top The new value of the view's top property.
9981         * @param right The new value of the view's right property.
9982         * @param bottom The new value of the view's bottom property.
9983         * @param oldLeft The previous value of the view's left property.
9984         * @param oldTop The previous value of the view's top property.
9985         * @param oldRight The previous value of the view's right property.
9986         * @param oldBottom The previous value of the view's bottom property.
9987         */
9988        void onLayoutChange(View v, int left, int top, int right, int bottom,
9989            int oldLeft, int oldTop, int oldRight, int oldBottom);
9990    }
9991
9992    /**
9993     * This is called during layout when the size of this view has changed. If
9994     * you were just added to the view hierarchy, you're called with the old
9995     * values of 0.
9996     *
9997     * @param w Current width of this view.
9998     * @param h Current height of this view.
9999     * @param oldw Old width of this view.
10000     * @param oldh Old height of this view.
10001     */
10002    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10003    }
10004
10005    /**
10006     * Called by draw to draw the child views. This may be overridden
10007     * by derived classes to gain control just before its children are drawn
10008     * (but after its own view has been drawn).
10009     * @param canvas the canvas on which to draw the view
10010     */
10011    protected void dispatchDraw(Canvas canvas) {
10012
10013    }
10014
10015    /**
10016     * Gets the parent of this view. Note that the parent is a
10017     * ViewParent and not necessarily a View.
10018     *
10019     * @return Parent of this view.
10020     */
10021    public final ViewParent getParent() {
10022        return mParent;
10023    }
10024
10025    /**
10026     * Set the horizontal scrolled position of your view. This will cause a call to
10027     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10028     * invalidated.
10029     * @param value the x position to scroll to
10030     */
10031    public void setScrollX(int value) {
10032        scrollTo(value, mScrollY);
10033    }
10034
10035    /**
10036     * Set the vertical scrolled position of your view. This will cause a call to
10037     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10038     * invalidated.
10039     * @param value the y position to scroll to
10040     */
10041    public void setScrollY(int value) {
10042        scrollTo(mScrollX, value);
10043    }
10044
10045    /**
10046     * Return the scrolled left position of this view. This is the left edge of
10047     * the displayed part of your view. You do not need to draw any pixels
10048     * farther left, since those are outside of the frame of your view on
10049     * screen.
10050     *
10051     * @return The left edge of the displayed part of your view, in pixels.
10052     */
10053    public final int getScrollX() {
10054        return mScrollX;
10055    }
10056
10057    /**
10058     * Return the scrolled top position of this view. This is the top edge of
10059     * the displayed part of your view. You do not need to draw any pixels above
10060     * it, since those are outside of the frame of your view on screen.
10061     *
10062     * @return The top edge of the displayed part of your view, in pixels.
10063     */
10064    public final int getScrollY() {
10065        return mScrollY;
10066    }
10067
10068    /**
10069     * Return the width of the your view.
10070     *
10071     * @return The width of your view, in pixels.
10072     */
10073    @ViewDebug.ExportedProperty(category = "layout")
10074    public final int getWidth() {
10075        return mRight - mLeft;
10076    }
10077
10078    /**
10079     * Return the height of your view.
10080     *
10081     * @return The height of your view, in pixels.
10082     */
10083    @ViewDebug.ExportedProperty(category = "layout")
10084    public final int getHeight() {
10085        return mBottom - mTop;
10086    }
10087
10088    /**
10089     * Return the visible drawing bounds of your view. Fills in the output
10090     * rectangle with the values from getScrollX(), getScrollY(),
10091     * getWidth(), and getHeight(). These bounds do not account for any
10092     * transformation properties currently set on the view, such as
10093     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10094     *
10095     * @param outRect The (scrolled) drawing bounds of the view.
10096     */
10097    public void getDrawingRect(Rect outRect) {
10098        outRect.left = mScrollX;
10099        outRect.top = mScrollY;
10100        outRect.right = mScrollX + (mRight - mLeft);
10101        outRect.bottom = mScrollY + (mBottom - mTop);
10102    }
10103
10104    /**
10105     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10106     * raw width component (that is the result is masked by
10107     * {@link #MEASURED_SIZE_MASK}).
10108     *
10109     * @return The raw measured width of this view.
10110     */
10111    public final int getMeasuredWidth() {
10112        return mMeasuredWidth & MEASURED_SIZE_MASK;
10113    }
10114
10115    /**
10116     * Return the full width measurement information for this view as computed
10117     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10118     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10119     * This should be used during measurement and layout calculations only. Use
10120     * {@link #getWidth()} to see how wide a view is after layout.
10121     *
10122     * @return The measured width of this view as a bit mask.
10123     */
10124    public final int getMeasuredWidthAndState() {
10125        return mMeasuredWidth;
10126    }
10127
10128    /**
10129     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10130     * raw width component (that is the result is masked by
10131     * {@link #MEASURED_SIZE_MASK}).
10132     *
10133     * @return The raw measured height of this view.
10134     */
10135    public final int getMeasuredHeight() {
10136        return mMeasuredHeight & MEASURED_SIZE_MASK;
10137    }
10138
10139    /**
10140     * Return the full height measurement information for this view as computed
10141     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10142     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10143     * This should be used during measurement and layout calculations only. Use
10144     * {@link #getHeight()} to see how wide a view is after layout.
10145     *
10146     * @return The measured width of this view as a bit mask.
10147     */
10148    public final int getMeasuredHeightAndState() {
10149        return mMeasuredHeight;
10150    }
10151
10152    /**
10153     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10154     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10155     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10156     * and the height component is at the shifted bits
10157     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10158     */
10159    public final int getMeasuredState() {
10160        return (mMeasuredWidth&MEASURED_STATE_MASK)
10161                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10162                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10163    }
10164
10165    /**
10166     * The transform matrix of this view, which is calculated based on the current
10167     * rotation, scale, and pivot properties.
10168     *
10169     * @see #getRotation()
10170     * @see #getScaleX()
10171     * @see #getScaleY()
10172     * @see #getPivotX()
10173     * @see #getPivotY()
10174     * @return The current transform matrix for the view
10175     */
10176    public Matrix getMatrix() {
10177        ensureTransformationInfo();
10178        final Matrix matrix = mTransformationInfo.mMatrix;
10179        mRenderNode.getMatrix(matrix);
10180        return matrix;
10181    }
10182
10183    /**
10184     * Returns true if the transform matrix is the identity matrix.
10185     * Recomputes the matrix if necessary.
10186     *
10187     * @return True if the transform matrix is the identity matrix, false otherwise.
10188     */
10189    final boolean hasIdentityMatrix() {
10190        return mRenderNode.hasIdentityMatrix();
10191    }
10192
10193    void ensureTransformationInfo() {
10194        if (mTransformationInfo == null) {
10195            mTransformationInfo = new TransformationInfo();
10196        }
10197    }
10198
10199   /**
10200     * Utility method to retrieve the inverse of the current mMatrix property.
10201     * We cache the matrix to avoid recalculating it when transform properties
10202     * have not changed.
10203     *
10204     * @return The inverse of the current matrix of this view.
10205     * @hide
10206     */
10207    public final Matrix getInverseMatrix() {
10208        ensureTransformationInfo();
10209        if (mTransformationInfo.mInverseMatrix == null) {
10210            mTransformationInfo.mInverseMatrix = new Matrix();
10211        }
10212        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10213        mRenderNode.getInverseMatrix(matrix);
10214        return matrix;
10215    }
10216
10217    /**
10218     * Gets the distance along the Z axis from the camera to this view.
10219     *
10220     * @see #setCameraDistance(float)
10221     *
10222     * @return The distance along the Z axis.
10223     */
10224    public float getCameraDistance() {
10225        final float dpi = mResources.getDisplayMetrics().densityDpi;
10226        return -(mRenderNode.getCameraDistance() * dpi);
10227    }
10228
10229    /**
10230     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10231     * views are drawn) from the camera to this view. The camera's distance
10232     * affects 3D transformations, for instance rotations around the X and Y
10233     * axis. If the rotationX or rotationY properties are changed and this view is
10234     * large (more than half the size of the screen), it is recommended to always
10235     * use a camera distance that's greater than the height (X axis rotation) or
10236     * the width (Y axis rotation) of this view.</p>
10237     *
10238     * <p>The distance of the camera from the view plane can have an affect on the
10239     * perspective distortion of the view when it is rotated around the x or y axis.
10240     * For example, a large distance will result in a large viewing angle, and there
10241     * will not be much perspective distortion of the view as it rotates. A short
10242     * distance may cause much more perspective distortion upon rotation, and can
10243     * also result in some drawing artifacts if the rotated view ends up partially
10244     * behind the camera (which is why the recommendation is to use a distance at
10245     * least as far as the size of the view, if the view is to be rotated.)</p>
10246     *
10247     * <p>The distance is expressed in "depth pixels." The default distance depends
10248     * on the screen density. For instance, on a medium density display, the
10249     * default distance is 1280. On a high density display, the default distance
10250     * is 1920.</p>
10251     *
10252     * <p>If you want to specify a distance that leads to visually consistent
10253     * results across various densities, use the following formula:</p>
10254     * <pre>
10255     * float scale = context.getResources().getDisplayMetrics().density;
10256     * view.setCameraDistance(distance * scale);
10257     * </pre>
10258     *
10259     * <p>The density scale factor of a high density display is 1.5,
10260     * and 1920 = 1280 * 1.5.</p>
10261     *
10262     * @param distance The distance in "depth pixels", if negative the opposite
10263     *        value is used
10264     *
10265     * @see #setRotationX(float)
10266     * @see #setRotationY(float)
10267     */
10268    public void setCameraDistance(float distance) {
10269        final float dpi = mResources.getDisplayMetrics().densityDpi;
10270
10271        invalidateViewProperty(true, false);
10272        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10273        invalidateViewProperty(false, false);
10274
10275        invalidateParentIfNeededAndWasQuickRejected();
10276    }
10277
10278    /**
10279     * The degrees that the view is rotated around the pivot point.
10280     *
10281     * @see #setRotation(float)
10282     * @see #getPivotX()
10283     * @see #getPivotY()
10284     *
10285     * @return The degrees of rotation.
10286     */
10287    @ViewDebug.ExportedProperty(category = "drawing")
10288    public float getRotation() {
10289        return mRenderNode.getRotation();
10290    }
10291
10292    /**
10293     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10294     * result in clockwise rotation.
10295     *
10296     * @param rotation The degrees of rotation.
10297     *
10298     * @see #getRotation()
10299     * @see #getPivotX()
10300     * @see #getPivotY()
10301     * @see #setRotationX(float)
10302     * @see #setRotationY(float)
10303     *
10304     * @attr ref android.R.styleable#View_rotation
10305     */
10306    public void setRotation(float rotation) {
10307        if (rotation != getRotation()) {
10308            // Double-invalidation is necessary to capture view's old and new areas
10309            invalidateViewProperty(true, false);
10310            mRenderNode.setRotation(rotation);
10311            invalidateViewProperty(false, true);
10312
10313            invalidateParentIfNeededAndWasQuickRejected();
10314            notifySubtreeAccessibilityStateChangedIfNeeded();
10315        }
10316    }
10317
10318    /**
10319     * The degrees that the view is rotated around the vertical axis through the pivot point.
10320     *
10321     * @see #getPivotX()
10322     * @see #getPivotY()
10323     * @see #setRotationY(float)
10324     *
10325     * @return The degrees of Y rotation.
10326     */
10327    @ViewDebug.ExportedProperty(category = "drawing")
10328    public float getRotationY() {
10329        return mRenderNode.getRotationY();
10330    }
10331
10332    /**
10333     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10334     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10335     * down the y axis.
10336     *
10337     * When rotating large views, it is recommended to adjust the camera distance
10338     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10339     *
10340     * @param rotationY The degrees of Y rotation.
10341     *
10342     * @see #getRotationY()
10343     * @see #getPivotX()
10344     * @see #getPivotY()
10345     * @see #setRotation(float)
10346     * @see #setRotationX(float)
10347     * @see #setCameraDistance(float)
10348     *
10349     * @attr ref android.R.styleable#View_rotationY
10350     */
10351    public void setRotationY(float rotationY) {
10352        if (rotationY != getRotationY()) {
10353            invalidateViewProperty(true, false);
10354            mRenderNode.setRotationY(rotationY);
10355            invalidateViewProperty(false, true);
10356
10357            invalidateParentIfNeededAndWasQuickRejected();
10358            notifySubtreeAccessibilityStateChangedIfNeeded();
10359        }
10360    }
10361
10362    /**
10363     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10364     *
10365     * @see #getPivotX()
10366     * @see #getPivotY()
10367     * @see #setRotationX(float)
10368     *
10369     * @return The degrees of X rotation.
10370     */
10371    @ViewDebug.ExportedProperty(category = "drawing")
10372    public float getRotationX() {
10373        return mRenderNode.getRotationX();
10374    }
10375
10376    /**
10377     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10378     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10379     * x axis.
10380     *
10381     * When rotating large views, it is recommended to adjust the camera distance
10382     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10383     *
10384     * @param rotationX The degrees of X rotation.
10385     *
10386     * @see #getRotationX()
10387     * @see #getPivotX()
10388     * @see #getPivotY()
10389     * @see #setRotation(float)
10390     * @see #setRotationY(float)
10391     * @see #setCameraDistance(float)
10392     *
10393     * @attr ref android.R.styleable#View_rotationX
10394     */
10395    public void setRotationX(float rotationX) {
10396        if (rotationX != getRotationX()) {
10397            invalidateViewProperty(true, false);
10398            mRenderNode.setRotationX(rotationX);
10399            invalidateViewProperty(false, true);
10400
10401            invalidateParentIfNeededAndWasQuickRejected();
10402            notifySubtreeAccessibilityStateChangedIfNeeded();
10403        }
10404    }
10405
10406    /**
10407     * The amount that the view is scaled in x around the pivot point, as a proportion of
10408     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10409     *
10410     * <p>By default, this is 1.0f.
10411     *
10412     * @see #getPivotX()
10413     * @see #getPivotY()
10414     * @return The scaling factor.
10415     */
10416    @ViewDebug.ExportedProperty(category = "drawing")
10417    public float getScaleX() {
10418        return mRenderNode.getScaleX();
10419    }
10420
10421    /**
10422     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10423     * the view's unscaled width. A value of 1 means that no scaling is applied.
10424     *
10425     * @param scaleX The scaling factor.
10426     * @see #getPivotX()
10427     * @see #getPivotY()
10428     *
10429     * @attr ref android.R.styleable#View_scaleX
10430     */
10431    public void setScaleX(float scaleX) {
10432        if (scaleX != getScaleX()) {
10433            invalidateViewProperty(true, false);
10434            mRenderNode.setScaleX(scaleX);
10435            invalidateViewProperty(false, true);
10436
10437            invalidateParentIfNeededAndWasQuickRejected();
10438            notifySubtreeAccessibilityStateChangedIfNeeded();
10439        }
10440    }
10441
10442    /**
10443     * The amount that the view is scaled in y around the pivot point, as a proportion of
10444     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10445     *
10446     * <p>By default, this is 1.0f.
10447     *
10448     * @see #getPivotX()
10449     * @see #getPivotY()
10450     * @return The scaling factor.
10451     */
10452    @ViewDebug.ExportedProperty(category = "drawing")
10453    public float getScaleY() {
10454        return mRenderNode.getScaleY();
10455    }
10456
10457    /**
10458     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10459     * the view's unscaled width. A value of 1 means that no scaling is applied.
10460     *
10461     * @param scaleY The scaling factor.
10462     * @see #getPivotX()
10463     * @see #getPivotY()
10464     *
10465     * @attr ref android.R.styleable#View_scaleY
10466     */
10467    public void setScaleY(float scaleY) {
10468        if (scaleY != getScaleY()) {
10469            invalidateViewProperty(true, false);
10470            mRenderNode.setScaleY(scaleY);
10471            invalidateViewProperty(false, true);
10472
10473            invalidateParentIfNeededAndWasQuickRejected();
10474            notifySubtreeAccessibilityStateChangedIfNeeded();
10475        }
10476    }
10477
10478    /**
10479     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10480     * and {@link #setScaleX(float) scaled}.
10481     *
10482     * @see #getRotation()
10483     * @see #getScaleX()
10484     * @see #getScaleY()
10485     * @see #getPivotY()
10486     * @return The x location of the pivot point.
10487     *
10488     * @attr ref android.R.styleable#View_transformPivotX
10489     */
10490    @ViewDebug.ExportedProperty(category = "drawing")
10491    public float getPivotX() {
10492        return mRenderNode.getPivotX();
10493    }
10494
10495    /**
10496     * Sets the x location of the point around which the view is
10497     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10498     * By default, the pivot point is centered on the object.
10499     * Setting this property disables this behavior and causes the view to use only the
10500     * explicitly set pivotX and pivotY values.
10501     *
10502     * @param pivotX The x location of the pivot point.
10503     * @see #getRotation()
10504     * @see #getScaleX()
10505     * @see #getScaleY()
10506     * @see #getPivotY()
10507     *
10508     * @attr ref android.R.styleable#View_transformPivotX
10509     */
10510    public void setPivotX(float pivotX) {
10511        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10512            invalidateViewProperty(true, false);
10513            mRenderNode.setPivotX(pivotX);
10514            invalidateViewProperty(false, true);
10515
10516            invalidateParentIfNeededAndWasQuickRejected();
10517        }
10518    }
10519
10520    /**
10521     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10522     * and {@link #setScaleY(float) scaled}.
10523     *
10524     * @see #getRotation()
10525     * @see #getScaleX()
10526     * @see #getScaleY()
10527     * @see #getPivotY()
10528     * @return The y location of the pivot point.
10529     *
10530     * @attr ref android.R.styleable#View_transformPivotY
10531     */
10532    @ViewDebug.ExportedProperty(category = "drawing")
10533    public float getPivotY() {
10534        return mRenderNode.getPivotY();
10535    }
10536
10537    /**
10538     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10539     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10540     * Setting this property disables this behavior and causes the view to use only the
10541     * explicitly set pivotX and pivotY values.
10542     *
10543     * @param pivotY The y location of the pivot point.
10544     * @see #getRotation()
10545     * @see #getScaleX()
10546     * @see #getScaleY()
10547     * @see #getPivotY()
10548     *
10549     * @attr ref android.R.styleable#View_transformPivotY
10550     */
10551    public void setPivotY(float pivotY) {
10552        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10553            invalidateViewProperty(true, false);
10554            mRenderNode.setPivotY(pivotY);
10555            invalidateViewProperty(false, true);
10556
10557            invalidateParentIfNeededAndWasQuickRejected();
10558        }
10559    }
10560
10561    /**
10562     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10563     * completely transparent and 1 means the view is completely opaque.
10564     *
10565     * <p>By default this is 1.0f.
10566     * @return The opacity of the view.
10567     */
10568    @ViewDebug.ExportedProperty(category = "drawing")
10569    public float getAlpha() {
10570        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10571    }
10572
10573    /**
10574     * Returns whether this View has content which overlaps.
10575     *
10576     * <p>This function, intended to be overridden by specific View types, is an optimization when
10577     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10578     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10579     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10580     * directly. An example of overlapping rendering is a TextView with a background image, such as
10581     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10582     * ImageView with only the foreground image. The default implementation returns true; subclasses
10583     * should override if they have cases which can be optimized.</p>
10584     *
10585     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10586     * necessitates that a View return true if it uses the methods internally without passing the
10587     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10588     *
10589     * @return true if the content in this view might overlap, false otherwise.
10590     */
10591    @ViewDebug.ExportedProperty(category = "drawing")
10592    public boolean hasOverlappingRendering() {
10593        return true;
10594    }
10595
10596    /**
10597     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10598     * completely transparent and 1 means the view is completely opaque.</p>
10599     *
10600     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10601     * performance implications, especially for large views. It is best to use the alpha property
10602     * sparingly and transiently, as in the case of fading animations.</p>
10603     *
10604     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10605     * strongly recommended for performance reasons to either override
10606     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10607     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10608     *
10609     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10610     * responsible for applying the opacity itself.</p>
10611     *
10612     * <p>Note that if the view is backed by a
10613     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10614     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10615     * 1.0 will supercede the alpha of the layer paint.</p>
10616     *
10617     * @param alpha The opacity of the view.
10618     *
10619     * @see #hasOverlappingRendering()
10620     * @see #setLayerType(int, android.graphics.Paint)
10621     *
10622     * @attr ref android.R.styleable#View_alpha
10623     */
10624    public void setAlpha(float alpha) {
10625        ensureTransformationInfo();
10626        if (mTransformationInfo.mAlpha != alpha) {
10627            mTransformationInfo.mAlpha = alpha;
10628            if (onSetAlpha((int) (alpha * 255))) {
10629                mPrivateFlags |= PFLAG_ALPHA_SET;
10630                // subclass is handling alpha - don't optimize rendering cache invalidation
10631                invalidateParentCaches();
10632                invalidate(true);
10633            } else {
10634                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10635                invalidateViewProperty(true, false);
10636                mRenderNode.setAlpha(getFinalAlpha());
10637                notifyViewAccessibilityStateChangedIfNeeded(
10638                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10639            }
10640        }
10641    }
10642
10643    /**
10644     * Faster version of setAlpha() which performs the same steps except there are
10645     * no calls to invalidate(). The caller of this function should perform proper invalidation
10646     * on the parent and this object. The return value indicates whether the subclass handles
10647     * alpha (the return value for onSetAlpha()).
10648     *
10649     * @param alpha The new value for the alpha property
10650     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10651     *         the new value for the alpha property is different from the old value
10652     */
10653    boolean setAlphaNoInvalidation(float alpha) {
10654        ensureTransformationInfo();
10655        if (mTransformationInfo.mAlpha != alpha) {
10656            mTransformationInfo.mAlpha = alpha;
10657            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10658            if (subclassHandlesAlpha) {
10659                mPrivateFlags |= PFLAG_ALPHA_SET;
10660                return true;
10661            } else {
10662                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10663                mRenderNode.setAlpha(getFinalAlpha());
10664            }
10665        }
10666        return false;
10667    }
10668
10669    /**
10670     * This property is hidden and intended only for use by the Fade transition, which
10671     * animates it to produce a visual translucency that does not side-effect (or get
10672     * affected by) the real alpha property. This value is composited with the other
10673     * alpha value (and the AlphaAnimation value, when that is present) to produce
10674     * a final visual translucency result, which is what is passed into the DisplayList.
10675     *
10676     * @hide
10677     */
10678    public void setTransitionAlpha(float alpha) {
10679        ensureTransformationInfo();
10680        if (mTransformationInfo.mTransitionAlpha != alpha) {
10681            mTransformationInfo.mTransitionAlpha = alpha;
10682            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10683            invalidateViewProperty(true, false);
10684            mRenderNode.setAlpha(getFinalAlpha());
10685        }
10686    }
10687
10688    /**
10689     * Calculates the visual alpha of this view, which is a combination of the actual
10690     * alpha value and the transitionAlpha value (if set).
10691     */
10692    private float getFinalAlpha() {
10693        if (mTransformationInfo != null) {
10694            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10695        }
10696        return 1;
10697    }
10698
10699    /**
10700     * This property is hidden and intended only for use by the Fade transition, which
10701     * animates it to produce a visual translucency that does not side-effect (or get
10702     * affected by) the real alpha property. This value is composited with the other
10703     * alpha value (and the AlphaAnimation value, when that is present) to produce
10704     * a final visual translucency result, which is what is passed into the DisplayList.
10705     *
10706     * @hide
10707     */
10708    @ViewDebug.ExportedProperty(category = "drawing")
10709    public float getTransitionAlpha() {
10710        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10711    }
10712
10713    /**
10714     * Top position of this view relative to its parent.
10715     *
10716     * @return The top of this view, in pixels.
10717     */
10718    @ViewDebug.CapturedViewProperty
10719    public final int getTop() {
10720        return mTop;
10721    }
10722
10723    /**
10724     * Sets the top position of this view relative to its parent. This method is meant to be called
10725     * by the layout system and should not generally be called otherwise, because the property
10726     * may be changed at any time by the layout.
10727     *
10728     * @param top The top of this view, in pixels.
10729     */
10730    public final void setTop(int top) {
10731        if (top != mTop) {
10732            final boolean matrixIsIdentity = hasIdentityMatrix();
10733            if (matrixIsIdentity) {
10734                if (mAttachInfo != null) {
10735                    int minTop;
10736                    int yLoc;
10737                    if (top < mTop) {
10738                        minTop = top;
10739                        yLoc = top - mTop;
10740                    } else {
10741                        minTop = mTop;
10742                        yLoc = 0;
10743                    }
10744                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10745                }
10746            } else {
10747                // Double-invalidation is necessary to capture view's old and new areas
10748                invalidate(true);
10749            }
10750
10751            int width = mRight - mLeft;
10752            int oldHeight = mBottom - mTop;
10753
10754            mTop = top;
10755            mRenderNode.setTop(mTop);
10756
10757            sizeChange(width, mBottom - mTop, width, oldHeight);
10758
10759            if (!matrixIsIdentity) {
10760                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10761                invalidate(true);
10762            }
10763            mBackgroundSizeChanged = true;
10764            invalidateParentIfNeeded();
10765            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10766                // View was rejected last time it was drawn by its parent; this may have changed
10767                invalidateParentIfNeeded();
10768            }
10769        }
10770    }
10771
10772    /**
10773     * Bottom position of this view relative to its parent.
10774     *
10775     * @return The bottom of this view, in pixels.
10776     */
10777    @ViewDebug.CapturedViewProperty
10778    public final int getBottom() {
10779        return mBottom;
10780    }
10781
10782    /**
10783     * True if this view has changed since the last time being drawn.
10784     *
10785     * @return The dirty state of this view.
10786     */
10787    public boolean isDirty() {
10788        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10789    }
10790
10791    /**
10792     * Sets the bottom position of this view relative to its parent. This method is meant to be
10793     * called by the layout system and should not generally be called otherwise, because the
10794     * property may be changed at any time by the layout.
10795     *
10796     * @param bottom The bottom of this view, in pixels.
10797     */
10798    public final void setBottom(int bottom) {
10799        if (bottom != mBottom) {
10800            final boolean matrixIsIdentity = hasIdentityMatrix();
10801            if (matrixIsIdentity) {
10802                if (mAttachInfo != null) {
10803                    int maxBottom;
10804                    if (bottom < mBottom) {
10805                        maxBottom = mBottom;
10806                    } else {
10807                        maxBottom = bottom;
10808                    }
10809                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10810                }
10811            } else {
10812                // Double-invalidation is necessary to capture view's old and new areas
10813                invalidate(true);
10814            }
10815
10816            int width = mRight - mLeft;
10817            int oldHeight = mBottom - mTop;
10818
10819            mBottom = bottom;
10820            mRenderNode.setBottom(mBottom);
10821
10822            sizeChange(width, mBottom - mTop, width, oldHeight);
10823
10824            if (!matrixIsIdentity) {
10825                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10826                invalidate(true);
10827            }
10828            mBackgroundSizeChanged = true;
10829            invalidateParentIfNeeded();
10830            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10831                // View was rejected last time it was drawn by its parent; this may have changed
10832                invalidateParentIfNeeded();
10833            }
10834        }
10835    }
10836
10837    /**
10838     * Left position of this view relative to its parent.
10839     *
10840     * @return The left edge of this view, in pixels.
10841     */
10842    @ViewDebug.CapturedViewProperty
10843    public final int getLeft() {
10844        return mLeft;
10845    }
10846
10847    /**
10848     * Sets the left position of this view relative to its parent. This method is meant to be called
10849     * by the layout system and should not generally be called otherwise, because the property
10850     * may be changed at any time by the layout.
10851     *
10852     * @param left The left of this view, in pixels.
10853     */
10854    public final void setLeft(int left) {
10855        if (left != mLeft) {
10856            final boolean matrixIsIdentity = hasIdentityMatrix();
10857            if (matrixIsIdentity) {
10858                if (mAttachInfo != null) {
10859                    int minLeft;
10860                    int xLoc;
10861                    if (left < mLeft) {
10862                        minLeft = left;
10863                        xLoc = left - mLeft;
10864                    } else {
10865                        minLeft = mLeft;
10866                        xLoc = 0;
10867                    }
10868                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10869                }
10870            } else {
10871                // Double-invalidation is necessary to capture view's old and new areas
10872                invalidate(true);
10873            }
10874
10875            int oldWidth = mRight - mLeft;
10876            int height = mBottom - mTop;
10877
10878            mLeft = left;
10879            mRenderNode.setLeft(left);
10880
10881            sizeChange(mRight - mLeft, height, oldWidth, height);
10882
10883            if (!matrixIsIdentity) {
10884                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10885                invalidate(true);
10886            }
10887            mBackgroundSizeChanged = true;
10888            invalidateParentIfNeeded();
10889            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10890                // View was rejected last time it was drawn by its parent; this may have changed
10891                invalidateParentIfNeeded();
10892            }
10893        }
10894    }
10895
10896    /**
10897     * Right position of this view relative to its parent.
10898     *
10899     * @return The right edge of this view, in pixels.
10900     */
10901    @ViewDebug.CapturedViewProperty
10902    public final int getRight() {
10903        return mRight;
10904    }
10905
10906    /**
10907     * Sets the right position of this view relative to its parent. This method is meant to be called
10908     * by the layout system and should not generally be called otherwise, because the property
10909     * may be changed at any time by the layout.
10910     *
10911     * @param right The right of this view, in pixels.
10912     */
10913    public final void setRight(int right) {
10914        if (right != mRight) {
10915            final boolean matrixIsIdentity = hasIdentityMatrix();
10916            if (matrixIsIdentity) {
10917                if (mAttachInfo != null) {
10918                    int maxRight;
10919                    if (right < mRight) {
10920                        maxRight = mRight;
10921                    } else {
10922                        maxRight = right;
10923                    }
10924                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10925                }
10926            } else {
10927                // Double-invalidation is necessary to capture view's old and new areas
10928                invalidate(true);
10929            }
10930
10931            int oldWidth = mRight - mLeft;
10932            int height = mBottom - mTop;
10933
10934            mRight = right;
10935            mRenderNode.setRight(mRight);
10936
10937            sizeChange(mRight - mLeft, height, oldWidth, height);
10938
10939            if (!matrixIsIdentity) {
10940                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10941                invalidate(true);
10942            }
10943            mBackgroundSizeChanged = true;
10944            invalidateParentIfNeeded();
10945            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10946                // View was rejected last time it was drawn by its parent; this may have changed
10947                invalidateParentIfNeeded();
10948            }
10949        }
10950    }
10951
10952    /**
10953     * The visual x position of this view, in pixels. This is equivalent to the
10954     * {@link #setTranslationX(float) translationX} property plus the current
10955     * {@link #getLeft() left} property.
10956     *
10957     * @return The visual x position of this view, in pixels.
10958     */
10959    @ViewDebug.ExportedProperty(category = "drawing")
10960    public float getX() {
10961        return mLeft + getTranslationX();
10962    }
10963
10964    /**
10965     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10966     * {@link #setTranslationX(float) translationX} property to be the difference between
10967     * the x value passed in and the current {@link #getLeft() left} property.
10968     *
10969     * @param x The visual x position of this view, in pixels.
10970     */
10971    public void setX(float x) {
10972        setTranslationX(x - mLeft);
10973    }
10974
10975    /**
10976     * The visual y position of this view, in pixels. This is equivalent to the
10977     * {@link #setTranslationY(float) translationY} property plus the current
10978     * {@link #getTop() top} property.
10979     *
10980     * @return The visual y position of this view, in pixels.
10981     */
10982    @ViewDebug.ExportedProperty(category = "drawing")
10983    public float getY() {
10984        return mTop + getTranslationY();
10985    }
10986
10987    /**
10988     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10989     * {@link #setTranslationY(float) translationY} property to be the difference between
10990     * the y value passed in and the current {@link #getTop() top} property.
10991     *
10992     * @param y The visual y position of this view, in pixels.
10993     */
10994    public void setY(float y) {
10995        setTranslationY(y - mTop);
10996    }
10997
10998    /**
10999     * The visual z position of this view, in pixels. This is equivalent to the
11000     * {@link #setTranslationZ(float) translationZ} property plus the current
11001     * {@link #getElevation() elevation} property.
11002     *
11003     * @return The visual z position of this view, in pixels.
11004     */
11005    @ViewDebug.ExportedProperty(category = "drawing")
11006    public float getZ() {
11007        return getElevation() + getTranslationZ();
11008    }
11009
11010    /**
11011     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11012     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11013     * the x value passed in and the current {@link #getElevation() elevation} property.
11014     *
11015     * @param z The visual z position of this view, in pixels.
11016     */
11017    public void setZ(float z) {
11018        setTranslationZ(z - getElevation());
11019    }
11020
11021    /**
11022     * The base elevation of this view relative to its parent, in pixels.
11023     *
11024     * @return The base depth position of the view, in pixels.
11025     */
11026    @ViewDebug.ExportedProperty(category = "drawing")
11027    public float getElevation() {
11028        return mRenderNode.getElevation();
11029    }
11030
11031    /**
11032     * Sets the base elevation of this view, in pixels.
11033     *
11034     * @attr ref android.R.styleable#View_elevation
11035     */
11036    public void setElevation(float elevation) {
11037        if (elevation != getElevation()) {
11038            invalidateViewProperty(true, false);
11039            mRenderNode.setElevation(elevation);
11040            invalidateViewProperty(false, true);
11041
11042            invalidateParentIfNeededAndWasQuickRejected();
11043        }
11044    }
11045
11046    /**
11047     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11048     * This position is post-layout, in addition to wherever the object's
11049     * layout placed it.
11050     *
11051     * @return The horizontal position of this view relative to its left position, in pixels.
11052     */
11053    @ViewDebug.ExportedProperty(category = "drawing")
11054    public float getTranslationX() {
11055        return mRenderNode.getTranslationX();
11056    }
11057
11058    /**
11059     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11060     * This effectively positions the object post-layout, in addition to wherever the object's
11061     * layout placed it.
11062     *
11063     * @param translationX The horizontal position of this view relative to its left position,
11064     * in pixels.
11065     *
11066     * @attr ref android.R.styleable#View_translationX
11067     */
11068    public void setTranslationX(float translationX) {
11069        if (translationX != getTranslationX()) {
11070            invalidateViewProperty(true, false);
11071            mRenderNode.setTranslationX(translationX);
11072            invalidateViewProperty(false, true);
11073
11074            invalidateParentIfNeededAndWasQuickRejected();
11075            notifySubtreeAccessibilityStateChangedIfNeeded();
11076        }
11077    }
11078
11079    /**
11080     * The vertical location of this view relative to its {@link #getTop() top} position.
11081     * This position is post-layout, in addition to wherever the object's
11082     * layout placed it.
11083     *
11084     * @return The vertical position of this view relative to its top position,
11085     * in pixels.
11086     */
11087    @ViewDebug.ExportedProperty(category = "drawing")
11088    public float getTranslationY() {
11089        return mRenderNode.getTranslationY();
11090    }
11091
11092    /**
11093     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11094     * This effectively positions the object post-layout, in addition to wherever the object's
11095     * layout placed it.
11096     *
11097     * @param translationY The vertical position of this view relative to its top position,
11098     * in pixels.
11099     *
11100     * @attr ref android.R.styleable#View_translationY
11101     */
11102    public void setTranslationY(float translationY) {
11103        if (translationY != getTranslationY()) {
11104            invalidateViewProperty(true, false);
11105            mRenderNode.setTranslationY(translationY);
11106            invalidateViewProperty(false, true);
11107
11108            invalidateParentIfNeededAndWasQuickRejected();
11109        }
11110    }
11111
11112    /**
11113     * The depth location of this view relative to its {@link #getElevation() elevation}.
11114     *
11115     * @return The depth of this view relative to its elevation.
11116     */
11117    @ViewDebug.ExportedProperty(category = "drawing")
11118    public float getTranslationZ() {
11119        return mRenderNode.getTranslationZ();
11120    }
11121
11122    /**
11123     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11124     *
11125     * @attr ref android.R.styleable#View_translationZ
11126     */
11127    public void setTranslationZ(float translationZ) {
11128        if (translationZ != getTranslationZ()) {
11129            invalidateViewProperty(true, false);
11130            mRenderNode.setTranslationZ(translationZ);
11131            invalidateViewProperty(false, true);
11132
11133            invalidateParentIfNeededAndWasQuickRejected();
11134        }
11135    }
11136
11137    /** @hide */
11138    public void setAnimationMatrix(Matrix matrix) {
11139        invalidateViewProperty(true, false);
11140        mRenderNode.setAnimationMatrix(matrix);
11141        invalidateViewProperty(false, true);
11142
11143        invalidateParentIfNeededAndWasQuickRejected();
11144    }
11145
11146    /**
11147     * Returns the current StateListAnimator if exists.
11148     *
11149     * @return StateListAnimator or null if it does not exists
11150     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11151     */
11152    public StateListAnimator getStateListAnimator() {
11153        return mStateListAnimator;
11154    }
11155
11156    /**
11157     * Attaches the provided StateListAnimator to this View.
11158     * <p>
11159     * Any previously attached StateListAnimator will be detached.
11160     *
11161     * @param stateListAnimator The StateListAnimator to update the view
11162     * @see {@link android.animation.StateListAnimator}
11163     */
11164    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11165        if (mStateListAnimator == stateListAnimator) {
11166            return;
11167        }
11168        if (mStateListAnimator != null) {
11169            mStateListAnimator.setTarget(null);
11170        }
11171        mStateListAnimator = stateListAnimator;
11172        if (stateListAnimator != null) {
11173            stateListAnimator.setTarget(this);
11174            if (isAttachedToWindow()) {
11175                stateListAnimator.setState(getDrawableState());
11176            }
11177        }
11178    }
11179
11180    /**
11181     * Returns whether the Outline should be used to clip the contents of the View.
11182     * <p>
11183     * Note that this flag will only be respected if the View's Outline returns true from
11184     * {@link Outline#canClip()}.
11185     *
11186     * @see #setOutlineProvider(ViewOutlineProvider)
11187     * @see #setClipToOutline(boolean)
11188     */
11189    public final boolean getClipToOutline() {
11190        return mRenderNode.getClipToOutline();
11191    }
11192
11193    /**
11194     * Sets whether the View's Outline should be used to clip the contents of the View.
11195     * <p>
11196     * Only a single non-rectangular clip can be applied on a View at any time.
11197     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11198     * circular reveal} animation take priority over Outline clipping, and
11199     * child Outline clipping takes priority over Outline clipping done by a
11200     * parent.
11201     * <p>
11202     * Note that this flag will only be respected if the View's Outline returns true from
11203     * {@link Outline#canClip()}.
11204     *
11205     * @see #setOutlineProvider(ViewOutlineProvider)
11206     * @see #getClipToOutline()
11207     */
11208    public void setClipToOutline(boolean clipToOutline) {
11209        damageInParent();
11210        if (getClipToOutline() != clipToOutline) {
11211            mRenderNode.setClipToOutline(clipToOutline);
11212        }
11213    }
11214
11215    // correspond to the enum values of View_outlineProvider
11216    private static final int PROVIDER_BACKGROUND = 0;
11217    private static final int PROVIDER_NONE = 1;
11218    private static final int PROVIDER_BOUNDS = 2;
11219    private static final int PROVIDER_PADDED_BOUNDS = 3;
11220    private void setOutlineProviderFromAttribute(int providerInt) {
11221        switch (providerInt) {
11222            case PROVIDER_BACKGROUND:
11223                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11224                break;
11225            case PROVIDER_NONE:
11226                setOutlineProvider(null);
11227                break;
11228            case PROVIDER_BOUNDS:
11229                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11230                break;
11231            case PROVIDER_PADDED_BOUNDS:
11232                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11233                break;
11234        }
11235    }
11236
11237    /**
11238     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11239     * the shape of the shadow it casts, and enables outline clipping.
11240     * <p>
11241     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11242     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11243     * outline provider with this method allows this behavior to be overridden.
11244     * <p>
11245     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11246     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11247     * <p>
11248     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11249     *
11250     * @see #setClipToOutline(boolean)
11251     * @see #getClipToOutline()
11252     * @see #getOutlineProvider()
11253     */
11254    public void setOutlineProvider(ViewOutlineProvider provider) {
11255        mOutlineProvider = provider;
11256        invalidateOutline();
11257    }
11258
11259    /**
11260     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11261     * that defines the shape of the shadow it casts, and enables outline clipping.
11262     *
11263     * @see #setOutlineProvider(ViewOutlineProvider)
11264     */
11265    public ViewOutlineProvider getOutlineProvider() {
11266        return mOutlineProvider;
11267    }
11268
11269    /**
11270     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11271     *
11272     * @see #setOutlineProvider(ViewOutlineProvider)
11273     */
11274    public void invalidateOutline() {
11275        rebuildOutline();
11276
11277        notifySubtreeAccessibilityStateChangedIfNeeded();
11278        invalidateViewProperty(false, false);
11279    }
11280
11281    /**
11282     * Internal version of {@link #invalidateOutline()} which invalidates the
11283     * outline without invalidating the view itself. This is intended to be called from
11284     * within methods in the View class itself which are the result of the view being
11285     * invalidated already. For example, when we are drawing the background of a View,
11286     * we invalidate the outline in case it changed in the meantime, but we do not
11287     * need to invalidate the view because we're already drawing the background as part
11288     * of drawing the view in response to an earlier invalidation of the view.
11289     */
11290    private void rebuildOutline() {
11291        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11292        if (mAttachInfo == null) return;
11293
11294        if (mOutlineProvider == null) {
11295            // no provider, remove outline
11296            mRenderNode.setOutline(null);
11297        } else {
11298            final Outline outline = mAttachInfo.mTmpOutline;
11299            outline.setEmpty();
11300            outline.setAlpha(1.0f);
11301
11302            mOutlineProvider.getOutline(this, outline);
11303            mRenderNode.setOutline(outline);
11304        }
11305    }
11306
11307    /**
11308     * HierarchyViewer only
11309     *
11310     * @hide
11311     */
11312    @ViewDebug.ExportedProperty(category = "drawing")
11313    public boolean hasShadow() {
11314        return mRenderNode.hasShadow();
11315    }
11316
11317
11318    /** @hide */
11319    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11320        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11321        invalidateViewProperty(false, false);
11322    }
11323
11324    /**
11325     * Hit rectangle in parent's coordinates
11326     *
11327     * @param outRect The hit rectangle of the view.
11328     */
11329    public void getHitRect(Rect outRect) {
11330        if (hasIdentityMatrix() || mAttachInfo == null) {
11331            outRect.set(mLeft, mTop, mRight, mBottom);
11332        } else {
11333            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11334            tmpRect.set(0, 0, getWidth(), getHeight());
11335            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11336            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11337                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11338        }
11339    }
11340
11341    /**
11342     * Determines whether the given point, in local coordinates is inside the view.
11343     */
11344    /*package*/ final boolean pointInView(float localX, float localY) {
11345        return localX >= 0 && localX < (mRight - mLeft)
11346                && localY >= 0 && localY < (mBottom - mTop);
11347    }
11348
11349    /**
11350     * Utility method to determine whether the given point, in local coordinates,
11351     * is inside the view, where the area of the view is expanded by the slop factor.
11352     * This method is called while processing touch-move events to determine if the event
11353     * is still within the view.
11354     *
11355     * @hide
11356     */
11357    public boolean pointInView(float localX, float localY, float slop) {
11358        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11359                localY < ((mBottom - mTop) + slop);
11360    }
11361
11362    /**
11363     * When a view has focus and the user navigates away from it, the next view is searched for
11364     * starting from the rectangle filled in by this method.
11365     *
11366     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11367     * of the view.  However, if your view maintains some idea of internal selection,
11368     * such as a cursor, or a selected row or column, you should override this method and
11369     * fill in a more specific rectangle.
11370     *
11371     * @param r The rectangle to fill in, in this view's coordinates.
11372     */
11373    public void getFocusedRect(Rect r) {
11374        getDrawingRect(r);
11375    }
11376
11377    /**
11378     * If some part of this view is not clipped by any of its parents, then
11379     * return that area in r in global (root) coordinates. To convert r to local
11380     * coordinates (without taking possible View rotations into account), offset
11381     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11382     * If the view is completely clipped or translated out, return false.
11383     *
11384     * @param r If true is returned, r holds the global coordinates of the
11385     *        visible portion of this view.
11386     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11387     *        between this view and its root. globalOffet may be null.
11388     * @return true if r is non-empty (i.e. part of the view is visible at the
11389     *         root level.
11390     */
11391    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11392        int width = mRight - mLeft;
11393        int height = mBottom - mTop;
11394        if (width > 0 && height > 0) {
11395            r.set(0, 0, width, height);
11396            if (globalOffset != null) {
11397                globalOffset.set(-mScrollX, -mScrollY);
11398            }
11399            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11400        }
11401        return false;
11402    }
11403
11404    public final boolean getGlobalVisibleRect(Rect r) {
11405        return getGlobalVisibleRect(r, null);
11406    }
11407
11408    public final boolean getLocalVisibleRect(Rect r) {
11409        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11410        if (getGlobalVisibleRect(r, offset)) {
11411            r.offset(-offset.x, -offset.y); // make r local
11412            return true;
11413        }
11414        return false;
11415    }
11416
11417    /**
11418     * Offset this view's vertical location by the specified number of pixels.
11419     *
11420     * @param offset the number of pixels to offset the view by
11421     */
11422    public void offsetTopAndBottom(int offset) {
11423        if (offset != 0) {
11424            final boolean matrixIsIdentity = hasIdentityMatrix();
11425            if (matrixIsIdentity) {
11426                if (isHardwareAccelerated()) {
11427                    invalidateViewProperty(false, false);
11428                } else {
11429                    final ViewParent p = mParent;
11430                    if (p != null && mAttachInfo != null) {
11431                        final Rect r = mAttachInfo.mTmpInvalRect;
11432                        int minTop;
11433                        int maxBottom;
11434                        int yLoc;
11435                        if (offset < 0) {
11436                            minTop = mTop + offset;
11437                            maxBottom = mBottom;
11438                            yLoc = offset;
11439                        } else {
11440                            minTop = mTop;
11441                            maxBottom = mBottom + offset;
11442                            yLoc = 0;
11443                        }
11444                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11445                        p.invalidateChild(this, r);
11446                    }
11447                }
11448            } else {
11449                invalidateViewProperty(false, false);
11450            }
11451
11452            mTop += offset;
11453            mBottom += offset;
11454            mRenderNode.offsetTopAndBottom(offset);
11455            if (isHardwareAccelerated()) {
11456                invalidateViewProperty(false, false);
11457            } else {
11458                if (!matrixIsIdentity) {
11459                    invalidateViewProperty(false, true);
11460                }
11461                invalidateParentIfNeeded();
11462            }
11463            notifySubtreeAccessibilityStateChangedIfNeeded();
11464        }
11465    }
11466
11467    /**
11468     * Offset this view's horizontal location by the specified amount of pixels.
11469     *
11470     * @param offset the number of pixels to offset the view by
11471     */
11472    public void offsetLeftAndRight(int offset) {
11473        if (offset != 0) {
11474            final boolean matrixIsIdentity = hasIdentityMatrix();
11475            if (matrixIsIdentity) {
11476                if (isHardwareAccelerated()) {
11477                    invalidateViewProperty(false, false);
11478                } else {
11479                    final ViewParent p = mParent;
11480                    if (p != null && mAttachInfo != null) {
11481                        final Rect r = mAttachInfo.mTmpInvalRect;
11482                        int minLeft;
11483                        int maxRight;
11484                        if (offset < 0) {
11485                            minLeft = mLeft + offset;
11486                            maxRight = mRight;
11487                        } else {
11488                            minLeft = mLeft;
11489                            maxRight = mRight + offset;
11490                        }
11491                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11492                        p.invalidateChild(this, r);
11493                    }
11494                }
11495            } else {
11496                invalidateViewProperty(false, false);
11497            }
11498
11499            mLeft += offset;
11500            mRight += offset;
11501            mRenderNode.offsetLeftAndRight(offset);
11502            if (isHardwareAccelerated()) {
11503                invalidateViewProperty(false, false);
11504            } else {
11505                if (!matrixIsIdentity) {
11506                    invalidateViewProperty(false, true);
11507                }
11508                invalidateParentIfNeeded();
11509            }
11510            notifySubtreeAccessibilityStateChangedIfNeeded();
11511        }
11512    }
11513
11514    /**
11515     * Get the LayoutParams associated with this view. All views should have
11516     * layout parameters. These supply parameters to the <i>parent</i> of this
11517     * view specifying how it should be arranged. There are many subclasses of
11518     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11519     * of ViewGroup that are responsible for arranging their children.
11520     *
11521     * This method may return null if this View is not attached to a parent
11522     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11523     * was not invoked successfully. When a View is attached to a parent
11524     * ViewGroup, this method must not return null.
11525     *
11526     * @return The LayoutParams associated with this view, or null if no
11527     *         parameters have been set yet
11528     */
11529    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11530    public ViewGroup.LayoutParams getLayoutParams() {
11531        return mLayoutParams;
11532    }
11533
11534    /**
11535     * Set the layout parameters associated with this view. These supply
11536     * parameters to the <i>parent</i> of this view specifying how it should be
11537     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11538     * correspond to the different subclasses of ViewGroup that are responsible
11539     * for arranging their children.
11540     *
11541     * @param params The layout parameters for this view, cannot be null
11542     */
11543    public void setLayoutParams(ViewGroup.LayoutParams params) {
11544        if (params == null) {
11545            throw new NullPointerException("Layout parameters cannot be null");
11546        }
11547        mLayoutParams = params;
11548        resolveLayoutParams();
11549        if (mParent instanceof ViewGroup) {
11550            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11551        }
11552        requestLayout();
11553    }
11554
11555    /**
11556     * Resolve the layout parameters depending on the resolved layout direction
11557     *
11558     * @hide
11559     */
11560    public void resolveLayoutParams() {
11561        if (mLayoutParams != null) {
11562            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11563        }
11564    }
11565
11566    /**
11567     * Set the scrolled position of your view. This will cause a call to
11568     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11569     * invalidated.
11570     * @param x the x position to scroll to
11571     * @param y the y position to scroll to
11572     */
11573    public void scrollTo(int x, int y) {
11574        if (mScrollX != x || mScrollY != y) {
11575            int oldX = mScrollX;
11576            int oldY = mScrollY;
11577            mScrollX = x;
11578            mScrollY = y;
11579            invalidateParentCaches();
11580            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11581            if (!awakenScrollBars()) {
11582                postInvalidateOnAnimation();
11583            }
11584        }
11585    }
11586
11587    /**
11588     * Move the scrolled position of your view. This will cause a call to
11589     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11590     * invalidated.
11591     * @param x the amount of pixels to scroll by horizontally
11592     * @param y the amount of pixels to scroll by vertically
11593     */
11594    public void scrollBy(int x, int y) {
11595        scrollTo(mScrollX + x, mScrollY + y);
11596    }
11597
11598    /**
11599     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11600     * animation to fade the scrollbars out after a default delay. If a subclass
11601     * provides animated scrolling, the start delay should equal the duration
11602     * of the scrolling animation.</p>
11603     *
11604     * <p>The animation starts only if at least one of the scrollbars is
11605     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11606     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11607     * this method returns true, and false otherwise. If the animation is
11608     * started, this method calls {@link #invalidate()}; in that case the
11609     * caller should not call {@link #invalidate()}.</p>
11610     *
11611     * <p>This method should be invoked every time a subclass directly updates
11612     * the scroll parameters.</p>
11613     *
11614     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11615     * and {@link #scrollTo(int, int)}.</p>
11616     *
11617     * @return true if the animation is played, false otherwise
11618     *
11619     * @see #awakenScrollBars(int)
11620     * @see #scrollBy(int, int)
11621     * @see #scrollTo(int, int)
11622     * @see #isHorizontalScrollBarEnabled()
11623     * @see #isVerticalScrollBarEnabled()
11624     * @see #setHorizontalScrollBarEnabled(boolean)
11625     * @see #setVerticalScrollBarEnabled(boolean)
11626     */
11627    protected boolean awakenScrollBars() {
11628        return mScrollCache != null &&
11629                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11630    }
11631
11632    /**
11633     * Trigger the scrollbars to draw.
11634     * This method differs from awakenScrollBars() only in its default duration.
11635     * initialAwakenScrollBars() will show the scroll bars for longer than
11636     * usual to give the user more of a chance to notice them.
11637     *
11638     * @return true if the animation is played, false otherwise.
11639     */
11640    private boolean initialAwakenScrollBars() {
11641        return mScrollCache != null &&
11642                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11643    }
11644
11645    /**
11646     * <p>
11647     * Trigger the scrollbars to draw. When invoked this method starts an
11648     * animation to fade the scrollbars out after a fixed delay. If a subclass
11649     * provides animated scrolling, the start delay should equal the duration of
11650     * the scrolling animation.
11651     * </p>
11652     *
11653     * <p>
11654     * The animation starts only if at least one of the scrollbars is enabled,
11655     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11656     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11657     * this method returns true, and false otherwise. If the animation is
11658     * started, this method calls {@link #invalidate()}; in that case the caller
11659     * should not call {@link #invalidate()}.
11660     * </p>
11661     *
11662     * <p>
11663     * This method should be invoked everytime a subclass directly updates the
11664     * scroll parameters.
11665     * </p>
11666     *
11667     * @param startDelay the delay, in milliseconds, after which the animation
11668     *        should start; when the delay is 0, the animation starts
11669     *        immediately
11670     * @return true if the animation is played, false otherwise
11671     *
11672     * @see #scrollBy(int, int)
11673     * @see #scrollTo(int, int)
11674     * @see #isHorizontalScrollBarEnabled()
11675     * @see #isVerticalScrollBarEnabled()
11676     * @see #setHorizontalScrollBarEnabled(boolean)
11677     * @see #setVerticalScrollBarEnabled(boolean)
11678     */
11679    protected boolean awakenScrollBars(int startDelay) {
11680        return awakenScrollBars(startDelay, true);
11681    }
11682
11683    /**
11684     * <p>
11685     * Trigger the scrollbars to draw. When invoked this method starts an
11686     * animation to fade the scrollbars out after a fixed delay. If a subclass
11687     * provides animated scrolling, the start delay should equal the duration of
11688     * the scrolling animation.
11689     * </p>
11690     *
11691     * <p>
11692     * The animation starts only if at least one of the scrollbars is enabled,
11693     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11694     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11695     * this method returns true, and false otherwise. If the animation is
11696     * started, this method calls {@link #invalidate()} if the invalidate parameter
11697     * is set to true; in that case the caller
11698     * should not call {@link #invalidate()}.
11699     * </p>
11700     *
11701     * <p>
11702     * This method should be invoked everytime a subclass directly updates the
11703     * scroll parameters.
11704     * </p>
11705     *
11706     * @param startDelay the delay, in milliseconds, after which the animation
11707     *        should start; when the delay is 0, the animation starts
11708     *        immediately
11709     *
11710     * @param invalidate Wheter this method should call invalidate
11711     *
11712     * @return true if the animation is played, false otherwise
11713     *
11714     * @see #scrollBy(int, int)
11715     * @see #scrollTo(int, int)
11716     * @see #isHorizontalScrollBarEnabled()
11717     * @see #isVerticalScrollBarEnabled()
11718     * @see #setHorizontalScrollBarEnabled(boolean)
11719     * @see #setVerticalScrollBarEnabled(boolean)
11720     */
11721    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11722        final ScrollabilityCache scrollCache = mScrollCache;
11723
11724        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11725            return false;
11726        }
11727
11728        if (scrollCache.scrollBar == null) {
11729            scrollCache.scrollBar = new ScrollBarDrawable();
11730        }
11731
11732        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11733
11734            if (invalidate) {
11735                // Invalidate to show the scrollbars
11736                postInvalidateOnAnimation();
11737            }
11738
11739            if (scrollCache.state == ScrollabilityCache.OFF) {
11740                // FIXME: this is copied from WindowManagerService.
11741                // We should get this value from the system when it
11742                // is possible to do so.
11743                final int KEY_REPEAT_FIRST_DELAY = 750;
11744                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11745            }
11746
11747            // Tell mScrollCache when we should start fading. This may
11748            // extend the fade start time if one was already scheduled
11749            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11750            scrollCache.fadeStartTime = fadeStartTime;
11751            scrollCache.state = ScrollabilityCache.ON;
11752
11753            // Schedule our fader to run, unscheduling any old ones first
11754            if (mAttachInfo != null) {
11755                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11756                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11757            }
11758
11759            return true;
11760        }
11761
11762        return false;
11763    }
11764
11765    /**
11766     * Do not invalidate views which are not visible and which are not running an animation. They
11767     * will not get drawn and they should not set dirty flags as if they will be drawn
11768     */
11769    private boolean skipInvalidate() {
11770        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11771                (!(mParent instanceof ViewGroup) ||
11772                        !((ViewGroup) mParent).isViewTransitioning(this));
11773    }
11774
11775    /**
11776     * Mark the area defined by dirty as needing to be drawn. If the view is
11777     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11778     * point in the future.
11779     * <p>
11780     * This must be called from a UI thread. To call from a non-UI thread, call
11781     * {@link #postInvalidate()}.
11782     * <p>
11783     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11784     * {@code dirty}.
11785     *
11786     * @param dirty the rectangle representing the bounds of the dirty region
11787     */
11788    public void invalidate(Rect dirty) {
11789        final int scrollX = mScrollX;
11790        final int scrollY = mScrollY;
11791        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11792                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11793    }
11794
11795    /**
11796     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11797     * coordinates of the dirty rect are relative to the view. If the view is
11798     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11799     * point in the future.
11800     * <p>
11801     * This must be called from a UI thread. To call from a non-UI thread, call
11802     * {@link #postInvalidate()}.
11803     *
11804     * @param l the left position of the dirty region
11805     * @param t the top position of the dirty region
11806     * @param r the right position of the dirty region
11807     * @param b the bottom position of the dirty region
11808     */
11809    public void invalidate(int l, int t, int r, int b) {
11810        final int scrollX = mScrollX;
11811        final int scrollY = mScrollY;
11812        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11813    }
11814
11815    /**
11816     * Invalidate the whole view. If the view is visible,
11817     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11818     * the future.
11819     * <p>
11820     * This must be called from a UI thread. To call from a non-UI thread, call
11821     * {@link #postInvalidate()}.
11822     */
11823    public void invalidate() {
11824        invalidate(true);
11825    }
11826
11827    /**
11828     * This is where the invalidate() work actually happens. A full invalidate()
11829     * causes the drawing cache to be invalidated, but this function can be
11830     * called with invalidateCache set to false to skip that invalidation step
11831     * for cases that do not need it (for example, a component that remains at
11832     * the same dimensions with the same content).
11833     *
11834     * @param invalidateCache Whether the drawing cache for this view should be
11835     *            invalidated as well. This is usually true for a full
11836     *            invalidate, but may be set to false if the View's contents or
11837     *            dimensions have not changed.
11838     */
11839    void invalidate(boolean invalidateCache) {
11840        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11841    }
11842
11843    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11844            boolean fullInvalidate) {
11845        if (mGhostView != null) {
11846            mGhostView.invalidate(true);
11847            return;
11848        }
11849
11850        if (skipInvalidate()) {
11851            return;
11852        }
11853
11854        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11855                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11856                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11857                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11858            if (fullInvalidate) {
11859                mLastIsOpaque = isOpaque();
11860                mPrivateFlags &= ~PFLAG_DRAWN;
11861            }
11862
11863            mPrivateFlags |= PFLAG_DIRTY;
11864
11865            if (invalidateCache) {
11866                mPrivateFlags |= PFLAG_INVALIDATED;
11867                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11868            }
11869
11870            // Propagate the damage rectangle to the parent view.
11871            final AttachInfo ai = mAttachInfo;
11872            final ViewParent p = mParent;
11873            if (p != null && ai != null && l < r && t < b) {
11874                final Rect damage = ai.mTmpInvalRect;
11875                damage.set(l, t, r, b);
11876                p.invalidateChild(this, damage);
11877            }
11878
11879            // Damage the entire projection receiver, if necessary.
11880            if (mBackground != null && mBackground.isProjected()) {
11881                final View receiver = getProjectionReceiver();
11882                if (receiver != null) {
11883                    receiver.damageInParent();
11884                }
11885            }
11886
11887            // Damage the entire IsolatedZVolume receiving this view's shadow.
11888            if (isHardwareAccelerated() && getZ() != 0) {
11889                damageShadowReceiver();
11890            }
11891        }
11892    }
11893
11894    /**
11895     * @return this view's projection receiver, or {@code null} if none exists
11896     */
11897    private View getProjectionReceiver() {
11898        ViewParent p = getParent();
11899        while (p != null && p instanceof View) {
11900            final View v = (View) p;
11901            if (v.isProjectionReceiver()) {
11902                return v;
11903            }
11904            p = p.getParent();
11905        }
11906
11907        return null;
11908    }
11909
11910    /**
11911     * @return whether the view is a projection receiver
11912     */
11913    private boolean isProjectionReceiver() {
11914        return mBackground != null;
11915    }
11916
11917    /**
11918     * Damage area of the screen that can be covered by this View's shadow.
11919     *
11920     * This method will guarantee that any changes to shadows cast by a View
11921     * are damaged on the screen for future redraw.
11922     */
11923    private void damageShadowReceiver() {
11924        final AttachInfo ai = mAttachInfo;
11925        if (ai != null) {
11926            ViewParent p = getParent();
11927            if (p != null && p instanceof ViewGroup) {
11928                final ViewGroup vg = (ViewGroup) p;
11929                vg.damageInParent();
11930            }
11931        }
11932    }
11933
11934    /**
11935     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11936     * set any flags or handle all of the cases handled by the default invalidation methods.
11937     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11938     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11939     * walk up the hierarchy, transforming the dirty rect as necessary.
11940     *
11941     * The method also handles normal invalidation logic if display list properties are not
11942     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11943     * backup approach, to handle these cases used in the various property-setting methods.
11944     *
11945     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11946     * are not being used in this view
11947     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11948     * list properties are not being used in this view
11949     */
11950    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11951        if (!isHardwareAccelerated()
11952                || !mRenderNode.isValid()
11953                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11954            if (invalidateParent) {
11955                invalidateParentCaches();
11956            }
11957            if (forceRedraw) {
11958                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11959            }
11960            invalidate(false);
11961        } else {
11962            damageInParent();
11963        }
11964        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11965            damageShadowReceiver();
11966        }
11967    }
11968
11969    /**
11970     * Tells the parent view to damage this view's bounds.
11971     *
11972     * @hide
11973     */
11974    protected void damageInParent() {
11975        final AttachInfo ai = mAttachInfo;
11976        final ViewParent p = mParent;
11977        if (p != null && ai != null) {
11978            final Rect r = ai.mTmpInvalRect;
11979            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11980            if (mParent instanceof ViewGroup) {
11981                ((ViewGroup) mParent).damageChild(this, r);
11982            } else {
11983                mParent.invalidateChild(this, r);
11984            }
11985        }
11986    }
11987
11988    /**
11989     * Utility method to transform a given Rect by the current matrix of this view.
11990     */
11991    void transformRect(final Rect rect) {
11992        if (!getMatrix().isIdentity()) {
11993            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11994            boundingRect.set(rect);
11995            getMatrix().mapRect(boundingRect);
11996            rect.set((int) Math.floor(boundingRect.left),
11997                    (int) Math.floor(boundingRect.top),
11998                    (int) Math.ceil(boundingRect.right),
11999                    (int) Math.ceil(boundingRect.bottom));
12000        }
12001    }
12002
12003    /**
12004     * Used to indicate that the parent of this view should clear its caches. This functionality
12005     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12006     * which is necessary when various parent-managed properties of the view change, such as
12007     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12008     * clears the parent caches and does not causes an invalidate event.
12009     *
12010     * @hide
12011     */
12012    protected void invalidateParentCaches() {
12013        if (mParent instanceof View) {
12014            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12015        }
12016    }
12017
12018    /**
12019     * Used to indicate that the parent of this view should be invalidated. This functionality
12020     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12021     * which is necessary when various parent-managed properties of the view change, such as
12022     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12023     * an invalidation event to the parent.
12024     *
12025     * @hide
12026     */
12027    protected void invalidateParentIfNeeded() {
12028        if (isHardwareAccelerated() && mParent instanceof View) {
12029            ((View) mParent).invalidate(true);
12030        }
12031    }
12032
12033    /**
12034     * @hide
12035     */
12036    protected void invalidateParentIfNeededAndWasQuickRejected() {
12037        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12038            // View was rejected last time it was drawn by its parent; this may have changed
12039            invalidateParentIfNeeded();
12040        }
12041    }
12042
12043    /**
12044     * Indicates whether this View is opaque. An opaque View guarantees that it will
12045     * draw all the pixels overlapping its bounds using a fully opaque color.
12046     *
12047     * Subclasses of View should override this method whenever possible to indicate
12048     * whether an instance is opaque. Opaque Views are treated in a special way by
12049     * the View hierarchy, possibly allowing it to perform optimizations during
12050     * invalidate/draw passes.
12051     *
12052     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12053     */
12054    @ViewDebug.ExportedProperty(category = "drawing")
12055    public boolean isOpaque() {
12056        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12057                getFinalAlpha() >= 1.0f;
12058    }
12059
12060    /**
12061     * @hide
12062     */
12063    protected void computeOpaqueFlags() {
12064        // Opaque if:
12065        //   - Has a background
12066        //   - Background is opaque
12067        //   - Doesn't have scrollbars or scrollbars overlay
12068
12069        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12070            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12071        } else {
12072            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12073        }
12074
12075        final int flags = mViewFlags;
12076        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12077                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12078                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12079            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12080        } else {
12081            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12082        }
12083    }
12084
12085    /**
12086     * @hide
12087     */
12088    protected boolean hasOpaqueScrollbars() {
12089        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12090    }
12091
12092    /**
12093     * @return A handler associated with the thread running the View. This
12094     * handler can be used to pump events in the UI events queue.
12095     */
12096    public Handler getHandler() {
12097        final AttachInfo attachInfo = mAttachInfo;
12098        if (attachInfo != null) {
12099            return attachInfo.mHandler;
12100        }
12101        return null;
12102    }
12103
12104    /**
12105     * Gets the view root associated with the View.
12106     * @return The view root, or null if none.
12107     * @hide
12108     */
12109    public ViewRootImpl getViewRootImpl() {
12110        if (mAttachInfo != null) {
12111            return mAttachInfo.mViewRootImpl;
12112        }
12113        return null;
12114    }
12115
12116    /**
12117     * @hide
12118     */
12119    public HardwareRenderer getHardwareRenderer() {
12120        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12121    }
12122
12123    /**
12124     * <p>Causes the Runnable to be added to the message queue.
12125     * The runnable will be run on the user interface thread.</p>
12126     *
12127     * @param action The Runnable that will be executed.
12128     *
12129     * @return Returns true if the Runnable was successfully placed in to the
12130     *         message queue.  Returns false on failure, usually because the
12131     *         looper processing the message queue is exiting.
12132     *
12133     * @see #postDelayed
12134     * @see #removeCallbacks
12135     */
12136    public boolean post(Runnable action) {
12137        final AttachInfo attachInfo = mAttachInfo;
12138        if (attachInfo != null) {
12139            return attachInfo.mHandler.post(action);
12140        }
12141        // Assume that post will succeed later
12142        ViewRootImpl.getRunQueue().post(action);
12143        return true;
12144    }
12145
12146    /**
12147     * <p>Causes the Runnable to be added to the message queue, to be run
12148     * after the specified amount of time elapses.
12149     * The runnable will be run on the user interface thread.</p>
12150     *
12151     * @param action The Runnable that will be executed.
12152     * @param delayMillis The delay (in milliseconds) until the Runnable
12153     *        will be executed.
12154     *
12155     * @return true if the Runnable was successfully placed in to the
12156     *         message queue.  Returns false on failure, usually because the
12157     *         looper processing the message queue is exiting.  Note that a
12158     *         result of true does not mean the Runnable will be processed --
12159     *         if the looper is quit before the delivery time of the message
12160     *         occurs then the message will be dropped.
12161     *
12162     * @see #post
12163     * @see #removeCallbacks
12164     */
12165    public boolean postDelayed(Runnable action, long delayMillis) {
12166        final AttachInfo attachInfo = mAttachInfo;
12167        if (attachInfo != null) {
12168            return attachInfo.mHandler.postDelayed(action, delayMillis);
12169        }
12170        // Assume that post will succeed later
12171        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12172        return true;
12173    }
12174
12175    /**
12176     * <p>Causes the Runnable to execute on the next animation time step.
12177     * The runnable will be run on the user interface thread.</p>
12178     *
12179     * @param action The Runnable that will be executed.
12180     *
12181     * @see #postOnAnimationDelayed
12182     * @see #removeCallbacks
12183     */
12184    public void postOnAnimation(Runnable action) {
12185        final AttachInfo attachInfo = mAttachInfo;
12186        if (attachInfo != null) {
12187            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12188                    Choreographer.CALLBACK_ANIMATION, action, null);
12189        } else {
12190            // Assume that post will succeed later
12191            ViewRootImpl.getRunQueue().post(action);
12192        }
12193    }
12194
12195    /**
12196     * <p>Causes the Runnable to execute on the next animation time step,
12197     * after the specified amount of time elapses.
12198     * The runnable will be run on the user interface thread.</p>
12199     *
12200     * @param action The Runnable that will be executed.
12201     * @param delayMillis The delay (in milliseconds) until the Runnable
12202     *        will be executed.
12203     *
12204     * @see #postOnAnimation
12205     * @see #removeCallbacks
12206     */
12207    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12208        final AttachInfo attachInfo = mAttachInfo;
12209        if (attachInfo != null) {
12210            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12211                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12212        } else {
12213            // Assume that post will succeed later
12214            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12215        }
12216    }
12217
12218    /**
12219     * <p>Removes the specified Runnable from the message queue.</p>
12220     *
12221     * @param action The Runnable to remove from the message handling queue
12222     *
12223     * @return true if this view could ask the Handler to remove the Runnable,
12224     *         false otherwise. When the returned value is true, the Runnable
12225     *         may or may not have been actually removed from the message queue
12226     *         (for instance, if the Runnable was not in the queue already.)
12227     *
12228     * @see #post
12229     * @see #postDelayed
12230     * @see #postOnAnimation
12231     * @see #postOnAnimationDelayed
12232     */
12233    public boolean removeCallbacks(Runnable action) {
12234        if (action != null) {
12235            final AttachInfo attachInfo = mAttachInfo;
12236            if (attachInfo != null) {
12237                attachInfo.mHandler.removeCallbacks(action);
12238                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12239                        Choreographer.CALLBACK_ANIMATION, action, null);
12240            }
12241            // Assume that post will succeed later
12242            ViewRootImpl.getRunQueue().removeCallbacks(action);
12243        }
12244        return true;
12245    }
12246
12247    /**
12248     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12249     * Use this to invalidate the View from a non-UI thread.</p>
12250     *
12251     * <p>This method can be invoked from outside of the UI thread
12252     * only when this View is attached to a window.</p>
12253     *
12254     * @see #invalidate()
12255     * @see #postInvalidateDelayed(long)
12256     */
12257    public void postInvalidate() {
12258        postInvalidateDelayed(0);
12259    }
12260
12261    /**
12262     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12263     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12264     *
12265     * <p>This method can be invoked from outside of the UI thread
12266     * only when this View is attached to a window.</p>
12267     *
12268     * @param left The left coordinate of the rectangle to invalidate.
12269     * @param top The top coordinate of the rectangle to invalidate.
12270     * @param right The right coordinate of the rectangle to invalidate.
12271     * @param bottom The bottom coordinate of the rectangle to invalidate.
12272     *
12273     * @see #invalidate(int, int, int, int)
12274     * @see #invalidate(Rect)
12275     * @see #postInvalidateDelayed(long, int, int, int, int)
12276     */
12277    public void postInvalidate(int left, int top, int right, int bottom) {
12278        postInvalidateDelayed(0, left, top, right, bottom);
12279    }
12280
12281    /**
12282     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12283     * loop. Waits for the specified amount of time.</p>
12284     *
12285     * <p>This method can be invoked from outside of the UI thread
12286     * only when this View is attached to a window.</p>
12287     *
12288     * @param delayMilliseconds the duration in milliseconds to delay the
12289     *         invalidation by
12290     *
12291     * @see #invalidate()
12292     * @see #postInvalidate()
12293     */
12294    public void postInvalidateDelayed(long delayMilliseconds) {
12295        // We try only with the AttachInfo because there's no point in invalidating
12296        // if we are not attached to our window
12297        final AttachInfo attachInfo = mAttachInfo;
12298        if (attachInfo != null) {
12299            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12300        }
12301    }
12302
12303    /**
12304     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12305     * through the event loop. Waits for the specified amount of time.</p>
12306     *
12307     * <p>This method can be invoked from outside of the UI thread
12308     * only when this View is attached to a window.</p>
12309     *
12310     * @param delayMilliseconds the duration in milliseconds to delay the
12311     *         invalidation by
12312     * @param left The left coordinate of the rectangle to invalidate.
12313     * @param top The top coordinate of the rectangle to invalidate.
12314     * @param right The right coordinate of the rectangle to invalidate.
12315     * @param bottom The bottom coordinate of the rectangle to invalidate.
12316     *
12317     * @see #invalidate(int, int, int, int)
12318     * @see #invalidate(Rect)
12319     * @see #postInvalidate(int, int, int, int)
12320     */
12321    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12322            int right, int bottom) {
12323
12324        // We try only with the AttachInfo because there's no point in invalidating
12325        // if we are not attached to our window
12326        final AttachInfo attachInfo = mAttachInfo;
12327        if (attachInfo != null) {
12328            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12329            info.target = this;
12330            info.left = left;
12331            info.top = top;
12332            info.right = right;
12333            info.bottom = bottom;
12334
12335            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12336        }
12337    }
12338
12339    /**
12340     * <p>Cause an invalidate to happen on the next animation time step, typically the
12341     * next display frame.</p>
12342     *
12343     * <p>This method can be invoked from outside of the UI thread
12344     * only when this View is attached to a window.</p>
12345     *
12346     * @see #invalidate()
12347     */
12348    public void postInvalidateOnAnimation() {
12349        // We try only with the AttachInfo because there's no point in invalidating
12350        // if we are not attached to our window
12351        final AttachInfo attachInfo = mAttachInfo;
12352        if (attachInfo != null) {
12353            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12354        }
12355    }
12356
12357    /**
12358     * <p>Cause an invalidate of the specified area to happen on the next animation
12359     * time step, typically the next display frame.</p>
12360     *
12361     * <p>This method can be invoked from outside of the UI thread
12362     * only when this View is attached to a window.</p>
12363     *
12364     * @param left The left coordinate of the rectangle to invalidate.
12365     * @param top The top coordinate of the rectangle to invalidate.
12366     * @param right The right coordinate of the rectangle to invalidate.
12367     * @param bottom The bottom coordinate of the rectangle to invalidate.
12368     *
12369     * @see #invalidate(int, int, int, int)
12370     * @see #invalidate(Rect)
12371     */
12372    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12373        // We try only with the AttachInfo because there's no point in invalidating
12374        // if we are not attached to our window
12375        final AttachInfo attachInfo = mAttachInfo;
12376        if (attachInfo != null) {
12377            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12378            info.target = this;
12379            info.left = left;
12380            info.top = top;
12381            info.right = right;
12382            info.bottom = bottom;
12383
12384            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12385        }
12386    }
12387
12388    /**
12389     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12390     * This event is sent at most once every
12391     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12392     */
12393    private void postSendViewScrolledAccessibilityEventCallback() {
12394        if (mSendViewScrolledAccessibilityEvent == null) {
12395            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12396        }
12397        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12398            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12399            postDelayed(mSendViewScrolledAccessibilityEvent,
12400                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12401        }
12402    }
12403
12404    /**
12405     * Called by a parent to request that a child update its values for mScrollX
12406     * and mScrollY if necessary. This will typically be done if the child is
12407     * animating a scroll using a {@link android.widget.Scroller Scroller}
12408     * object.
12409     */
12410    public void computeScroll() {
12411    }
12412
12413    /**
12414     * <p>Indicate whether the horizontal edges are faded when the view is
12415     * scrolled horizontally.</p>
12416     *
12417     * @return true if the horizontal edges should are faded on scroll, false
12418     *         otherwise
12419     *
12420     * @see #setHorizontalFadingEdgeEnabled(boolean)
12421     *
12422     * @attr ref android.R.styleable#View_requiresFadingEdge
12423     */
12424    public boolean isHorizontalFadingEdgeEnabled() {
12425        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12426    }
12427
12428    /**
12429     * <p>Define whether the horizontal edges should be faded when this view
12430     * is scrolled horizontally.</p>
12431     *
12432     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12433     *                                    be faded when the view is scrolled
12434     *                                    horizontally
12435     *
12436     * @see #isHorizontalFadingEdgeEnabled()
12437     *
12438     * @attr ref android.R.styleable#View_requiresFadingEdge
12439     */
12440    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12441        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12442            if (horizontalFadingEdgeEnabled) {
12443                initScrollCache();
12444            }
12445
12446            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12447        }
12448    }
12449
12450    /**
12451     * <p>Indicate whether the vertical edges are faded when the view is
12452     * scrolled horizontally.</p>
12453     *
12454     * @return true if the vertical edges should are faded on scroll, false
12455     *         otherwise
12456     *
12457     * @see #setVerticalFadingEdgeEnabled(boolean)
12458     *
12459     * @attr ref android.R.styleable#View_requiresFadingEdge
12460     */
12461    public boolean isVerticalFadingEdgeEnabled() {
12462        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12463    }
12464
12465    /**
12466     * <p>Define whether the vertical edges should be faded when this view
12467     * is scrolled vertically.</p>
12468     *
12469     * @param verticalFadingEdgeEnabled true if the vertical edges should
12470     *                                  be faded when the view is scrolled
12471     *                                  vertically
12472     *
12473     * @see #isVerticalFadingEdgeEnabled()
12474     *
12475     * @attr ref android.R.styleable#View_requiresFadingEdge
12476     */
12477    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12478        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12479            if (verticalFadingEdgeEnabled) {
12480                initScrollCache();
12481            }
12482
12483            mViewFlags ^= FADING_EDGE_VERTICAL;
12484        }
12485    }
12486
12487    /**
12488     * Returns the strength, or intensity, of the top faded edge. The strength is
12489     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12490     * returns 0.0 or 1.0 but no value in between.
12491     *
12492     * Subclasses should override this method to provide a smoother fade transition
12493     * when scrolling occurs.
12494     *
12495     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12496     */
12497    protected float getTopFadingEdgeStrength() {
12498        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12499    }
12500
12501    /**
12502     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12503     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12504     * returns 0.0 or 1.0 but no value in between.
12505     *
12506     * Subclasses should override this method to provide a smoother fade transition
12507     * when scrolling occurs.
12508     *
12509     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12510     */
12511    protected float getBottomFadingEdgeStrength() {
12512        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12513                computeVerticalScrollRange() ? 1.0f : 0.0f;
12514    }
12515
12516    /**
12517     * Returns the strength, or intensity, of the left faded edge. The strength is
12518     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12519     * returns 0.0 or 1.0 but no value in between.
12520     *
12521     * Subclasses should override this method to provide a smoother fade transition
12522     * when scrolling occurs.
12523     *
12524     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12525     */
12526    protected float getLeftFadingEdgeStrength() {
12527        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12528    }
12529
12530    /**
12531     * Returns the strength, or intensity, of the right faded edge. The strength is
12532     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12533     * returns 0.0 or 1.0 but no value in between.
12534     *
12535     * Subclasses should override this method to provide a smoother fade transition
12536     * when scrolling occurs.
12537     *
12538     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12539     */
12540    protected float getRightFadingEdgeStrength() {
12541        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12542                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12543    }
12544
12545    /**
12546     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12547     * scrollbar is not drawn by default.</p>
12548     *
12549     * @return true if the horizontal scrollbar should be painted, false
12550     *         otherwise
12551     *
12552     * @see #setHorizontalScrollBarEnabled(boolean)
12553     */
12554    public boolean isHorizontalScrollBarEnabled() {
12555        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12556    }
12557
12558    /**
12559     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12560     * scrollbar is not drawn by default.</p>
12561     *
12562     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12563     *                                   be painted
12564     *
12565     * @see #isHorizontalScrollBarEnabled()
12566     */
12567    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12568        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12569            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12570            computeOpaqueFlags();
12571            resolvePadding();
12572        }
12573    }
12574
12575    /**
12576     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12577     * scrollbar is not drawn by default.</p>
12578     *
12579     * @return true if the vertical scrollbar should be painted, false
12580     *         otherwise
12581     *
12582     * @see #setVerticalScrollBarEnabled(boolean)
12583     */
12584    public boolean isVerticalScrollBarEnabled() {
12585        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12586    }
12587
12588    /**
12589     * <p>Define whether the vertical scrollbar should be drawn or not. The
12590     * scrollbar is not drawn by default.</p>
12591     *
12592     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12593     *                                 be painted
12594     *
12595     * @see #isVerticalScrollBarEnabled()
12596     */
12597    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12598        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12599            mViewFlags ^= SCROLLBARS_VERTICAL;
12600            computeOpaqueFlags();
12601            resolvePadding();
12602        }
12603    }
12604
12605    /**
12606     * @hide
12607     */
12608    protected void recomputePadding() {
12609        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12610    }
12611
12612    /**
12613     * Define whether scrollbars will fade when the view is not scrolling.
12614     *
12615     * @param fadeScrollbars wheter to enable fading
12616     *
12617     * @attr ref android.R.styleable#View_fadeScrollbars
12618     */
12619    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12620        initScrollCache();
12621        final ScrollabilityCache scrollabilityCache = mScrollCache;
12622        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12623        if (fadeScrollbars) {
12624            scrollabilityCache.state = ScrollabilityCache.OFF;
12625        } else {
12626            scrollabilityCache.state = ScrollabilityCache.ON;
12627        }
12628    }
12629
12630    /**
12631     *
12632     * Returns true if scrollbars will fade when this view is not scrolling
12633     *
12634     * @return true if scrollbar fading is enabled
12635     *
12636     * @attr ref android.R.styleable#View_fadeScrollbars
12637     */
12638    public boolean isScrollbarFadingEnabled() {
12639        return mScrollCache != null && mScrollCache.fadeScrollBars;
12640    }
12641
12642    /**
12643     *
12644     * Returns the delay before scrollbars fade.
12645     *
12646     * @return the delay before scrollbars fade
12647     *
12648     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12649     */
12650    public int getScrollBarDefaultDelayBeforeFade() {
12651        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12652                mScrollCache.scrollBarDefaultDelayBeforeFade;
12653    }
12654
12655    /**
12656     * Define the delay before scrollbars fade.
12657     *
12658     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12659     *
12660     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12661     */
12662    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12663        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12664    }
12665
12666    /**
12667     *
12668     * Returns the scrollbar fade duration.
12669     *
12670     * @return the scrollbar fade duration
12671     *
12672     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12673     */
12674    public int getScrollBarFadeDuration() {
12675        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12676                mScrollCache.scrollBarFadeDuration;
12677    }
12678
12679    /**
12680     * Define the scrollbar fade duration.
12681     *
12682     * @param scrollBarFadeDuration - the scrollbar fade duration
12683     *
12684     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12685     */
12686    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12687        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12688    }
12689
12690    /**
12691     *
12692     * Returns the scrollbar size.
12693     *
12694     * @return the scrollbar size
12695     *
12696     * @attr ref android.R.styleable#View_scrollbarSize
12697     */
12698    public int getScrollBarSize() {
12699        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12700                mScrollCache.scrollBarSize;
12701    }
12702
12703    /**
12704     * Define the scrollbar size.
12705     *
12706     * @param scrollBarSize - the scrollbar size
12707     *
12708     * @attr ref android.R.styleable#View_scrollbarSize
12709     */
12710    public void setScrollBarSize(int scrollBarSize) {
12711        getScrollCache().scrollBarSize = scrollBarSize;
12712    }
12713
12714    /**
12715     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12716     * inset. When inset, they add to the padding of the view. And the scrollbars
12717     * can be drawn inside the padding area or on the edge of the view. For example,
12718     * if a view has a background drawable and you want to draw the scrollbars
12719     * inside the padding specified by the drawable, you can use
12720     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12721     * appear at the edge of the view, ignoring the padding, then you can use
12722     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12723     * @param style the style of the scrollbars. Should be one of
12724     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12725     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12726     * @see #SCROLLBARS_INSIDE_OVERLAY
12727     * @see #SCROLLBARS_INSIDE_INSET
12728     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12729     * @see #SCROLLBARS_OUTSIDE_INSET
12730     *
12731     * @attr ref android.R.styleable#View_scrollbarStyle
12732     */
12733    public void setScrollBarStyle(@ScrollBarStyle int style) {
12734        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12735            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12736            computeOpaqueFlags();
12737            resolvePadding();
12738        }
12739    }
12740
12741    /**
12742     * <p>Returns the current scrollbar style.</p>
12743     * @return the current scrollbar style
12744     * @see #SCROLLBARS_INSIDE_OVERLAY
12745     * @see #SCROLLBARS_INSIDE_INSET
12746     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12747     * @see #SCROLLBARS_OUTSIDE_INSET
12748     *
12749     * @attr ref android.R.styleable#View_scrollbarStyle
12750     */
12751    @ViewDebug.ExportedProperty(mapping = {
12752            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12753            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12754            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12755            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12756    })
12757    @ScrollBarStyle
12758    public int getScrollBarStyle() {
12759        return mViewFlags & SCROLLBARS_STYLE_MASK;
12760    }
12761
12762    /**
12763     * <p>Compute the horizontal range that the horizontal scrollbar
12764     * represents.</p>
12765     *
12766     * <p>The range is expressed in arbitrary units that must be the same as the
12767     * units used by {@link #computeHorizontalScrollExtent()} and
12768     * {@link #computeHorizontalScrollOffset()}.</p>
12769     *
12770     * <p>The default range is the drawing width of this view.</p>
12771     *
12772     * @return the total horizontal range represented by the horizontal
12773     *         scrollbar
12774     *
12775     * @see #computeHorizontalScrollExtent()
12776     * @see #computeHorizontalScrollOffset()
12777     * @see android.widget.ScrollBarDrawable
12778     */
12779    protected int computeHorizontalScrollRange() {
12780        return getWidth();
12781    }
12782
12783    /**
12784     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12785     * within the horizontal range. This value is used to compute the position
12786     * of the thumb within the scrollbar's track.</p>
12787     *
12788     * <p>The range is expressed in arbitrary units that must be the same as the
12789     * units used by {@link #computeHorizontalScrollRange()} and
12790     * {@link #computeHorizontalScrollExtent()}.</p>
12791     *
12792     * <p>The default offset is the scroll offset of this view.</p>
12793     *
12794     * @return the horizontal offset of the scrollbar's thumb
12795     *
12796     * @see #computeHorizontalScrollRange()
12797     * @see #computeHorizontalScrollExtent()
12798     * @see android.widget.ScrollBarDrawable
12799     */
12800    protected int computeHorizontalScrollOffset() {
12801        return mScrollX;
12802    }
12803
12804    /**
12805     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12806     * within the horizontal range. This value is used to compute the length
12807     * of the thumb within the scrollbar's track.</p>
12808     *
12809     * <p>The range is expressed in arbitrary units that must be the same as the
12810     * units used by {@link #computeHorizontalScrollRange()} and
12811     * {@link #computeHorizontalScrollOffset()}.</p>
12812     *
12813     * <p>The default extent is the drawing width of this view.</p>
12814     *
12815     * @return the horizontal extent of the scrollbar's thumb
12816     *
12817     * @see #computeHorizontalScrollRange()
12818     * @see #computeHorizontalScrollOffset()
12819     * @see android.widget.ScrollBarDrawable
12820     */
12821    protected int computeHorizontalScrollExtent() {
12822        return getWidth();
12823    }
12824
12825    /**
12826     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12827     *
12828     * <p>The range is expressed in arbitrary units that must be the same as the
12829     * units used by {@link #computeVerticalScrollExtent()} and
12830     * {@link #computeVerticalScrollOffset()}.</p>
12831     *
12832     * @return the total vertical range represented by the vertical scrollbar
12833     *
12834     * <p>The default range is the drawing height of this view.</p>
12835     *
12836     * @see #computeVerticalScrollExtent()
12837     * @see #computeVerticalScrollOffset()
12838     * @see android.widget.ScrollBarDrawable
12839     */
12840    protected int computeVerticalScrollRange() {
12841        return getHeight();
12842    }
12843
12844    /**
12845     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12846     * within the horizontal range. This value is used to compute the position
12847     * of the thumb within the scrollbar's track.</p>
12848     *
12849     * <p>The range is expressed in arbitrary units that must be the same as the
12850     * units used by {@link #computeVerticalScrollRange()} and
12851     * {@link #computeVerticalScrollExtent()}.</p>
12852     *
12853     * <p>The default offset is the scroll offset of this view.</p>
12854     *
12855     * @return the vertical offset of the scrollbar's thumb
12856     *
12857     * @see #computeVerticalScrollRange()
12858     * @see #computeVerticalScrollExtent()
12859     * @see android.widget.ScrollBarDrawable
12860     */
12861    protected int computeVerticalScrollOffset() {
12862        return mScrollY;
12863    }
12864
12865    /**
12866     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12867     * within the vertical range. This value is used to compute the length
12868     * of the thumb within the scrollbar's track.</p>
12869     *
12870     * <p>The range is expressed in arbitrary units that must be the same as the
12871     * units used by {@link #computeVerticalScrollRange()} and
12872     * {@link #computeVerticalScrollOffset()}.</p>
12873     *
12874     * <p>The default extent is the drawing height of this view.</p>
12875     *
12876     * @return the vertical extent of the scrollbar's thumb
12877     *
12878     * @see #computeVerticalScrollRange()
12879     * @see #computeVerticalScrollOffset()
12880     * @see android.widget.ScrollBarDrawable
12881     */
12882    protected int computeVerticalScrollExtent() {
12883        return getHeight();
12884    }
12885
12886    /**
12887     * Check if this view can be scrolled horizontally in a certain direction.
12888     *
12889     * @param direction Negative to check scrolling left, positive to check scrolling right.
12890     * @return true if this view can be scrolled in the specified direction, false otherwise.
12891     */
12892    public boolean canScrollHorizontally(int direction) {
12893        final int offset = computeHorizontalScrollOffset();
12894        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12895        if (range == 0) return false;
12896        if (direction < 0) {
12897            return offset > 0;
12898        } else {
12899            return offset < range - 1;
12900        }
12901    }
12902
12903    /**
12904     * Check if this view can be scrolled vertically in a certain direction.
12905     *
12906     * @param direction Negative to check scrolling up, positive to check scrolling down.
12907     * @return true if this view can be scrolled in the specified direction, false otherwise.
12908     */
12909    public boolean canScrollVertically(int direction) {
12910        final int offset = computeVerticalScrollOffset();
12911        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12912        if (range == 0) return false;
12913        if (direction < 0) {
12914            return offset > 0;
12915        } else {
12916            return offset < range - 1;
12917        }
12918    }
12919
12920    /**
12921     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12922     * scrollbars are painted only if they have been awakened first.</p>
12923     *
12924     * @param canvas the canvas on which to draw the scrollbars
12925     *
12926     * @see #awakenScrollBars(int)
12927     */
12928    protected final void onDrawScrollBars(Canvas canvas) {
12929        // scrollbars are drawn only when the animation is running
12930        final ScrollabilityCache cache = mScrollCache;
12931        if (cache != null) {
12932
12933            int state = cache.state;
12934
12935            if (state == ScrollabilityCache.OFF) {
12936                return;
12937            }
12938
12939            boolean invalidate = false;
12940
12941            if (state == ScrollabilityCache.FADING) {
12942                // We're fading -- get our fade interpolation
12943                if (cache.interpolatorValues == null) {
12944                    cache.interpolatorValues = new float[1];
12945                }
12946
12947                float[] values = cache.interpolatorValues;
12948
12949                // Stops the animation if we're done
12950                if (cache.scrollBarInterpolator.timeToValues(values) ==
12951                        Interpolator.Result.FREEZE_END) {
12952                    cache.state = ScrollabilityCache.OFF;
12953                } else {
12954                    cache.scrollBar.setAlpha(Math.round(values[0]));
12955                }
12956
12957                // This will make the scroll bars inval themselves after
12958                // drawing. We only want this when we're fading so that
12959                // we prevent excessive redraws
12960                invalidate = true;
12961            } else {
12962                // We're just on -- but we may have been fading before so
12963                // reset alpha
12964                cache.scrollBar.setAlpha(255);
12965            }
12966
12967
12968            final int viewFlags = mViewFlags;
12969
12970            final boolean drawHorizontalScrollBar =
12971                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12972            final boolean drawVerticalScrollBar =
12973                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12974                && !isVerticalScrollBarHidden();
12975
12976            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12977                final int width = mRight - mLeft;
12978                final int height = mBottom - mTop;
12979
12980                final ScrollBarDrawable scrollBar = cache.scrollBar;
12981
12982                final int scrollX = mScrollX;
12983                final int scrollY = mScrollY;
12984                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12985
12986                int left;
12987                int top;
12988                int right;
12989                int bottom;
12990
12991                if (drawHorizontalScrollBar) {
12992                    int size = scrollBar.getSize(false);
12993                    if (size <= 0) {
12994                        size = cache.scrollBarSize;
12995                    }
12996
12997                    scrollBar.setParameters(computeHorizontalScrollRange(),
12998                                            computeHorizontalScrollOffset(),
12999                                            computeHorizontalScrollExtent(), false);
13000                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13001                            getVerticalScrollbarWidth() : 0;
13002                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13003                    left = scrollX + (mPaddingLeft & inside);
13004                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13005                    bottom = top + size;
13006                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13007                    if (invalidate) {
13008                        invalidate(left, top, right, bottom);
13009                    }
13010                }
13011
13012                if (drawVerticalScrollBar) {
13013                    int size = scrollBar.getSize(true);
13014                    if (size <= 0) {
13015                        size = cache.scrollBarSize;
13016                    }
13017
13018                    scrollBar.setParameters(computeVerticalScrollRange(),
13019                                            computeVerticalScrollOffset(),
13020                                            computeVerticalScrollExtent(), true);
13021                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13022                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13023                        verticalScrollbarPosition = isLayoutRtl() ?
13024                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13025                    }
13026                    switch (verticalScrollbarPosition) {
13027                        default:
13028                        case SCROLLBAR_POSITION_RIGHT:
13029                            left = scrollX + width - size - (mUserPaddingRight & inside);
13030                            break;
13031                        case SCROLLBAR_POSITION_LEFT:
13032                            left = scrollX + (mUserPaddingLeft & inside);
13033                            break;
13034                    }
13035                    top = scrollY + (mPaddingTop & inside);
13036                    right = left + size;
13037                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13038                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13039                    if (invalidate) {
13040                        invalidate(left, top, right, bottom);
13041                    }
13042                }
13043            }
13044        }
13045    }
13046
13047    /**
13048     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13049     * FastScroller is visible.
13050     * @return whether to temporarily hide the vertical scrollbar
13051     * @hide
13052     */
13053    protected boolean isVerticalScrollBarHidden() {
13054        return false;
13055    }
13056
13057    /**
13058     * <p>Draw the horizontal scrollbar if
13059     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13060     *
13061     * @param canvas the canvas on which to draw the scrollbar
13062     * @param scrollBar the scrollbar's drawable
13063     *
13064     * @see #isHorizontalScrollBarEnabled()
13065     * @see #computeHorizontalScrollRange()
13066     * @see #computeHorizontalScrollExtent()
13067     * @see #computeHorizontalScrollOffset()
13068     * @see android.widget.ScrollBarDrawable
13069     * @hide
13070     */
13071    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13072            int l, int t, int r, int b) {
13073        scrollBar.setBounds(l, t, r, b);
13074        scrollBar.draw(canvas);
13075    }
13076
13077    /**
13078     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13079     * returns true.</p>
13080     *
13081     * @param canvas the canvas on which to draw the scrollbar
13082     * @param scrollBar the scrollbar's drawable
13083     *
13084     * @see #isVerticalScrollBarEnabled()
13085     * @see #computeVerticalScrollRange()
13086     * @see #computeVerticalScrollExtent()
13087     * @see #computeVerticalScrollOffset()
13088     * @see android.widget.ScrollBarDrawable
13089     * @hide
13090     */
13091    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13092            int l, int t, int r, int b) {
13093        scrollBar.setBounds(l, t, r, b);
13094        scrollBar.draw(canvas);
13095    }
13096
13097    /**
13098     * Implement this to do your drawing.
13099     *
13100     * @param canvas the canvas on which the background will be drawn
13101     */
13102    protected void onDraw(Canvas canvas) {
13103    }
13104
13105    /*
13106     * Caller is responsible for calling requestLayout if necessary.
13107     * (This allows addViewInLayout to not request a new layout.)
13108     */
13109    void assignParent(ViewParent parent) {
13110        if (mParent == null) {
13111            mParent = parent;
13112        } else if (parent == null) {
13113            mParent = null;
13114        } else {
13115            throw new RuntimeException("view " + this + " being added, but"
13116                    + " it already has a parent");
13117        }
13118    }
13119
13120    /**
13121     * This is called when the view is attached to a window.  At this point it
13122     * has a Surface and will start drawing.  Note that this function is
13123     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13124     * however it may be called any time before the first onDraw -- including
13125     * before or after {@link #onMeasure(int, int)}.
13126     *
13127     * @see #onDetachedFromWindow()
13128     */
13129    protected void onAttachedToWindow() {
13130        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13131            mParent.requestTransparentRegion(this);
13132        }
13133
13134        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13135            initialAwakenScrollBars();
13136            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13137        }
13138
13139        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13140
13141        jumpDrawablesToCurrentState();
13142
13143        resetSubtreeAccessibilityStateChanged();
13144
13145        // rebuild, since Outline not maintained while View is detached
13146        rebuildOutline();
13147
13148        if (isFocused()) {
13149            InputMethodManager imm = InputMethodManager.peekInstance();
13150            imm.focusIn(this);
13151        }
13152    }
13153
13154    /**
13155     * Resolve all RTL related properties.
13156     *
13157     * @return true if resolution of RTL properties has been done
13158     *
13159     * @hide
13160     */
13161    public boolean resolveRtlPropertiesIfNeeded() {
13162        if (!needRtlPropertiesResolution()) return false;
13163
13164        // Order is important here: LayoutDirection MUST be resolved first
13165        if (!isLayoutDirectionResolved()) {
13166            resolveLayoutDirection();
13167            resolveLayoutParams();
13168        }
13169        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13170        if (!isTextDirectionResolved()) {
13171            resolveTextDirection();
13172        }
13173        if (!isTextAlignmentResolved()) {
13174            resolveTextAlignment();
13175        }
13176        // Should resolve Drawables before Padding because we need the layout direction of the
13177        // Drawable to correctly resolve Padding.
13178        if (!areDrawablesResolved()) {
13179            resolveDrawables();
13180        }
13181        if (!isPaddingResolved()) {
13182            resolvePadding();
13183        }
13184        onRtlPropertiesChanged(getLayoutDirection());
13185        return true;
13186    }
13187
13188    /**
13189     * Reset resolution of all RTL related properties.
13190     *
13191     * @hide
13192     */
13193    public void resetRtlProperties() {
13194        resetResolvedLayoutDirection();
13195        resetResolvedTextDirection();
13196        resetResolvedTextAlignment();
13197        resetResolvedPadding();
13198        resetResolvedDrawables();
13199    }
13200
13201    /**
13202     * @see #onScreenStateChanged(int)
13203     */
13204    void dispatchScreenStateChanged(int screenState) {
13205        onScreenStateChanged(screenState);
13206    }
13207
13208    /**
13209     * This method is called whenever the state of the screen this view is
13210     * attached to changes. A state change will usually occurs when the screen
13211     * turns on or off (whether it happens automatically or the user does it
13212     * manually.)
13213     *
13214     * @param screenState The new state of the screen. Can be either
13215     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13216     */
13217    public void onScreenStateChanged(int screenState) {
13218    }
13219
13220    /**
13221     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13222     */
13223    private boolean hasRtlSupport() {
13224        return mContext.getApplicationInfo().hasRtlSupport();
13225    }
13226
13227    /**
13228     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13229     * RTL not supported)
13230     */
13231    private boolean isRtlCompatibilityMode() {
13232        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13233        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13234    }
13235
13236    /**
13237     * @return true if RTL properties need resolution.
13238     *
13239     */
13240    private boolean needRtlPropertiesResolution() {
13241        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13242    }
13243
13244    /**
13245     * Called when any RTL property (layout direction or text direction or text alignment) has
13246     * been changed.
13247     *
13248     * Subclasses need to override this method to take care of cached information that depends on the
13249     * resolved layout direction, or to inform child views that inherit their layout direction.
13250     *
13251     * The default implementation does nothing.
13252     *
13253     * @param layoutDirection the direction of the layout
13254     *
13255     * @see #LAYOUT_DIRECTION_LTR
13256     * @see #LAYOUT_DIRECTION_RTL
13257     */
13258    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13259    }
13260
13261    /**
13262     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13263     * that the parent directionality can and will be resolved before its children.
13264     *
13265     * @return true if resolution has been done, false otherwise.
13266     *
13267     * @hide
13268     */
13269    public boolean resolveLayoutDirection() {
13270        // Clear any previous layout direction resolution
13271        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13272
13273        if (hasRtlSupport()) {
13274            // Set resolved depending on layout direction
13275            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13276                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13277                case LAYOUT_DIRECTION_INHERIT:
13278                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13279                    // later to get the correct resolved value
13280                    if (!canResolveLayoutDirection()) return false;
13281
13282                    // Parent has not yet resolved, LTR is still the default
13283                    try {
13284                        if (!mParent.isLayoutDirectionResolved()) return false;
13285
13286                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13287                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13288                        }
13289                    } catch (AbstractMethodError e) {
13290                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13291                                " does not fully implement ViewParent", e);
13292                    }
13293                    break;
13294                case LAYOUT_DIRECTION_RTL:
13295                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13296                    break;
13297                case LAYOUT_DIRECTION_LOCALE:
13298                    if((LAYOUT_DIRECTION_RTL ==
13299                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13300                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13301                    }
13302                    break;
13303                default:
13304                    // Nothing to do, LTR by default
13305            }
13306        }
13307
13308        // Set to resolved
13309        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13310        return true;
13311    }
13312
13313    /**
13314     * Check if layout direction resolution can be done.
13315     *
13316     * @return true if layout direction resolution can be done otherwise return false.
13317     */
13318    public boolean canResolveLayoutDirection() {
13319        switch (getRawLayoutDirection()) {
13320            case LAYOUT_DIRECTION_INHERIT:
13321                if (mParent != null) {
13322                    try {
13323                        return mParent.canResolveLayoutDirection();
13324                    } catch (AbstractMethodError e) {
13325                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13326                                " does not fully implement ViewParent", e);
13327                    }
13328                }
13329                return false;
13330
13331            default:
13332                return true;
13333        }
13334    }
13335
13336    /**
13337     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13338     * {@link #onMeasure(int, int)}.
13339     *
13340     * @hide
13341     */
13342    public void resetResolvedLayoutDirection() {
13343        // Reset the current resolved bits
13344        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13345    }
13346
13347    /**
13348     * @return true if the layout direction is inherited.
13349     *
13350     * @hide
13351     */
13352    public boolean isLayoutDirectionInherited() {
13353        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13354    }
13355
13356    /**
13357     * @return true if layout direction has been resolved.
13358     */
13359    public boolean isLayoutDirectionResolved() {
13360        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13361    }
13362
13363    /**
13364     * Return if padding has been resolved
13365     *
13366     * @hide
13367     */
13368    boolean isPaddingResolved() {
13369        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13370    }
13371
13372    /**
13373     * Resolves padding depending on layout direction, if applicable, and
13374     * recomputes internal padding values to adjust for scroll bars.
13375     *
13376     * @hide
13377     */
13378    public void resolvePadding() {
13379        final int resolvedLayoutDirection = getLayoutDirection();
13380
13381        if (!isRtlCompatibilityMode()) {
13382            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13383            // If start / end padding are defined, they will be resolved (hence overriding) to
13384            // left / right or right / left depending on the resolved layout direction.
13385            // If start / end padding are not defined, use the left / right ones.
13386            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13387                Rect padding = sThreadLocal.get();
13388                if (padding == null) {
13389                    padding = new Rect();
13390                    sThreadLocal.set(padding);
13391                }
13392                mBackground.getPadding(padding);
13393                if (!mLeftPaddingDefined) {
13394                    mUserPaddingLeftInitial = padding.left;
13395                }
13396                if (!mRightPaddingDefined) {
13397                    mUserPaddingRightInitial = padding.right;
13398                }
13399            }
13400            switch (resolvedLayoutDirection) {
13401                case LAYOUT_DIRECTION_RTL:
13402                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13403                        mUserPaddingRight = mUserPaddingStart;
13404                    } else {
13405                        mUserPaddingRight = mUserPaddingRightInitial;
13406                    }
13407                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13408                        mUserPaddingLeft = mUserPaddingEnd;
13409                    } else {
13410                        mUserPaddingLeft = mUserPaddingLeftInitial;
13411                    }
13412                    break;
13413                case LAYOUT_DIRECTION_LTR:
13414                default:
13415                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13416                        mUserPaddingLeft = mUserPaddingStart;
13417                    } else {
13418                        mUserPaddingLeft = mUserPaddingLeftInitial;
13419                    }
13420                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13421                        mUserPaddingRight = mUserPaddingEnd;
13422                    } else {
13423                        mUserPaddingRight = mUserPaddingRightInitial;
13424                    }
13425            }
13426
13427            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13428        }
13429
13430        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13431        onRtlPropertiesChanged(resolvedLayoutDirection);
13432
13433        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13434    }
13435
13436    /**
13437     * Reset the resolved layout direction.
13438     *
13439     * @hide
13440     */
13441    public void resetResolvedPadding() {
13442        resetResolvedPaddingInternal();
13443    }
13444
13445    /**
13446     * Used when we only want to reset *this* view's padding and not trigger overrides
13447     * in ViewGroup that reset children too.
13448     */
13449    void resetResolvedPaddingInternal() {
13450        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13451    }
13452
13453    /**
13454     * This is called when the view is detached from a window.  At this point it
13455     * no longer has a surface for drawing.
13456     *
13457     * @see #onAttachedToWindow()
13458     */
13459    protected void onDetachedFromWindow() {
13460    }
13461
13462    /**
13463     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13464     * after onDetachedFromWindow().
13465     *
13466     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13467     * The super method should be called at the end of the overriden method to ensure
13468     * subclasses are destroyed first
13469     *
13470     * @hide
13471     */
13472    protected void onDetachedFromWindowInternal() {
13473        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13474        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13475
13476        removeUnsetPressCallback();
13477        removeLongPressCallback();
13478        removePerformClickCallback();
13479        removeSendViewScrolledAccessibilityEventCallback();
13480        stopNestedScroll();
13481
13482        // Anything that started animating right before detach should already
13483        // be in its final state when re-attached.
13484        jumpDrawablesToCurrentState();
13485
13486        destroyDrawingCache();
13487
13488        cleanupDraw();
13489        mCurrentAnimation = null;
13490    }
13491
13492    private void cleanupDraw() {
13493        resetDisplayList();
13494        if (mAttachInfo != null) {
13495            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13496        }
13497    }
13498
13499    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13500    }
13501
13502    /**
13503     * @return The number of times this view has been attached to a window
13504     */
13505    protected int getWindowAttachCount() {
13506        return mWindowAttachCount;
13507    }
13508
13509    /**
13510     * Retrieve a unique token identifying the window this view is attached to.
13511     * @return Return the window's token for use in
13512     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13513     */
13514    public IBinder getWindowToken() {
13515        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13516    }
13517
13518    /**
13519     * Retrieve the {@link WindowId} for the window this view is
13520     * currently attached to.
13521     */
13522    public WindowId getWindowId() {
13523        if (mAttachInfo == null) {
13524            return null;
13525        }
13526        if (mAttachInfo.mWindowId == null) {
13527            try {
13528                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13529                        mAttachInfo.mWindowToken);
13530                mAttachInfo.mWindowId = new WindowId(
13531                        mAttachInfo.mIWindowId);
13532            } catch (RemoteException e) {
13533            }
13534        }
13535        return mAttachInfo.mWindowId;
13536    }
13537
13538    /**
13539     * Retrieve a unique token identifying the top-level "real" window of
13540     * the window that this view is attached to.  That is, this is like
13541     * {@link #getWindowToken}, except if the window this view in is a panel
13542     * window (attached to another containing window), then the token of
13543     * the containing window is returned instead.
13544     *
13545     * @return Returns the associated window token, either
13546     * {@link #getWindowToken()} or the containing window's token.
13547     */
13548    public IBinder getApplicationWindowToken() {
13549        AttachInfo ai = mAttachInfo;
13550        if (ai != null) {
13551            IBinder appWindowToken = ai.mPanelParentWindowToken;
13552            if (appWindowToken == null) {
13553                appWindowToken = ai.mWindowToken;
13554            }
13555            return appWindowToken;
13556        }
13557        return null;
13558    }
13559
13560    /**
13561     * Gets the logical display to which the view's window has been attached.
13562     *
13563     * @return The logical display, or null if the view is not currently attached to a window.
13564     */
13565    public Display getDisplay() {
13566        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13567    }
13568
13569    /**
13570     * Retrieve private session object this view hierarchy is using to
13571     * communicate with the window manager.
13572     * @return the session object to communicate with the window manager
13573     */
13574    /*package*/ IWindowSession getWindowSession() {
13575        return mAttachInfo != null ? mAttachInfo.mSession : null;
13576    }
13577
13578    /**
13579     * @param info the {@link android.view.View.AttachInfo} to associated with
13580     *        this view
13581     */
13582    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13583        //System.out.println("Attached! " + this);
13584        mAttachInfo = info;
13585        if (mOverlay != null) {
13586            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13587        }
13588        mWindowAttachCount++;
13589        // We will need to evaluate the drawable state at least once.
13590        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13591        if (mFloatingTreeObserver != null) {
13592            info.mTreeObserver.merge(mFloatingTreeObserver);
13593            mFloatingTreeObserver = null;
13594        }
13595        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13596            mAttachInfo.mScrollContainers.add(this);
13597            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13598        }
13599        performCollectViewAttributes(mAttachInfo, visibility);
13600        onAttachedToWindow();
13601
13602        ListenerInfo li = mListenerInfo;
13603        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13604                li != null ? li.mOnAttachStateChangeListeners : null;
13605        if (listeners != null && listeners.size() > 0) {
13606            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13607            // perform the dispatching. The iterator is a safe guard against listeners that
13608            // could mutate the list by calling the various add/remove methods. This prevents
13609            // the array from being modified while we iterate it.
13610            for (OnAttachStateChangeListener listener : listeners) {
13611                listener.onViewAttachedToWindow(this);
13612            }
13613        }
13614
13615        int vis = info.mWindowVisibility;
13616        if (vis != GONE) {
13617            onWindowVisibilityChanged(vis);
13618        }
13619        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13620            // If nobody has evaluated the drawable state yet, then do it now.
13621            refreshDrawableState();
13622        }
13623        needGlobalAttributesUpdate(false);
13624    }
13625
13626    void dispatchDetachedFromWindow() {
13627        AttachInfo info = mAttachInfo;
13628        if (info != null) {
13629            int vis = info.mWindowVisibility;
13630            if (vis != GONE) {
13631                onWindowVisibilityChanged(GONE);
13632            }
13633        }
13634
13635        onDetachedFromWindow();
13636        onDetachedFromWindowInternal();
13637
13638        ListenerInfo li = mListenerInfo;
13639        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13640                li != null ? li.mOnAttachStateChangeListeners : null;
13641        if (listeners != null && listeners.size() > 0) {
13642            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13643            // perform the dispatching. The iterator is a safe guard against listeners that
13644            // could mutate the list by calling the various add/remove methods. This prevents
13645            // the array from being modified while we iterate it.
13646            for (OnAttachStateChangeListener listener : listeners) {
13647                listener.onViewDetachedFromWindow(this);
13648            }
13649        }
13650
13651        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13652            mAttachInfo.mScrollContainers.remove(this);
13653            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13654        }
13655
13656        mAttachInfo = null;
13657        if (mOverlay != null) {
13658            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13659        }
13660    }
13661
13662    /**
13663     * Cancel any deferred high-level input events that were previously posted to the event queue.
13664     *
13665     * <p>Many views post high-level events such as click handlers to the event queue
13666     * to run deferred in order to preserve a desired user experience - clearing visible
13667     * pressed states before executing, etc. This method will abort any events of this nature
13668     * that are currently in flight.</p>
13669     *
13670     * <p>Custom views that generate their own high-level deferred input events should override
13671     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13672     *
13673     * <p>This will also cancel pending input events for any child views.</p>
13674     *
13675     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13676     * This will not impact newer events posted after this call that may occur as a result of
13677     * lower-level input events still waiting in the queue. If you are trying to prevent
13678     * double-submitted  events for the duration of some sort of asynchronous transaction
13679     * you should also take other steps to protect against unexpected double inputs e.g. calling
13680     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13681     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13682     */
13683    public final void cancelPendingInputEvents() {
13684        dispatchCancelPendingInputEvents();
13685    }
13686
13687    /**
13688     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13689     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13690     */
13691    void dispatchCancelPendingInputEvents() {
13692        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13693        onCancelPendingInputEvents();
13694        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13695            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13696                    " did not call through to super.onCancelPendingInputEvents()");
13697        }
13698    }
13699
13700    /**
13701     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13702     * a parent view.
13703     *
13704     * <p>This method is responsible for removing any pending high-level input events that were
13705     * posted to the event queue to run later. Custom view classes that post their own deferred
13706     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13707     * {@link android.os.Handler} should override this method, call
13708     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13709     * </p>
13710     */
13711    public void onCancelPendingInputEvents() {
13712        removePerformClickCallback();
13713        cancelLongPress();
13714        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13715    }
13716
13717    /**
13718     * Store this view hierarchy's frozen state into the given container.
13719     *
13720     * @param container The SparseArray in which to save the view's state.
13721     *
13722     * @see #restoreHierarchyState(android.util.SparseArray)
13723     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13724     * @see #onSaveInstanceState()
13725     */
13726    public void saveHierarchyState(SparseArray<Parcelable> container) {
13727        dispatchSaveInstanceState(container);
13728    }
13729
13730    /**
13731     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13732     * this view and its children. May be overridden to modify how freezing happens to a
13733     * view's children; for example, some views may want to not store state for their children.
13734     *
13735     * @param container The SparseArray in which to save the view's state.
13736     *
13737     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13738     * @see #saveHierarchyState(android.util.SparseArray)
13739     * @see #onSaveInstanceState()
13740     */
13741    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13742        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13743            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13744            Parcelable state = onSaveInstanceState();
13745            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13746                throw new IllegalStateException(
13747                        "Derived class did not call super.onSaveInstanceState()");
13748            }
13749            if (state != null) {
13750                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13751                // + ": " + state);
13752                container.put(mID, state);
13753            }
13754        }
13755    }
13756
13757    /**
13758     * Hook allowing a view to generate a representation of its internal state
13759     * that can later be used to create a new instance with that same state.
13760     * This state should only contain information that is not persistent or can
13761     * not be reconstructed later. For example, you will never store your
13762     * current position on screen because that will be computed again when a
13763     * new instance of the view is placed in its view hierarchy.
13764     * <p>
13765     * Some examples of things you may store here: the current cursor position
13766     * in a text view (but usually not the text itself since that is stored in a
13767     * content provider or other persistent storage), the currently selected
13768     * item in a list view.
13769     *
13770     * @return Returns a Parcelable object containing the view's current dynamic
13771     *         state, or null if there is nothing interesting to save. The
13772     *         default implementation returns null.
13773     * @see #onRestoreInstanceState(android.os.Parcelable)
13774     * @see #saveHierarchyState(android.util.SparseArray)
13775     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13776     * @see #setSaveEnabled(boolean)
13777     */
13778    protected Parcelable onSaveInstanceState() {
13779        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13780        return BaseSavedState.EMPTY_STATE;
13781    }
13782
13783    /**
13784     * Restore this view hierarchy's frozen state from the given container.
13785     *
13786     * @param container The SparseArray which holds previously frozen states.
13787     *
13788     * @see #saveHierarchyState(android.util.SparseArray)
13789     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13790     * @see #onRestoreInstanceState(android.os.Parcelable)
13791     */
13792    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13793        dispatchRestoreInstanceState(container);
13794    }
13795
13796    /**
13797     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13798     * state for this view and its children. May be overridden to modify how restoring
13799     * happens to a view's children; for example, some views may want to not store state
13800     * for their children.
13801     *
13802     * @param container The SparseArray which holds previously saved state.
13803     *
13804     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13805     * @see #restoreHierarchyState(android.util.SparseArray)
13806     * @see #onRestoreInstanceState(android.os.Parcelable)
13807     */
13808    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13809        if (mID != NO_ID) {
13810            Parcelable state = container.get(mID);
13811            if (state != null) {
13812                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13813                // + ": " + state);
13814                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13815                onRestoreInstanceState(state);
13816                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13817                    throw new IllegalStateException(
13818                            "Derived class did not call super.onRestoreInstanceState()");
13819                }
13820            }
13821        }
13822    }
13823
13824    /**
13825     * Hook allowing a view to re-apply a representation of its internal state that had previously
13826     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13827     * null state.
13828     *
13829     * @param state The frozen state that had previously been returned by
13830     *        {@link #onSaveInstanceState}.
13831     *
13832     * @see #onSaveInstanceState()
13833     * @see #restoreHierarchyState(android.util.SparseArray)
13834     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13835     */
13836    protected void onRestoreInstanceState(Parcelable state) {
13837        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13838        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13839            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13840                    + "received " + state.getClass().toString() + " instead. This usually happens "
13841                    + "when two views of different type have the same id in the same hierarchy. "
13842                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13843                    + "other views do not use the same id.");
13844        }
13845    }
13846
13847    /**
13848     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13849     *
13850     * @return the drawing start time in milliseconds
13851     */
13852    public long getDrawingTime() {
13853        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13854    }
13855
13856    /**
13857     * <p>Enables or disables the duplication of the parent's state into this view. When
13858     * duplication is enabled, this view gets its drawable state from its parent rather
13859     * than from its own internal properties.</p>
13860     *
13861     * <p>Note: in the current implementation, setting this property to true after the
13862     * view was added to a ViewGroup might have no effect at all. This property should
13863     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13864     *
13865     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13866     * property is enabled, an exception will be thrown.</p>
13867     *
13868     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13869     * parent, these states should not be affected by this method.</p>
13870     *
13871     * @param enabled True to enable duplication of the parent's drawable state, false
13872     *                to disable it.
13873     *
13874     * @see #getDrawableState()
13875     * @see #isDuplicateParentStateEnabled()
13876     */
13877    public void setDuplicateParentStateEnabled(boolean enabled) {
13878        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13879    }
13880
13881    /**
13882     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13883     *
13884     * @return True if this view's drawable state is duplicated from the parent,
13885     *         false otherwise
13886     *
13887     * @see #getDrawableState()
13888     * @see #setDuplicateParentStateEnabled(boolean)
13889     */
13890    public boolean isDuplicateParentStateEnabled() {
13891        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13892    }
13893
13894    /**
13895     * <p>Specifies the type of layer backing this view. The layer can be
13896     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13897     * {@link #LAYER_TYPE_HARDWARE}.</p>
13898     *
13899     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13900     * instance that controls how the layer is composed on screen. The following
13901     * properties of the paint are taken into account when composing the layer:</p>
13902     * <ul>
13903     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13904     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13905     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13906     * </ul>
13907     *
13908     * <p>If this view has an alpha value set to < 1.0 by calling
13909     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13910     * by this view's alpha value.</p>
13911     *
13912     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13913     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13914     * for more information on when and how to use layers.</p>
13915     *
13916     * @param layerType The type of layer to use with this view, must be one of
13917     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13918     *        {@link #LAYER_TYPE_HARDWARE}
13919     * @param paint The paint used to compose the layer. This argument is optional
13920     *        and can be null. It is ignored when the layer type is
13921     *        {@link #LAYER_TYPE_NONE}
13922     *
13923     * @see #getLayerType()
13924     * @see #LAYER_TYPE_NONE
13925     * @see #LAYER_TYPE_SOFTWARE
13926     * @see #LAYER_TYPE_HARDWARE
13927     * @see #setAlpha(float)
13928     *
13929     * @attr ref android.R.styleable#View_layerType
13930     */
13931    public void setLayerType(int layerType, Paint paint) {
13932        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13933            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13934                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13935        }
13936
13937        boolean typeChanged = mRenderNode.setLayerType(layerType);
13938
13939        if (!typeChanged) {
13940            setLayerPaint(paint);
13941            return;
13942        }
13943
13944        // Destroy any previous software drawing cache if needed
13945        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13946            destroyDrawingCache();
13947        }
13948
13949        mLayerType = layerType;
13950        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13951        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13952        mRenderNode.setLayerPaint(mLayerPaint);
13953
13954        // draw() behaves differently if we are on a layer, so we need to
13955        // invalidate() here
13956        invalidateParentCaches();
13957        invalidate(true);
13958    }
13959
13960    /**
13961     * Updates the {@link Paint} object used with the current layer (used only if the current
13962     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13963     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13964     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13965     * ensure that the view gets redrawn immediately.
13966     *
13967     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13968     * instance that controls how the layer is composed on screen. The following
13969     * properties of the paint are taken into account when composing the layer:</p>
13970     * <ul>
13971     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13972     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13973     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13974     * </ul>
13975     *
13976     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13977     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13978     *
13979     * @param paint The paint used to compose the layer. This argument is optional
13980     *        and can be null. It is ignored when the layer type is
13981     *        {@link #LAYER_TYPE_NONE}
13982     *
13983     * @see #setLayerType(int, android.graphics.Paint)
13984     */
13985    public void setLayerPaint(Paint paint) {
13986        int layerType = getLayerType();
13987        if (layerType != LAYER_TYPE_NONE) {
13988            mLayerPaint = paint == null ? new Paint() : paint;
13989            if (layerType == LAYER_TYPE_HARDWARE) {
13990                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13991                    invalidateViewProperty(false, false);
13992                }
13993            } else {
13994                invalidate();
13995            }
13996        }
13997    }
13998
13999    /**
14000     * Indicates whether this view has a static layer. A view with layer type
14001     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
14002     * dynamic.
14003     */
14004    boolean hasStaticLayer() {
14005        return true;
14006    }
14007
14008    /**
14009     * Indicates what type of layer is currently associated with this view. By default
14010     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14011     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14012     * for more information on the different types of layers.
14013     *
14014     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14015     *         {@link #LAYER_TYPE_HARDWARE}
14016     *
14017     * @see #setLayerType(int, android.graphics.Paint)
14018     * @see #buildLayer()
14019     * @see #LAYER_TYPE_NONE
14020     * @see #LAYER_TYPE_SOFTWARE
14021     * @see #LAYER_TYPE_HARDWARE
14022     */
14023    public int getLayerType() {
14024        return mLayerType;
14025    }
14026
14027    /**
14028     * Forces this view's layer to be created and this view to be rendered
14029     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14030     * invoking this method will have no effect.
14031     *
14032     * This method can for instance be used to render a view into its layer before
14033     * starting an animation. If this view is complex, rendering into the layer
14034     * before starting the animation will avoid skipping frames.
14035     *
14036     * @throws IllegalStateException If this view is not attached to a window
14037     *
14038     * @see #setLayerType(int, android.graphics.Paint)
14039     */
14040    public void buildLayer() {
14041        if (mLayerType == LAYER_TYPE_NONE) return;
14042
14043        final AttachInfo attachInfo = mAttachInfo;
14044        if (attachInfo == null) {
14045            throw new IllegalStateException("This view must be attached to a window first");
14046        }
14047
14048        if (getWidth() == 0 || getHeight() == 0) {
14049            return;
14050        }
14051
14052        switch (mLayerType) {
14053            case LAYER_TYPE_HARDWARE:
14054                updateDisplayListIfDirty();
14055                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14056                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14057                }
14058                break;
14059            case LAYER_TYPE_SOFTWARE:
14060                buildDrawingCache(true);
14061                break;
14062        }
14063    }
14064
14065    /**
14066     * If this View draws with a HardwareLayer, returns it.
14067     * Otherwise returns null
14068     *
14069     * TODO: Only TextureView uses this, can we eliminate it?
14070     */
14071    HardwareLayer getHardwareLayer() {
14072        return null;
14073    }
14074
14075    /**
14076     * Destroys all hardware rendering resources. This method is invoked
14077     * when the system needs to reclaim resources. Upon execution of this
14078     * method, you should free any OpenGL resources created by the view.
14079     *
14080     * Note: you <strong>must</strong> call
14081     * <code>super.destroyHardwareResources()</code> when overriding
14082     * this method.
14083     *
14084     * @hide
14085     */
14086    protected void destroyHardwareResources() {
14087        // Although the Layer will be destroyed by RenderNode, we want to release
14088        // the staging display list, which is also a signal to RenderNode that it's
14089        // safe to free its copy of the display list as it knows that we will
14090        // push an updated DisplayList if we try to draw again
14091        resetDisplayList();
14092    }
14093
14094    /**
14095     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14096     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14097     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14098     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14099     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14100     * null.</p>
14101     *
14102     * <p>Enabling the drawing cache is similar to
14103     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14104     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14105     * drawing cache has no effect on rendering because the system uses a different mechanism
14106     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14107     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14108     * for information on how to enable software and hardware layers.</p>
14109     *
14110     * <p>This API can be used to manually generate
14111     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14112     * {@link #getDrawingCache()}.</p>
14113     *
14114     * @param enabled true to enable the drawing cache, false otherwise
14115     *
14116     * @see #isDrawingCacheEnabled()
14117     * @see #getDrawingCache()
14118     * @see #buildDrawingCache()
14119     * @see #setLayerType(int, android.graphics.Paint)
14120     */
14121    public void setDrawingCacheEnabled(boolean enabled) {
14122        mCachingFailed = false;
14123        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14124    }
14125
14126    /**
14127     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14128     *
14129     * @return true if the drawing cache is enabled
14130     *
14131     * @see #setDrawingCacheEnabled(boolean)
14132     * @see #getDrawingCache()
14133     */
14134    @ViewDebug.ExportedProperty(category = "drawing")
14135    public boolean isDrawingCacheEnabled() {
14136        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14137    }
14138
14139    /**
14140     * Debugging utility which recursively outputs the dirty state of a view and its
14141     * descendants.
14142     *
14143     * @hide
14144     */
14145    @SuppressWarnings({"UnusedDeclaration"})
14146    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14147        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14148                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14149                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14150                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14151        if (clear) {
14152            mPrivateFlags &= clearMask;
14153        }
14154        if (this instanceof ViewGroup) {
14155            ViewGroup parent = (ViewGroup) this;
14156            final int count = parent.getChildCount();
14157            for (int i = 0; i < count; i++) {
14158                final View child = parent.getChildAt(i);
14159                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14160            }
14161        }
14162    }
14163
14164    /**
14165     * This method is used by ViewGroup to cause its children to restore or recreate their
14166     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14167     * to recreate its own display list, which would happen if it went through the normal
14168     * draw/dispatchDraw mechanisms.
14169     *
14170     * @hide
14171     */
14172    protected void dispatchGetDisplayList() {}
14173
14174    /**
14175     * A view that is not attached or hardware accelerated cannot create a display list.
14176     * This method checks these conditions and returns the appropriate result.
14177     *
14178     * @return true if view has the ability to create a display list, false otherwise.
14179     *
14180     * @hide
14181     */
14182    public boolean canHaveDisplayList() {
14183        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14184    }
14185
14186    private void updateDisplayListIfDirty() {
14187        final RenderNode renderNode = mRenderNode;
14188        if (!canHaveDisplayList()) {
14189            // can't populate RenderNode, don't try
14190            return;
14191        }
14192
14193        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14194                || !renderNode.isValid()
14195                || (mRecreateDisplayList)) {
14196            // Don't need to recreate the display list, just need to tell our
14197            // children to restore/recreate theirs
14198            if (renderNode.isValid()
14199                    && !mRecreateDisplayList) {
14200                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14201                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14202                dispatchGetDisplayList();
14203
14204                return; // no work needed
14205            }
14206
14207            // If we got here, we're recreating it. Mark it as such to ensure that
14208            // we copy in child display lists into ours in drawChild()
14209            mRecreateDisplayList = true;
14210
14211            int width = mRight - mLeft;
14212            int height = mBottom - mTop;
14213            int layerType = getLayerType();
14214
14215            final HardwareCanvas canvas = renderNode.start(width, height);
14216            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14217
14218            try {
14219                final HardwareLayer layer = getHardwareLayer();
14220                if (layer != null && layer.isValid()) {
14221                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14222                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14223                    buildDrawingCache(true);
14224                    Bitmap cache = getDrawingCache(true);
14225                    if (cache != null) {
14226                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14227                    }
14228                } else {
14229                    computeScroll();
14230
14231                    canvas.translate(-mScrollX, -mScrollY);
14232                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14233                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14234
14235                    // Fast path for layouts with no backgrounds
14236                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14237                        dispatchDraw(canvas);
14238                        if (mOverlay != null && !mOverlay.isEmpty()) {
14239                            mOverlay.getOverlayView().draw(canvas);
14240                        }
14241                    } else {
14242                        draw(canvas);
14243                    }
14244                }
14245            } finally {
14246                renderNode.end(canvas);
14247                setDisplayListProperties(renderNode);
14248            }
14249        } else {
14250            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14251            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14252        }
14253    }
14254
14255    /**
14256     * Returns a RenderNode with View draw content recorded, which can be
14257     * used to draw this view again without executing its draw method.
14258     *
14259     * @return A RenderNode ready to replay, or null if caching is not enabled.
14260     *
14261     * @hide
14262     */
14263    public RenderNode getDisplayList() {
14264        updateDisplayListIfDirty();
14265        return mRenderNode;
14266    }
14267
14268    private void resetDisplayList() {
14269        if (mRenderNode.isValid()) {
14270            mRenderNode.destroyDisplayListData();
14271        }
14272
14273        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14274            mBackgroundRenderNode.destroyDisplayListData();
14275        }
14276    }
14277
14278    /**
14279     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14280     *
14281     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14282     *
14283     * @see #getDrawingCache(boolean)
14284     */
14285    public Bitmap getDrawingCache() {
14286        return getDrawingCache(false);
14287    }
14288
14289    /**
14290     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14291     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14292     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14293     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14294     * request the drawing cache by calling this method and draw it on screen if the
14295     * returned bitmap is not null.</p>
14296     *
14297     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14298     * this method will create a bitmap of the same size as this view. Because this bitmap
14299     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14300     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14301     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14302     * size than the view. This implies that your application must be able to handle this
14303     * size.</p>
14304     *
14305     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14306     *        the current density of the screen when the application is in compatibility
14307     *        mode.
14308     *
14309     * @return A bitmap representing this view or null if cache is disabled.
14310     *
14311     * @see #setDrawingCacheEnabled(boolean)
14312     * @see #isDrawingCacheEnabled()
14313     * @see #buildDrawingCache(boolean)
14314     * @see #destroyDrawingCache()
14315     */
14316    public Bitmap getDrawingCache(boolean autoScale) {
14317        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14318            return null;
14319        }
14320        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14321            buildDrawingCache(autoScale);
14322        }
14323        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14324    }
14325
14326    /**
14327     * <p>Frees the resources used by the drawing cache. If you call
14328     * {@link #buildDrawingCache()} manually without calling
14329     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14330     * should cleanup the cache with this method afterwards.</p>
14331     *
14332     * @see #setDrawingCacheEnabled(boolean)
14333     * @see #buildDrawingCache()
14334     * @see #getDrawingCache()
14335     */
14336    public void destroyDrawingCache() {
14337        if (mDrawingCache != null) {
14338            mDrawingCache.recycle();
14339            mDrawingCache = null;
14340        }
14341        if (mUnscaledDrawingCache != null) {
14342            mUnscaledDrawingCache.recycle();
14343            mUnscaledDrawingCache = null;
14344        }
14345    }
14346
14347    /**
14348     * Setting a solid background color for the drawing cache's bitmaps will improve
14349     * performance and memory usage. Note, though that this should only be used if this
14350     * view will always be drawn on top of a solid color.
14351     *
14352     * @param color The background color to use for the drawing cache's bitmap
14353     *
14354     * @see #setDrawingCacheEnabled(boolean)
14355     * @see #buildDrawingCache()
14356     * @see #getDrawingCache()
14357     */
14358    public void setDrawingCacheBackgroundColor(int color) {
14359        if (color != mDrawingCacheBackgroundColor) {
14360            mDrawingCacheBackgroundColor = color;
14361            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14362        }
14363    }
14364
14365    /**
14366     * @see #setDrawingCacheBackgroundColor(int)
14367     *
14368     * @return The background color to used for the drawing cache's bitmap
14369     */
14370    public int getDrawingCacheBackgroundColor() {
14371        return mDrawingCacheBackgroundColor;
14372    }
14373
14374    /**
14375     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14376     *
14377     * @see #buildDrawingCache(boolean)
14378     */
14379    public void buildDrawingCache() {
14380        buildDrawingCache(false);
14381    }
14382
14383    /**
14384     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14385     *
14386     * <p>If you call {@link #buildDrawingCache()} manually without calling
14387     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14388     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14389     *
14390     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14391     * this method will create a bitmap of the same size as this view. Because this bitmap
14392     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14393     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14394     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14395     * size than the view. This implies that your application must be able to handle this
14396     * size.</p>
14397     *
14398     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14399     * you do not need the drawing cache bitmap, calling this method will increase memory
14400     * usage and cause the view to be rendered in software once, thus negatively impacting
14401     * performance.</p>
14402     *
14403     * @see #getDrawingCache()
14404     * @see #destroyDrawingCache()
14405     */
14406    public void buildDrawingCache(boolean autoScale) {
14407        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14408                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14409            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14410                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14411                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14412            }
14413            try {
14414                buildDrawingCacheImpl(autoScale);
14415            } finally {
14416                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14417            }
14418        }
14419    }
14420
14421    /**
14422     * private, internal implementation of buildDrawingCache, used to enable tracing
14423     */
14424    private void buildDrawingCacheImpl(boolean autoScale) {
14425        mCachingFailed = false;
14426
14427        int width = mRight - mLeft;
14428        int height = mBottom - mTop;
14429
14430        final AttachInfo attachInfo = mAttachInfo;
14431        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14432
14433        if (autoScale && scalingRequired) {
14434            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14435            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14436        }
14437
14438        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14439        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14440        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14441
14442        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14443        final long drawingCacheSize =
14444                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14445        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14446            if (width > 0 && height > 0) {
14447                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14448                        + projectedBitmapSize + " bytes, only "
14449                        + drawingCacheSize + " available");
14450            }
14451            destroyDrawingCache();
14452            mCachingFailed = true;
14453            return;
14454        }
14455
14456        boolean clear = true;
14457        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14458
14459        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14460            Bitmap.Config quality;
14461            if (!opaque) {
14462                // Never pick ARGB_4444 because it looks awful
14463                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14464                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14465                    case DRAWING_CACHE_QUALITY_AUTO:
14466                    case DRAWING_CACHE_QUALITY_LOW:
14467                    case DRAWING_CACHE_QUALITY_HIGH:
14468                    default:
14469                        quality = Bitmap.Config.ARGB_8888;
14470                        break;
14471                }
14472            } else {
14473                // Optimization for translucent windows
14474                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14475                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14476            }
14477
14478            // Try to cleanup memory
14479            if (bitmap != null) bitmap.recycle();
14480
14481            try {
14482                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14483                        width, height, quality);
14484                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14485                if (autoScale) {
14486                    mDrawingCache = bitmap;
14487                } else {
14488                    mUnscaledDrawingCache = bitmap;
14489                }
14490                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14491            } catch (OutOfMemoryError e) {
14492                // If there is not enough memory to create the bitmap cache, just
14493                // ignore the issue as bitmap caches are not required to draw the
14494                // view hierarchy
14495                if (autoScale) {
14496                    mDrawingCache = null;
14497                } else {
14498                    mUnscaledDrawingCache = null;
14499                }
14500                mCachingFailed = true;
14501                return;
14502            }
14503
14504            clear = drawingCacheBackgroundColor != 0;
14505        }
14506
14507        Canvas canvas;
14508        if (attachInfo != null) {
14509            canvas = attachInfo.mCanvas;
14510            if (canvas == null) {
14511                canvas = new Canvas();
14512            }
14513            canvas.setBitmap(bitmap);
14514            // Temporarily clobber the cached Canvas in case one of our children
14515            // is also using a drawing cache. Without this, the children would
14516            // steal the canvas by attaching their own bitmap to it and bad, bad
14517            // thing would happen (invisible views, corrupted drawings, etc.)
14518            attachInfo.mCanvas = null;
14519        } else {
14520            // This case should hopefully never or seldom happen
14521            canvas = new Canvas(bitmap);
14522        }
14523
14524        if (clear) {
14525            bitmap.eraseColor(drawingCacheBackgroundColor);
14526        }
14527
14528        computeScroll();
14529        final int restoreCount = canvas.save();
14530
14531        if (autoScale && scalingRequired) {
14532            final float scale = attachInfo.mApplicationScale;
14533            canvas.scale(scale, scale);
14534        }
14535
14536        canvas.translate(-mScrollX, -mScrollY);
14537
14538        mPrivateFlags |= PFLAG_DRAWN;
14539        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14540                mLayerType != LAYER_TYPE_NONE) {
14541            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14542        }
14543
14544        // Fast path for layouts with no backgrounds
14545        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14546            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14547            dispatchDraw(canvas);
14548            if (mOverlay != null && !mOverlay.isEmpty()) {
14549                mOverlay.getOverlayView().draw(canvas);
14550            }
14551        } else {
14552            draw(canvas);
14553        }
14554
14555        canvas.restoreToCount(restoreCount);
14556        canvas.setBitmap(null);
14557
14558        if (attachInfo != null) {
14559            // Restore the cached Canvas for our siblings
14560            attachInfo.mCanvas = canvas;
14561        }
14562    }
14563
14564    /**
14565     * Create a snapshot of the view into a bitmap.  We should probably make
14566     * some form of this public, but should think about the API.
14567     */
14568    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14569        int width = mRight - mLeft;
14570        int height = mBottom - mTop;
14571
14572        final AttachInfo attachInfo = mAttachInfo;
14573        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14574        width = (int) ((width * scale) + 0.5f);
14575        height = (int) ((height * scale) + 0.5f);
14576
14577        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14578                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14579        if (bitmap == null) {
14580            throw new OutOfMemoryError();
14581        }
14582
14583        Resources resources = getResources();
14584        if (resources != null) {
14585            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14586        }
14587
14588        Canvas canvas;
14589        if (attachInfo != null) {
14590            canvas = attachInfo.mCanvas;
14591            if (canvas == null) {
14592                canvas = new Canvas();
14593            }
14594            canvas.setBitmap(bitmap);
14595            // Temporarily clobber the cached Canvas in case one of our children
14596            // is also using a drawing cache. Without this, the children would
14597            // steal the canvas by attaching their own bitmap to it and bad, bad
14598            // things would happen (invisible views, corrupted drawings, etc.)
14599            attachInfo.mCanvas = null;
14600        } else {
14601            // This case should hopefully never or seldom happen
14602            canvas = new Canvas(bitmap);
14603        }
14604
14605        if ((backgroundColor & 0xff000000) != 0) {
14606            bitmap.eraseColor(backgroundColor);
14607        }
14608
14609        computeScroll();
14610        final int restoreCount = canvas.save();
14611        canvas.scale(scale, scale);
14612        canvas.translate(-mScrollX, -mScrollY);
14613
14614        // Temporarily remove the dirty mask
14615        int flags = mPrivateFlags;
14616        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14617
14618        // Fast path for layouts with no backgrounds
14619        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14620            dispatchDraw(canvas);
14621            if (mOverlay != null && !mOverlay.isEmpty()) {
14622                mOverlay.getOverlayView().draw(canvas);
14623            }
14624        } else {
14625            draw(canvas);
14626        }
14627
14628        mPrivateFlags = flags;
14629
14630        canvas.restoreToCount(restoreCount);
14631        canvas.setBitmap(null);
14632
14633        if (attachInfo != null) {
14634            // Restore the cached Canvas for our siblings
14635            attachInfo.mCanvas = canvas;
14636        }
14637
14638        return bitmap;
14639    }
14640
14641    /**
14642     * Indicates whether this View is currently in edit mode. A View is usually
14643     * in edit mode when displayed within a developer tool. For instance, if
14644     * this View is being drawn by a visual user interface builder, this method
14645     * should return true.
14646     *
14647     * Subclasses should check the return value of this method to provide
14648     * different behaviors if their normal behavior might interfere with the
14649     * host environment. For instance: the class spawns a thread in its
14650     * constructor, the drawing code relies on device-specific features, etc.
14651     *
14652     * This method is usually checked in the drawing code of custom widgets.
14653     *
14654     * @return True if this View is in edit mode, false otherwise.
14655     */
14656    public boolean isInEditMode() {
14657        return false;
14658    }
14659
14660    /**
14661     * If the View draws content inside its padding and enables fading edges,
14662     * it needs to support padding offsets. Padding offsets are added to the
14663     * fading edges to extend the length of the fade so that it covers pixels
14664     * drawn inside the padding.
14665     *
14666     * Subclasses of this class should override this method if they need
14667     * to draw content inside the padding.
14668     *
14669     * @return True if padding offset must be applied, false otherwise.
14670     *
14671     * @see #getLeftPaddingOffset()
14672     * @see #getRightPaddingOffset()
14673     * @see #getTopPaddingOffset()
14674     * @see #getBottomPaddingOffset()
14675     *
14676     * @since CURRENT
14677     */
14678    protected boolean isPaddingOffsetRequired() {
14679        return false;
14680    }
14681
14682    /**
14683     * Amount by which to extend the left fading region. Called only when
14684     * {@link #isPaddingOffsetRequired()} returns true.
14685     *
14686     * @return The left padding offset in pixels.
14687     *
14688     * @see #isPaddingOffsetRequired()
14689     *
14690     * @since CURRENT
14691     */
14692    protected int getLeftPaddingOffset() {
14693        return 0;
14694    }
14695
14696    /**
14697     * Amount by which to extend the right fading region. Called only when
14698     * {@link #isPaddingOffsetRequired()} returns true.
14699     *
14700     * @return The right padding offset in pixels.
14701     *
14702     * @see #isPaddingOffsetRequired()
14703     *
14704     * @since CURRENT
14705     */
14706    protected int getRightPaddingOffset() {
14707        return 0;
14708    }
14709
14710    /**
14711     * Amount by which to extend the top fading region. Called only when
14712     * {@link #isPaddingOffsetRequired()} returns true.
14713     *
14714     * @return The top padding offset in pixels.
14715     *
14716     * @see #isPaddingOffsetRequired()
14717     *
14718     * @since CURRENT
14719     */
14720    protected int getTopPaddingOffset() {
14721        return 0;
14722    }
14723
14724    /**
14725     * Amount by which to extend the bottom fading region. Called only when
14726     * {@link #isPaddingOffsetRequired()} returns true.
14727     *
14728     * @return The bottom padding offset in pixels.
14729     *
14730     * @see #isPaddingOffsetRequired()
14731     *
14732     * @since CURRENT
14733     */
14734    protected int getBottomPaddingOffset() {
14735        return 0;
14736    }
14737
14738    /**
14739     * @hide
14740     * @param offsetRequired
14741     */
14742    protected int getFadeTop(boolean offsetRequired) {
14743        int top = mPaddingTop;
14744        if (offsetRequired) top += getTopPaddingOffset();
14745        return top;
14746    }
14747
14748    /**
14749     * @hide
14750     * @param offsetRequired
14751     */
14752    protected int getFadeHeight(boolean offsetRequired) {
14753        int padding = mPaddingTop;
14754        if (offsetRequired) padding += getTopPaddingOffset();
14755        return mBottom - mTop - mPaddingBottom - padding;
14756    }
14757
14758    /**
14759     * <p>Indicates whether this view is attached to a hardware accelerated
14760     * window or not.</p>
14761     *
14762     * <p>Even if this method returns true, it does not mean that every call
14763     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14764     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14765     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14766     * window is hardware accelerated,
14767     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14768     * return false, and this method will return true.</p>
14769     *
14770     * @return True if the view is attached to a window and the window is
14771     *         hardware accelerated; false in any other case.
14772     */
14773    @ViewDebug.ExportedProperty(category = "drawing")
14774    public boolean isHardwareAccelerated() {
14775        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14776    }
14777
14778    /**
14779     * Sets a rectangular area on this view to which the view will be clipped
14780     * when it is drawn. Setting the value to null will remove the clip bounds
14781     * and the view will draw normally, using its full bounds.
14782     *
14783     * @param clipBounds The rectangular area, in the local coordinates of
14784     * this view, to which future drawing operations will be clipped.
14785     */
14786    public void setClipBounds(Rect clipBounds) {
14787        if (clipBounds == mClipBounds
14788                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
14789            return;
14790        }
14791        if (clipBounds != null) {
14792            if (mClipBounds == null) {
14793                mClipBounds = new Rect(clipBounds);
14794            } else {
14795                mClipBounds.set(clipBounds);
14796            }
14797        } else {
14798            mClipBounds = null;
14799        }
14800        mRenderNode.setClipBounds(mClipBounds);
14801        invalidateViewProperty(false, false);
14802    }
14803
14804    /**
14805     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14806     *
14807     * @return A copy of the current clip bounds if clip bounds are set,
14808     * otherwise null.
14809     */
14810    public Rect getClipBounds() {
14811        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14812    }
14813
14814    /**
14815     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14816     * case of an active Animation being run on the view.
14817     */
14818    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14819            Animation a, boolean scalingRequired) {
14820        Transformation invalidationTransform;
14821        final int flags = parent.mGroupFlags;
14822        final boolean initialized = a.isInitialized();
14823        if (!initialized) {
14824            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14825            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14826            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14827            onAnimationStart();
14828        }
14829
14830        final Transformation t = parent.getChildTransformation();
14831        boolean more = a.getTransformation(drawingTime, t, 1f);
14832        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14833            if (parent.mInvalidationTransformation == null) {
14834                parent.mInvalidationTransformation = new Transformation();
14835            }
14836            invalidationTransform = parent.mInvalidationTransformation;
14837            a.getTransformation(drawingTime, invalidationTransform, 1f);
14838        } else {
14839            invalidationTransform = t;
14840        }
14841
14842        if (more) {
14843            if (!a.willChangeBounds()) {
14844                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14845                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14846                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14847                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14848                    // The child need to draw an animation, potentially offscreen, so
14849                    // make sure we do not cancel invalidate requests
14850                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14851                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14852                }
14853            } else {
14854                if (parent.mInvalidateRegion == null) {
14855                    parent.mInvalidateRegion = new RectF();
14856                }
14857                final RectF region = parent.mInvalidateRegion;
14858                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14859                        invalidationTransform);
14860
14861                // The child need to draw an animation, potentially offscreen, so
14862                // make sure we do not cancel invalidate requests
14863                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14864
14865                final int left = mLeft + (int) region.left;
14866                final int top = mTop + (int) region.top;
14867                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14868                        top + (int) (region.height() + .5f));
14869            }
14870        }
14871        return more;
14872    }
14873
14874    /**
14875     * This method is called by getDisplayList() when a display list is recorded for a View.
14876     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14877     */
14878    void setDisplayListProperties(RenderNode renderNode) {
14879        if (renderNode != null) {
14880            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14881            if (mParent instanceof ViewGroup) {
14882                renderNode.setClipToBounds(
14883                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14884            }
14885            float alpha = 1;
14886            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14887                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14888                ViewGroup parentVG = (ViewGroup) mParent;
14889                final Transformation t = parentVG.getChildTransformation();
14890                if (parentVG.getChildStaticTransformation(this, t)) {
14891                    final int transformType = t.getTransformationType();
14892                    if (transformType != Transformation.TYPE_IDENTITY) {
14893                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14894                            alpha = t.getAlpha();
14895                        }
14896                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14897                            renderNode.setStaticMatrix(t.getMatrix());
14898                        }
14899                    }
14900                }
14901            }
14902            if (mTransformationInfo != null) {
14903                alpha *= getFinalAlpha();
14904                if (alpha < 1) {
14905                    final int multipliedAlpha = (int) (255 * alpha);
14906                    if (onSetAlpha(multipliedAlpha)) {
14907                        alpha = 1;
14908                    }
14909                }
14910                renderNode.setAlpha(alpha);
14911            } else if (alpha < 1) {
14912                renderNode.setAlpha(alpha);
14913            }
14914        }
14915    }
14916
14917    /**
14918     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14919     * This draw() method is an implementation detail and is not intended to be overridden or
14920     * to be called from anywhere else other than ViewGroup.drawChild().
14921     */
14922    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14923        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14924        boolean more = false;
14925        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14926        final int flags = parent.mGroupFlags;
14927
14928        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14929            parent.getChildTransformation().clear();
14930            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14931        }
14932
14933        Transformation transformToApply = null;
14934        boolean concatMatrix = false;
14935
14936        boolean scalingRequired = false;
14937        boolean caching;
14938        int layerType = getLayerType();
14939
14940        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14941        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14942                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14943            caching = true;
14944            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14945            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14946        } else {
14947            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14948        }
14949
14950        final Animation a = getAnimation();
14951        if (a != null) {
14952            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14953            concatMatrix = a.willChangeTransformationMatrix();
14954            if (concatMatrix) {
14955                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14956            }
14957            transformToApply = parent.getChildTransformation();
14958        } else {
14959            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14960                // No longer animating: clear out old animation matrix
14961                mRenderNode.setAnimationMatrix(null);
14962                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14963            }
14964            if (!usingRenderNodeProperties &&
14965                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14966                final Transformation t = parent.getChildTransformation();
14967                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14968                if (hasTransform) {
14969                    final int transformType = t.getTransformationType();
14970                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14971                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14972                }
14973            }
14974        }
14975
14976        concatMatrix |= !childHasIdentityMatrix;
14977
14978        // Sets the flag as early as possible to allow draw() implementations
14979        // to call invalidate() successfully when doing animations
14980        mPrivateFlags |= PFLAG_DRAWN;
14981
14982        if (!concatMatrix &&
14983                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14984                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14985                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14986                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14987            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14988            return more;
14989        }
14990        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14991
14992        if (hardwareAccelerated) {
14993            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14994            // retain the flag's value temporarily in the mRecreateDisplayList flag
14995            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14996            mPrivateFlags &= ~PFLAG_INVALIDATED;
14997        }
14998
14999        RenderNode renderNode = null;
15000        Bitmap cache = null;
15001        boolean hasDisplayList = false;
15002        if (caching) {
15003            if (!hardwareAccelerated) {
15004                if (layerType != LAYER_TYPE_NONE) {
15005                    layerType = LAYER_TYPE_SOFTWARE;
15006                    buildDrawingCache(true);
15007                }
15008                cache = getDrawingCache(true);
15009            } else {
15010                switch (layerType) {
15011                    case LAYER_TYPE_SOFTWARE:
15012                        if (usingRenderNodeProperties) {
15013                            hasDisplayList = canHaveDisplayList();
15014                        } else {
15015                            buildDrawingCache(true);
15016                            cache = getDrawingCache(true);
15017                        }
15018                        break;
15019                    case LAYER_TYPE_HARDWARE:
15020                        if (usingRenderNodeProperties) {
15021                            hasDisplayList = canHaveDisplayList();
15022                        }
15023                        break;
15024                    case LAYER_TYPE_NONE:
15025                        // Delay getting the display list until animation-driven alpha values are
15026                        // set up and possibly passed on to the view
15027                        hasDisplayList = canHaveDisplayList();
15028                        break;
15029                }
15030            }
15031        }
15032        usingRenderNodeProperties &= hasDisplayList;
15033        if (usingRenderNodeProperties) {
15034            renderNode = getDisplayList();
15035            if (!renderNode.isValid()) {
15036                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15037                // to getDisplayList(), the display list will be marked invalid and we should not
15038                // try to use it again.
15039                renderNode = null;
15040                hasDisplayList = false;
15041                usingRenderNodeProperties = false;
15042            }
15043        }
15044
15045        int sx = 0;
15046        int sy = 0;
15047        if (!hasDisplayList) {
15048            computeScroll();
15049            sx = mScrollX;
15050            sy = mScrollY;
15051        }
15052
15053        final boolean hasNoCache = cache == null || hasDisplayList;
15054        final boolean offsetForScroll = cache == null && !hasDisplayList &&
15055                layerType != LAYER_TYPE_HARDWARE;
15056
15057        int restoreTo = -1;
15058        if (!usingRenderNodeProperties || transformToApply != null) {
15059            restoreTo = canvas.save();
15060        }
15061        if (offsetForScroll) {
15062            canvas.translate(mLeft - sx, mTop - sy);
15063        } else {
15064            if (!usingRenderNodeProperties) {
15065                canvas.translate(mLeft, mTop);
15066            }
15067            if (scalingRequired) {
15068                if (usingRenderNodeProperties) {
15069                    // TODO: Might not need this if we put everything inside the DL
15070                    restoreTo = canvas.save();
15071                }
15072                // mAttachInfo cannot be null, otherwise scalingRequired == false
15073                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15074                canvas.scale(scale, scale);
15075            }
15076        }
15077
15078        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
15079        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
15080                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15081            if (transformToApply != null || !childHasIdentityMatrix) {
15082                int transX = 0;
15083                int transY = 0;
15084
15085                if (offsetForScroll) {
15086                    transX = -sx;
15087                    transY = -sy;
15088                }
15089
15090                if (transformToApply != null) {
15091                    if (concatMatrix) {
15092                        if (usingRenderNodeProperties) {
15093                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15094                        } else {
15095                            // Undo the scroll translation, apply the transformation matrix,
15096                            // then redo the scroll translate to get the correct result.
15097                            canvas.translate(-transX, -transY);
15098                            canvas.concat(transformToApply.getMatrix());
15099                            canvas.translate(transX, transY);
15100                        }
15101                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15102                    }
15103
15104                    float transformAlpha = transformToApply.getAlpha();
15105                    if (transformAlpha < 1) {
15106                        alpha *= transformAlpha;
15107                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15108                    }
15109                }
15110
15111                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
15112                    canvas.translate(-transX, -transY);
15113                    canvas.concat(getMatrix());
15114                    canvas.translate(transX, transY);
15115                }
15116            }
15117
15118            // Deal with alpha if it is or used to be <1
15119            if (alpha < 1 ||
15120                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15121                if (alpha < 1) {
15122                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15123                } else {
15124                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15125                }
15126                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15127                if (hasNoCache) {
15128                    final int multipliedAlpha = (int) (255 * alpha);
15129                    if (!onSetAlpha(multipliedAlpha)) {
15130                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15131                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
15132                                layerType != LAYER_TYPE_NONE) {
15133                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15134                        }
15135                        if (usingRenderNodeProperties) {
15136                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15137                        } else  if (layerType == LAYER_TYPE_NONE) {
15138                            final int scrollX = hasDisplayList ? 0 : sx;
15139                            final int scrollY = hasDisplayList ? 0 : sy;
15140                            canvas.saveLayerAlpha(scrollX, scrollY,
15141                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
15142                                    multipliedAlpha, layerFlags);
15143                        }
15144                    } else {
15145                        // Alpha is handled by the child directly, clobber the layer's alpha
15146                        mPrivateFlags |= PFLAG_ALPHA_SET;
15147                    }
15148                }
15149            }
15150        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15151            onSetAlpha(255);
15152            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15153        }
15154
15155        if (!usingRenderNodeProperties) {
15156            // apply clips directly, since RenderNode won't do it for this draw
15157            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
15158                    && cache == null) {
15159                if (offsetForScroll) {
15160                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
15161                } else {
15162                    if (!scalingRequired || cache == null) {
15163                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
15164                    } else {
15165                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15166                    }
15167                }
15168            }
15169
15170            if (mClipBounds != null) {
15171                // clip bounds ignore scroll
15172                canvas.clipRect(mClipBounds);
15173            }
15174        }
15175
15176
15177
15178        if (!usingRenderNodeProperties && hasDisplayList) {
15179            renderNode = getDisplayList();
15180            if (!renderNode.isValid()) {
15181                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15182                // to getDisplayList(), the display list will be marked invalid and we should not
15183                // try to use it again.
15184                renderNode = null;
15185                hasDisplayList = false;
15186            }
15187        }
15188
15189        if (hasNoCache) {
15190            boolean layerRendered = false;
15191            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
15192                final HardwareLayer layer = getHardwareLayer();
15193                if (layer != null && layer.isValid()) {
15194                    int restoreAlpha = mLayerPaint.getAlpha();
15195                    mLayerPaint.setAlpha((int) (alpha * 255));
15196                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15197                    mLayerPaint.setAlpha(restoreAlpha);
15198                    layerRendered = true;
15199                } else {
15200                    final int scrollX = hasDisplayList ? 0 : sx;
15201                    final int scrollY = hasDisplayList ? 0 : sy;
15202                    canvas.saveLayer(scrollX, scrollY,
15203                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
15204                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
15205                }
15206            }
15207
15208            if (!layerRendered) {
15209                if (!hasDisplayList) {
15210                    // Fast path for layouts with no backgrounds
15211                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15212                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15213                        dispatchDraw(canvas);
15214                    } else {
15215                        draw(canvas);
15216                    }
15217                } else {
15218                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15219                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
15220                }
15221            }
15222        } else if (cache != null) {
15223            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15224            Paint cachePaint;
15225            int restoreAlpha = 0;
15226
15227            if (layerType == LAYER_TYPE_NONE) {
15228                cachePaint = parent.mCachePaint;
15229                if (cachePaint == null) {
15230                    cachePaint = new Paint();
15231                    cachePaint.setDither(false);
15232                    parent.mCachePaint = cachePaint;
15233                }
15234            } else {
15235                cachePaint = mLayerPaint;
15236                restoreAlpha = mLayerPaint.getAlpha();
15237            }
15238            cachePaint.setAlpha((int) (alpha * 255));
15239            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15240            cachePaint.setAlpha(restoreAlpha);
15241        }
15242
15243        if (restoreTo >= 0) {
15244            canvas.restoreToCount(restoreTo);
15245        }
15246
15247        if (a != null && !more) {
15248            if (!hardwareAccelerated && !a.getFillAfter()) {
15249                onSetAlpha(255);
15250            }
15251            parent.finishAnimatingView(this, a);
15252        }
15253
15254        if (more && hardwareAccelerated) {
15255            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15256                // alpha animations should cause the child to recreate its display list
15257                invalidate(true);
15258            }
15259        }
15260
15261        mRecreateDisplayList = false;
15262
15263        return more;
15264    }
15265
15266    /**
15267     * Manually render this view (and all of its children) to the given Canvas.
15268     * The view must have already done a full layout before this function is
15269     * called.  When implementing a view, implement
15270     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15271     * If you do need to override this method, call the superclass version.
15272     *
15273     * @param canvas The Canvas to which the View is rendered.
15274     */
15275    public void draw(Canvas canvas) {
15276        final int privateFlags = mPrivateFlags;
15277        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15278                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15279        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15280
15281        /*
15282         * Draw traversal performs several drawing steps which must be executed
15283         * in the appropriate order:
15284         *
15285         *      1. Draw the background
15286         *      2. If necessary, save the canvas' layers to prepare for fading
15287         *      3. Draw view's content
15288         *      4. Draw children
15289         *      5. If necessary, draw the fading edges and restore layers
15290         *      6. Draw decorations (scrollbars for instance)
15291         */
15292
15293        // Step 1, draw the background, if needed
15294        int saveCount;
15295
15296        if (!dirtyOpaque) {
15297            drawBackground(canvas);
15298        }
15299
15300        // skip step 2 & 5 if possible (common case)
15301        final int viewFlags = mViewFlags;
15302        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15303        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15304        if (!verticalEdges && !horizontalEdges) {
15305            // Step 3, draw the content
15306            if (!dirtyOpaque) onDraw(canvas);
15307
15308            // Step 4, draw the children
15309            dispatchDraw(canvas);
15310
15311            // Step 6, draw decorations (scrollbars)
15312            onDrawScrollBars(canvas);
15313
15314            if (mOverlay != null && !mOverlay.isEmpty()) {
15315                mOverlay.getOverlayView().dispatchDraw(canvas);
15316            }
15317
15318            // we're done...
15319            return;
15320        }
15321
15322        /*
15323         * Here we do the full fledged routine...
15324         * (this is an uncommon case where speed matters less,
15325         * this is why we repeat some of the tests that have been
15326         * done above)
15327         */
15328
15329        boolean drawTop = false;
15330        boolean drawBottom = false;
15331        boolean drawLeft = false;
15332        boolean drawRight = false;
15333
15334        float topFadeStrength = 0.0f;
15335        float bottomFadeStrength = 0.0f;
15336        float leftFadeStrength = 0.0f;
15337        float rightFadeStrength = 0.0f;
15338
15339        // Step 2, save the canvas' layers
15340        int paddingLeft = mPaddingLeft;
15341
15342        final boolean offsetRequired = isPaddingOffsetRequired();
15343        if (offsetRequired) {
15344            paddingLeft += getLeftPaddingOffset();
15345        }
15346
15347        int left = mScrollX + paddingLeft;
15348        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15349        int top = mScrollY + getFadeTop(offsetRequired);
15350        int bottom = top + getFadeHeight(offsetRequired);
15351
15352        if (offsetRequired) {
15353            right += getRightPaddingOffset();
15354            bottom += getBottomPaddingOffset();
15355        }
15356
15357        final ScrollabilityCache scrollabilityCache = mScrollCache;
15358        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15359        int length = (int) fadeHeight;
15360
15361        // clip the fade length if top and bottom fades overlap
15362        // overlapping fades produce odd-looking artifacts
15363        if (verticalEdges && (top + length > bottom - length)) {
15364            length = (bottom - top) / 2;
15365        }
15366
15367        // also clip horizontal fades if necessary
15368        if (horizontalEdges && (left + length > right - length)) {
15369            length = (right - left) / 2;
15370        }
15371
15372        if (verticalEdges) {
15373            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15374            drawTop = topFadeStrength * fadeHeight > 1.0f;
15375            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15376            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15377        }
15378
15379        if (horizontalEdges) {
15380            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15381            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15382            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15383            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15384        }
15385
15386        saveCount = canvas.getSaveCount();
15387
15388        int solidColor = getSolidColor();
15389        if (solidColor == 0) {
15390            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15391
15392            if (drawTop) {
15393                canvas.saveLayer(left, top, right, top + length, null, flags);
15394            }
15395
15396            if (drawBottom) {
15397                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15398            }
15399
15400            if (drawLeft) {
15401                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15402            }
15403
15404            if (drawRight) {
15405                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15406            }
15407        } else {
15408            scrollabilityCache.setFadeColor(solidColor);
15409        }
15410
15411        // Step 3, draw the content
15412        if (!dirtyOpaque) onDraw(canvas);
15413
15414        // Step 4, draw the children
15415        dispatchDraw(canvas);
15416
15417        // Step 5, draw the fade effect and restore layers
15418        final Paint p = scrollabilityCache.paint;
15419        final Matrix matrix = scrollabilityCache.matrix;
15420        final Shader fade = scrollabilityCache.shader;
15421
15422        if (drawTop) {
15423            matrix.setScale(1, fadeHeight * topFadeStrength);
15424            matrix.postTranslate(left, top);
15425            fade.setLocalMatrix(matrix);
15426            p.setShader(fade);
15427            canvas.drawRect(left, top, right, top + length, p);
15428        }
15429
15430        if (drawBottom) {
15431            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15432            matrix.postRotate(180);
15433            matrix.postTranslate(left, bottom);
15434            fade.setLocalMatrix(matrix);
15435            p.setShader(fade);
15436            canvas.drawRect(left, bottom - length, right, bottom, p);
15437        }
15438
15439        if (drawLeft) {
15440            matrix.setScale(1, fadeHeight * leftFadeStrength);
15441            matrix.postRotate(-90);
15442            matrix.postTranslate(left, top);
15443            fade.setLocalMatrix(matrix);
15444            p.setShader(fade);
15445            canvas.drawRect(left, top, left + length, bottom, p);
15446        }
15447
15448        if (drawRight) {
15449            matrix.setScale(1, fadeHeight * rightFadeStrength);
15450            matrix.postRotate(90);
15451            matrix.postTranslate(right, top);
15452            fade.setLocalMatrix(matrix);
15453            p.setShader(fade);
15454            canvas.drawRect(right - length, top, right, bottom, p);
15455        }
15456
15457        canvas.restoreToCount(saveCount);
15458
15459        // Step 6, draw decorations (scrollbars)
15460        onDrawScrollBars(canvas);
15461
15462        if (mOverlay != null && !mOverlay.isEmpty()) {
15463            mOverlay.getOverlayView().dispatchDraw(canvas);
15464        }
15465    }
15466
15467    /**
15468     * Draws the background onto the specified canvas.
15469     *
15470     * @param canvas Canvas on which to draw the background
15471     */
15472    private void drawBackground(Canvas canvas) {
15473        final Drawable background = mBackground;
15474        if (background == null) {
15475            return;
15476        }
15477
15478        if (mBackgroundSizeChanged) {
15479            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15480            mBackgroundSizeChanged = false;
15481            rebuildOutline();
15482        }
15483
15484        // Attempt to use a display list if requested.
15485        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15486                && mAttachInfo.mHardwareRenderer != null) {
15487            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15488
15489            final RenderNode renderNode = mBackgroundRenderNode;
15490            if (renderNode != null && renderNode.isValid()) {
15491                setBackgroundRenderNodeProperties(renderNode);
15492                ((HardwareCanvas) canvas).drawRenderNode(renderNode);
15493                return;
15494            }
15495        }
15496
15497        final int scrollX = mScrollX;
15498        final int scrollY = mScrollY;
15499        if ((scrollX | scrollY) == 0) {
15500            background.draw(canvas);
15501        } else {
15502            canvas.translate(scrollX, scrollY);
15503            background.draw(canvas);
15504            canvas.translate(-scrollX, -scrollY);
15505        }
15506    }
15507
15508    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15509        renderNode.setTranslationX(mScrollX);
15510        renderNode.setTranslationY(mScrollY);
15511    }
15512
15513    /**
15514     * Creates a new display list or updates the existing display list for the
15515     * specified Drawable.
15516     *
15517     * @param drawable Drawable for which to create a display list
15518     * @param renderNode Existing RenderNode, or {@code null}
15519     * @return A valid display list for the specified drawable
15520     */
15521    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15522        if (renderNode == null) {
15523            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15524        }
15525
15526        final Rect bounds = drawable.getBounds();
15527        final int width = bounds.width();
15528        final int height = bounds.height();
15529        final HardwareCanvas canvas = renderNode.start(width, height);
15530        try {
15531            drawable.draw(canvas);
15532        } finally {
15533            renderNode.end(canvas);
15534        }
15535
15536        // Set up drawable properties that are view-independent.
15537        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15538        renderNode.setProjectBackwards(drawable.isProjected());
15539        renderNode.setProjectionReceiver(true);
15540        renderNode.setClipToBounds(false);
15541        return renderNode;
15542    }
15543
15544    /**
15545     * Returns the overlay for this view, creating it if it does not yet exist.
15546     * Adding drawables to the overlay will cause them to be displayed whenever
15547     * the view itself is redrawn. Objects in the overlay should be actively
15548     * managed: remove them when they should not be displayed anymore. The
15549     * overlay will always have the same size as its host view.
15550     *
15551     * <p>Note: Overlays do not currently work correctly with {@link
15552     * SurfaceView} or {@link TextureView}; contents in overlays for these
15553     * types of views may not display correctly.</p>
15554     *
15555     * @return The ViewOverlay object for this view.
15556     * @see ViewOverlay
15557     */
15558    public ViewOverlay getOverlay() {
15559        if (mOverlay == null) {
15560            mOverlay = new ViewOverlay(mContext, this);
15561        }
15562        return mOverlay;
15563    }
15564
15565    /**
15566     * Override this if your view is known to always be drawn on top of a solid color background,
15567     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15568     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15569     * should be set to 0xFF.
15570     *
15571     * @see #setVerticalFadingEdgeEnabled(boolean)
15572     * @see #setHorizontalFadingEdgeEnabled(boolean)
15573     *
15574     * @return The known solid color background for this view, or 0 if the color may vary
15575     */
15576    @ViewDebug.ExportedProperty(category = "drawing")
15577    public int getSolidColor() {
15578        return 0;
15579    }
15580
15581    /**
15582     * Build a human readable string representation of the specified view flags.
15583     *
15584     * @param flags the view flags to convert to a string
15585     * @return a String representing the supplied flags
15586     */
15587    private static String printFlags(int flags) {
15588        String output = "";
15589        int numFlags = 0;
15590        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15591            output += "TAKES_FOCUS";
15592            numFlags++;
15593        }
15594
15595        switch (flags & VISIBILITY_MASK) {
15596        case INVISIBLE:
15597            if (numFlags > 0) {
15598                output += " ";
15599            }
15600            output += "INVISIBLE";
15601            // USELESS HERE numFlags++;
15602            break;
15603        case GONE:
15604            if (numFlags > 0) {
15605                output += " ";
15606            }
15607            output += "GONE";
15608            // USELESS HERE numFlags++;
15609            break;
15610        default:
15611            break;
15612        }
15613        return output;
15614    }
15615
15616    /**
15617     * Build a human readable string representation of the specified private
15618     * view flags.
15619     *
15620     * @param privateFlags the private view flags to convert to a string
15621     * @return a String representing the supplied flags
15622     */
15623    private static String printPrivateFlags(int privateFlags) {
15624        String output = "";
15625        int numFlags = 0;
15626
15627        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15628            output += "WANTS_FOCUS";
15629            numFlags++;
15630        }
15631
15632        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15633            if (numFlags > 0) {
15634                output += " ";
15635            }
15636            output += "FOCUSED";
15637            numFlags++;
15638        }
15639
15640        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15641            if (numFlags > 0) {
15642                output += " ";
15643            }
15644            output += "SELECTED";
15645            numFlags++;
15646        }
15647
15648        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15649            if (numFlags > 0) {
15650                output += " ";
15651            }
15652            output += "IS_ROOT_NAMESPACE";
15653            numFlags++;
15654        }
15655
15656        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15657            if (numFlags > 0) {
15658                output += " ";
15659            }
15660            output += "HAS_BOUNDS";
15661            numFlags++;
15662        }
15663
15664        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15665            if (numFlags > 0) {
15666                output += " ";
15667            }
15668            output += "DRAWN";
15669            // USELESS HERE numFlags++;
15670        }
15671        return output;
15672    }
15673
15674    /**
15675     * <p>Indicates whether or not this view's layout will be requested during
15676     * the next hierarchy layout pass.</p>
15677     *
15678     * @return true if the layout will be forced during next layout pass
15679     */
15680    public boolean isLayoutRequested() {
15681        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15682    }
15683
15684    /**
15685     * Return true if o is a ViewGroup that is laying out using optical bounds.
15686     * @hide
15687     */
15688    public static boolean isLayoutModeOptical(Object o) {
15689        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15690    }
15691
15692    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15693        Insets parentInsets = mParent instanceof View ?
15694                ((View) mParent).getOpticalInsets() : Insets.NONE;
15695        Insets childInsets = getOpticalInsets();
15696        return setFrame(
15697                left   + parentInsets.left - childInsets.left,
15698                top    + parentInsets.top  - childInsets.top,
15699                right  + parentInsets.left + childInsets.right,
15700                bottom + parentInsets.top  + childInsets.bottom);
15701    }
15702
15703    /**
15704     * Assign a size and position to a view and all of its
15705     * descendants
15706     *
15707     * <p>This is the second phase of the layout mechanism.
15708     * (The first is measuring). In this phase, each parent calls
15709     * layout on all of its children to position them.
15710     * This is typically done using the child measurements
15711     * that were stored in the measure pass().</p>
15712     *
15713     * <p>Derived classes should not override this method.
15714     * Derived classes with children should override
15715     * onLayout. In that method, they should
15716     * call layout on each of their children.</p>
15717     *
15718     * @param l Left position, relative to parent
15719     * @param t Top position, relative to parent
15720     * @param r Right position, relative to parent
15721     * @param b Bottom position, relative to parent
15722     */
15723    @SuppressWarnings({"unchecked"})
15724    public void layout(int l, int t, int r, int b) {
15725        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15726            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15727            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15728        }
15729
15730        int oldL = mLeft;
15731        int oldT = mTop;
15732        int oldB = mBottom;
15733        int oldR = mRight;
15734
15735        boolean changed = isLayoutModeOptical(mParent) ?
15736                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15737
15738        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15739            onLayout(changed, l, t, r, b);
15740            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15741
15742            ListenerInfo li = mListenerInfo;
15743            if (li != null && li.mOnLayoutChangeListeners != null) {
15744                ArrayList<OnLayoutChangeListener> listenersCopy =
15745                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15746                int numListeners = listenersCopy.size();
15747                for (int i = 0; i < numListeners; ++i) {
15748                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15749                }
15750            }
15751        }
15752
15753        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15754        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15755    }
15756
15757    /**
15758     * Called from layout when this view should
15759     * assign a size and position to each of its children.
15760     *
15761     * Derived classes with children should override
15762     * this method and call layout on each of
15763     * their children.
15764     * @param changed This is a new size or position for this view
15765     * @param left Left position, relative to parent
15766     * @param top Top position, relative to parent
15767     * @param right Right position, relative to parent
15768     * @param bottom Bottom position, relative to parent
15769     */
15770    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15771    }
15772
15773    /**
15774     * Assign a size and position to this view.
15775     *
15776     * This is called from layout.
15777     *
15778     * @param left Left position, relative to parent
15779     * @param top Top position, relative to parent
15780     * @param right Right position, relative to parent
15781     * @param bottom Bottom position, relative to parent
15782     * @return true if the new size and position are different than the
15783     *         previous ones
15784     * {@hide}
15785     */
15786    protected boolean setFrame(int left, int top, int right, int bottom) {
15787        boolean changed = false;
15788
15789        if (DBG) {
15790            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15791                    + right + "," + bottom + ")");
15792        }
15793
15794        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15795            changed = true;
15796
15797            // Remember our drawn bit
15798            int drawn = mPrivateFlags & PFLAG_DRAWN;
15799
15800            int oldWidth = mRight - mLeft;
15801            int oldHeight = mBottom - mTop;
15802            int newWidth = right - left;
15803            int newHeight = bottom - top;
15804            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15805
15806            // Invalidate our old position
15807            invalidate(sizeChanged);
15808
15809            mLeft = left;
15810            mTop = top;
15811            mRight = right;
15812            mBottom = bottom;
15813            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15814
15815            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15816
15817
15818            if (sizeChanged) {
15819                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15820            }
15821
15822            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
15823                // If we are visible, force the DRAWN bit to on so that
15824                // this invalidate will go through (at least to our parent).
15825                // This is because someone may have invalidated this view
15826                // before this call to setFrame came in, thereby clearing
15827                // the DRAWN bit.
15828                mPrivateFlags |= PFLAG_DRAWN;
15829                invalidate(sizeChanged);
15830                // parent display list may need to be recreated based on a change in the bounds
15831                // of any child
15832                invalidateParentCaches();
15833            }
15834
15835            // Reset drawn bit to original value (invalidate turns it off)
15836            mPrivateFlags |= drawn;
15837
15838            mBackgroundSizeChanged = true;
15839
15840            notifySubtreeAccessibilityStateChangedIfNeeded();
15841        }
15842        return changed;
15843    }
15844
15845    /**
15846     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
15847     * @hide
15848     */
15849    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
15850        setFrame(left, top, right, bottom);
15851    }
15852
15853    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15854        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15855        if (mOverlay != null) {
15856            mOverlay.getOverlayView().setRight(newWidth);
15857            mOverlay.getOverlayView().setBottom(newHeight);
15858        }
15859        rebuildOutline();
15860    }
15861
15862    /**
15863     * Finalize inflating a view from XML.  This is called as the last phase
15864     * of inflation, after all child views have been added.
15865     *
15866     * <p>Even if the subclass overrides onFinishInflate, they should always be
15867     * sure to call the super method, so that we get called.
15868     */
15869    protected void onFinishInflate() {
15870    }
15871
15872    /**
15873     * Returns the resources associated with this view.
15874     *
15875     * @return Resources object.
15876     */
15877    public Resources getResources() {
15878        return mResources;
15879    }
15880
15881    /**
15882     * Invalidates the specified Drawable.
15883     *
15884     * @param drawable the drawable to invalidate
15885     */
15886    @Override
15887    public void invalidateDrawable(@NonNull Drawable drawable) {
15888        if (verifyDrawable(drawable)) {
15889            final Rect dirty = drawable.getDirtyBounds();
15890            final int scrollX = mScrollX;
15891            final int scrollY = mScrollY;
15892
15893            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15894                    dirty.right + scrollX, dirty.bottom + scrollY);
15895            rebuildOutline();
15896        }
15897    }
15898
15899    /**
15900     * Schedules an action on a drawable to occur at a specified time.
15901     *
15902     * @param who the recipient of the action
15903     * @param what the action to run on the drawable
15904     * @param when the time at which the action must occur. Uses the
15905     *        {@link SystemClock#uptimeMillis} timebase.
15906     */
15907    @Override
15908    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15909        if (verifyDrawable(who) && what != null) {
15910            final long delay = when - SystemClock.uptimeMillis();
15911            if (mAttachInfo != null) {
15912                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15913                        Choreographer.CALLBACK_ANIMATION, what, who,
15914                        Choreographer.subtractFrameDelay(delay));
15915            } else {
15916                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15917            }
15918        }
15919    }
15920
15921    /**
15922     * Cancels a scheduled action on a drawable.
15923     *
15924     * @param who the recipient of the action
15925     * @param what the action to cancel
15926     */
15927    @Override
15928    public void unscheduleDrawable(Drawable who, Runnable what) {
15929        if (verifyDrawable(who) && what != null) {
15930            if (mAttachInfo != null) {
15931                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15932                        Choreographer.CALLBACK_ANIMATION, what, who);
15933            }
15934            ViewRootImpl.getRunQueue().removeCallbacks(what);
15935        }
15936    }
15937
15938    /**
15939     * Unschedule any events associated with the given Drawable.  This can be
15940     * used when selecting a new Drawable into a view, so that the previous
15941     * one is completely unscheduled.
15942     *
15943     * @param who The Drawable to unschedule.
15944     *
15945     * @see #drawableStateChanged
15946     */
15947    public void unscheduleDrawable(Drawable who) {
15948        if (mAttachInfo != null && who != null) {
15949            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15950                    Choreographer.CALLBACK_ANIMATION, null, who);
15951        }
15952    }
15953
15954    /**
15955     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15956     * that the View directionality can and will be resolved before its Drawables.
15957     *
15958     * Will call {@link View#onResolveDrawables} when resolution is done.
15959     *
15960     * @hide
15961     */
15962    protected void resolveDrawables() {
15963        // Drawables resolution may need to happen before resolving the layout direction (which is
15964        // done only during the measure() call).
15965        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15966        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15967        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15968        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15969        // direction to be resolved as its resolved value will be the same as its raw value.
15970        if (!isLayoutDirectionResolved() &&
15971                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15972            return;
15973        }
15974
15975        final int layoutDirection = isLayoutDirectionResolved() ?
15976                getLayoutDirection() : getRawLayoutDirection();
15977
15978        if (mBackground != null) {
15979            mBackground.setLayoutDirection(layoutDirection);
15980        }
15981        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15982        onResolveDrawables(layoutDirection);
15983    }
15984
15985    boolean areDrawablesResolved() {
15986        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15987    }
15988
15989    /**
15990     * Called when layout direction has been resolved.
15991     *
15992     * The default implementation does nothing.
15993     *
15994     * @param layoutDirection The resolved layout direction.
15995     *
15996     * @see #LAYOUT_DIRECTION_LTR
15997     * @see #LAYOUT_DIRECTION_RTL
15998     *
15999     * @hide
16000     */
16001    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16002    }
16003
16004    /**
16005     * @hide
16006     */
16007    protected void resetResolvedDrawables() {
16008        resetResolvedDrawablesInternal();
16009    }
16010
16011    void resetResolvedDrawablesInternal() {
16012        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16013    }
16014
16015    /**
16016     * If your view subclass is displaying its own Drawable objects, it should
16017     * override this function and return true for any Drawable it is
16018     * displaying.  This allows animations for those drawables to be
16019     * scheduled.
16020     *
16021     * <p>Be sure to call through to the super class when overriding this
16022     * function.
16023     *
16024     * @param who The Drawable to verify.  Return true if it is one you are
16025     *            displaying, else return the result of calling through to the
16026     *            super class.
16027     *
16028     * @return boolean If true than the Drawable is being displayed in the
16029     *         view; else false and it is not allowed to animate.
16030     *
16031     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16032     * @see #drawableStateChanged()
16033     */
16034    protected boolean verifyDrawable(Drawable who) {
16035        return who == mBackground;
16036    }
16037
16038    /**
16039     * This function is called whenever the state of the view changes in such
16040     * a way that it impacts the state of drawables being shown.
16041     * <p>
16042     * If the View has a StateListAnimator, it will also be called to run necessary state
16043     * change animations.
16044     * <p>
16045     * Be sure to call through to the superclass when overriding this function.
16046     *
16047     * @see Drawable#setState(int[])
16048     */
16049    protected void drawableStateChanged() {
16050        final Drawable d = mBackground;
16051        if (d != null && d.isStateful()) {
16052            d.setState(getDrawableState());
16053        }
16054
16055        if (mStateListAnimator != null) {
16056            mStateListAnimator.setState(getDrawableState());
16057        }
16058    }
16059
16060    /**
16061     * This function is called whenever the view hotspot changes and needs to
16062     * be propagated to drawables or child views managed by the view.
16063     * <p>
16064     * Dispatching to child views is handled by
16065     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16066     * <p>
16067     * Be sure to call through to the superclass when overriding this function.
16068     *
16069     * @param x hotspot x coordinate
16070     * @param y hotspot y coordinate
16071     */
16072    public void drawableHotspotChanged(float x, float y) {
16073        if (mBackground != null) {
16074            mBackground.setHotspot(x, y);
16075        }
16076
16077        dispatchDrawableHotspotChanged(x, y);
16078    }
16079
16080    /**
16081     * Dispatches drawableHotspotChanged to all of this View's children.
16082     *
16083     * @param x hotspot x coordinate
16084     * @param y hotspot y coordinate
16085     * @see #drawableHotspotChanged(float, float)
16086     */
16087    public void dispatchDrawableHotspotChanged(float x, float y) {
16088    }
16089
16090    /**
16091     * Call this to force a view to update its drawable state. This will cause
16092     * drawableStateChanged to be called on this view. Views that are interested
16093     * in the new state should call getDrawableState.
16094     *
16095     * @see #drawableStateChanged
16096     * @see #getDrawableState
16097     */
16098    public void refreshDrawableState() {
16099        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16100        drawableStateChanged();
16101
16102        ViewParent parent = mParent;
16103        if (parent != null) {
16104            parent.childDrawableStateChanged(this);
16105        }
16106    }
16107
16108    /**
16109     * Return an array of resource IDs of the drawable states representing the
16110     * current state of the view.
16111     *
16112     * @return The current drawable state
16113     *
16114     * @see Drawable#setState(int[])
16115     * @see #drawableStateChanged()
16116     * @see #onCreateDrawableState(int)
16117     */
16118    public final int[] getDrawableState() {
16119        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16120            return mDrawableState;
16121        } else {
16122            mDrawableState = onCreateDrawableState(0);
16123            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16124            return mDrawableState;
16125        }
16126    }
16127
16128    /**
16129     * Generate the new {@link android.graphics.drawable.Drawable} state for
16130     * this view. This is called by the view
16131     * system when the cached Drawable state is determined to be invalid.  To
16132     * retrieve the current state, you should use {@link #getDrawableState}.
16133     *
16134     * @param extraSpace if non-zero, this is the number of extra entries you
16135     * would like in the returned array in which you can place your own
16136     * states.
16137     *
16138     * @return Returns an array holding the current {@link Drawable} state of
16139     * the view.
16140     *
16141     * @see #mergeDrawableStates(int[], int[])
16142     */
16143    protected int[] onCreateDrawableState(int extraSpace) {
16144        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16145                mParent instanceof View) {
16146            return ((View) mParent).onCreateDrawableState(extraSpace);
16147        }
16148
16149        int[] drawableState;
16150
16151        int privateFlags = mPrivateFlags;
16152
16153        int viewStateIndex = 0;
16154        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
16155        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
16156        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
16157        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
16158        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
16159        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
16160        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16161                HardwareRenderer.isAvailable()) {
16162            // This is set if HW acceleration is requested, even if the current
16163            // process doesn't allow it.  This is just to allow app preview
16164            // windows to better match their app.
16165            viewStateIndex |= VIEW_STATE_ACCELERATED;
16166        }
16167        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
16168
16169        final int privateFlags2 = mPrivateFlags2;
16170        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
16171        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
16172
16173        drawableState = VIEW_STATE_SETS[viewStateIndex];
16174
16175        //noinspection ConstantIfStatement
16176        if (false) {
16177            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16178            Log.i("View", toString()
16179                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16180                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16181                    + " fo=" + hasFocus()
16182                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16183                    + " wf=" + hasWindowFocus()
16184                    + ": " + Arrays.toString(drawableState));
16185        }
16186
16187        if (extraSpace == 0) {
16188            return drawableState;
16189        }
16190
16191        final int[] fullState;
16192        if (drawableState != null) {
16193            fullState = new int[drawableState.length + extraSpace];
16194            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16195        } else {
16196            fullState = new int[extraSpace];
16197        }
16198
16199        return fullState;
16200    }
16201
16202    /**
16203     * Merge your own state values in <var>additionalState</var> into the base
16204     * state values <var>baseState</var> that were returned by
16205     * {@link #onCreateDrawableState(int)}.
16206     *
16207     * @param baseState The base state values returned by
16208     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16209     * own additional state values.
16210     *
16211     * @param additionalState The additional state values you would like
16212     * added to <var>baseState</var>; this array is not modified.
16213     *
16214     * @return As a convenience, the <var>baseState</var> array you originally
16215     * passed into the function is returned.
16216     *
16217     * @see #onCreateDrawableState(int)
16218     */
16219    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16220        final int N = baseState.length;
16221        int i = N - 1;
16222        while (i >= 0 && baseState[i] == 0) {
16223            i--;
16224        }
16225        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16226        return baseState;
16227    }
16228
16229    /**
16230     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16231     * on all Drawable objects associated with this view.
16232     * <p>
16233     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16234     * attached to this view.
16235     */
16236    public void jumpDrawablesToCurrentState() {
16237        if (mBackground != null) {
16238            mBackground.jumpToCurrentState();
16239        }
16240        if (mStateListAnimator != null) {
16241            mStateListAnimator.jumpToCurrentState();
16242        }
16243    }
16244
16245    /**
16246     * Sets the background color for this view.
16247     * @param color the color of the background
16248     */
16249    @RemotableViewMethod
16250    public void setBackgroundColor(int color) {
16251        if (mBackground instanceof ColorDrawable) {
16252            ((ColorDrawable) mBackground.mutate()).setColor(color);
16253            computeOpaqueFlags();
16254            mBackgroundResource = 0;
16255        } else {
16256            setBackground(new ColorDrawable(color));
16257        }
16258    }
16259
16260    /**
16261     * Set the background to a given resource. The resource should refer to
16262     * a Drawable object or 0 to remove the background.
16263     * @param resid The identifier of the resource.
16264     *
16265     * @attr ref android.R.styleable#View_background
16266     */
16267    @RemotableViewMethod
16268    public void setBackgroundResource(int resid) {
16269        if (resid != 0 && resid == mBackgroundResource) {
16270            return;
16271        }
16272
16273        Drawable d = null;
16274        if (resid != 0) {
16275            d = mContext.getDrawable(resid);
16276        }
16277        setBackground(d);
16278
16279        mBackgroundResource = resid;
16280    }
16281
16282    /**
16283     * Set the background to a given Drawable, or remove the background. If the
16284     * background has padding, this View's padding is set to the background's
16285     * padding. However, when a background is removed, this View's padding isn't
16286     * touched. If setting the padding is desired, please use
16287     * {@link #setPadding(int, int, int, int)}.
16288     *
16289     * @param background The Drawable to use as the background, or null to remove the
16290     *        background
16291     */
16292    public void setBackground(Drawable background) {
16293        //noinspection deprecation
16294        setBackgroundDrawable(background);
16295    }
16296
16297    /**
16298     * @deprecated use {@link #setBackground(Drawable)} instead
16299     */
16300    @Deprecated
16301    public void setBackgroundDrawable(Drawable background) {
16302        computeOpaqueFlags();
16303
16304        if (background == mBackground) {
16305            return;
16306        }
16307
16308        boolean requestLayout = false;
16309
16310        mBackgroundResource = 0;
16311
16312        /*
16313         * Regardless of whether we're setting a new background or not, we want
16314         * to clear the previous drawable.
16315         */
16316        if (mBackground != null) {
16317            mBackground.setCallback(null);
16318            unscheduleDrawable(mBackground);
16319        }
16320
16321        if (background != null) {
16322            Rect padding = sThreadLocal.get();
16323            if (padding == null) {
16324                padding = new Rect();
16325                sThreadLocal.set(padding);
16326            }
16327            resetResolvedDrawablesInternal();
16328            background.setLayoutDirection(getLayoutDirection());
16329            if (background.getPadding(padding)) {
16330                resetResolvedPaddingInternal();
16331                switch (background.getLayoutDirection()) {
16332                    case LAYOUT_DIRECTION_RTL:
16333                        mUserPaddingLeftInitial = padding.right;
16334                        mUserPaddingRightInitial = padding.left;
16335                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16336                        break;
16337                    case LAYOUT_DIRECTION_LTR:
16338                    default:
16339                        mUserPaddingLeftInitial = padding.left;
16340                        mUserPaddingRightInitial = padding.right;
16341                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16342                }
16343                mLeftPaddingDefined = false;
16344                mRightPaddingDefined = false;
16345            }
16346
16347            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16348            // if it has a different minimum size, we should layout again
16349            if (mBackground == null
16350                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16351                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16352                requestLayout = true;
16353            }
16354
16355            background.setCallback(this);
16356            if (background.isStateful()) {
16357                background.setState(getDrawableState());
16358            }
16359            background.setVisible(getVisibility() == VISIBLE, false);
16360            mBackground = background;
16361
16362            applyBackgroundTint();
16363
16364            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16365                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16366                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16367                requestLayout = true;
16368            }
16369        } else {
16370            /* Remove the background */
16371            mBackground = null;
16372
16373            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16374                /*
16375                 * This view ONLY drew the background before and we're removing
16376                 * the background, so now it won't draw anything
16377                 * (hence we SKIP_DRAW)
16378                 */
16379                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16380                mPrivateFlags |= PFLAG_SKIP_DRAW;
16381            }
16382
16383            /*
16384             * When the background is set, we try to apply its padding to this
16385             * View. When the background is removed, we don't touch this View's
16386             * padding. This is noted in the Javadocs. Hence, we don't need to
16387             * requestLayout(), the invalidate() below is sufficient.
16388             */
16389
16390            // The old background's minimum size could have affected this
16391            // View's layout, so let's requestLayout
16392            requestLayout = true;
16393        }
16394
16395        computeOpaqueFlags();
16396
16397        if (requestLayout) {
16398            requestLayout();
16399        }
16400
16401        mBackgroundSizeChanged = true;
16402        invalidate(true);
16403    }
16404
16405    /**
16406     * Gets the background drawable
16407     *
16408     * @return The drawable used as the background for this view, if any.
16409     *
16410     * @see #setBackground(Drawable)
16411     *
16412     * @attr ref android.R.styleable#View_background
16413     */
16414    public Drawable getBackground() {
16415        return mBackground;
16416    }
16417
16418    /**
16419     * Applies a tint to the background drawable. Does not modify the current tint
16420     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16421     * <p>
16422     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16423     * mutate the drawable and apply the specified tint and tint mode using
16424     * {@link Drawable#setTintList(ColorStateList)}.
16425     *
16426     * @param tint the tint to apply, may be {@code null} to clear tint
16427     *
16428     * @attr ref android.R.styleable#View_backgroundTint
16429     * @see #getBackgroundTintList()
16430     * @see Drawable#setTintList(ColorStateList)
16431     */
16432    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16433        if (mBackgroundTint == null) {
16434            mBackgroundTint = new TintInfo();
16435        }
16436        mBackgroundTint.mTintList = tint;
16437        mBackgroundTint.mHasTintList = true;
16438
16439        applyBackgroundTint();
16440    }
16441
16442    /**
16443     * Return the tint applied to the background drawable, if specified.
16444     *
16445     * @return the tint applied to the background drawable
16446     * @attr ref android.R.styleable#View_backgroundTint
16447     * @see #setBackgroundTintList(ColorStateList)
16448     */
16449    @Nullable
16450    public ColorStateList getBackgroundTintList() {
16451        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16452    }
16453
16454    /**
16455     * Specifies the blending mode used to apply the tint specified by
16456     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16457     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16458     *
16459     * @param tintMode the blending mode used to apply the tint, may be
16460     *                 {@code null} to clear tint
16461     * @attr ref android.R.styleable#View_backgroundTintMode
16462     * @see #getBackgroundTintMode()
16463     * @see Drawable#setTintMode(PorterDuff.Mode)
16464     */
16465    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16466        if (mBackgroundTint == null) {
16467            mBackgroundTint = new TintInfo();
16468        }
16469        mBackgroundTint.mTintMode = tintMode;
16470        mBackgroundTint.mHasTintMode = true;
16471
16472        applyBackgroundTint();
16473    }
16474
16475    /**
16476     * Return the blending mode used to apply the tint to the background
16477     * drawable, if specified.
16478     *
16479     * @return the blending mode used to apply the tint to the background
16480     *         drawable
16481     * @attr ref android.R.styleable#View_backgroundTintMode
16482     * @see #setBackgroundTintMode(PorterDuff.Mode)
16483     */
16484    @Nullable
16485    public PorterDuff.Mode getBackgroundTintMode() {
16486        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16487    }
16488
16489    private void applyBackgroundTint() {
16490        if (mBackground != null && mBackgroundTint != null) {
16491            final TintInfo tintInfo = mBackgroundTint;
16492            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16493                mBackground = mBackground.mutate();
16494
16495                if (tintInfo.mHasTintList) {
16496                    mBackground.setTintList(tintInfo.mTintList);
16497                }
16498
16499                if (tintInfo.mHasTintMode) {
16500                    mBackground.setTintMode(tintInfo.mTintMode);
16501                }
16502
16503                // The drawable (or one of its children) may not have been
16504                // stateful before applying the tint, so let's try again.
16505                if (mBackground.isStateful()) {
16506                    mBackground.setState(getDrawableState());
16507                }
16508            }
16509        }
16510    }
16511
16512    /**
16513     * Sets the padding. The view may add on the space required to display
16514     * the scrollbars, depending on the style and visibility of the scrollbars.
16515     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16516     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16517     * from the values set in this call.
16518     *
16519     * @attr ref android.R.styleable#View_padding
16520     * @attr ref android.R.styleable#View_paddingBottom
16521     * @attr ref android.R.styleable#View_paddingLeft
16522     * @attr ref android.R.styleable#View_paddingRight
16523     * @attr ref android.R.styleable#View_paddingTop
16524     * @param left the left padding in pixels
16525     * @param top the top padding in pixels
16526     * @param right the right padding in pixels
16527     * @param bottom the bottom padding in pixels
16528     */
16529    public void setPadding(int left, int top, int right, int bottom) {
16530        resetResolvedPaddingInternal();
16531
16532        mUserPaddingStart = UNDEFINED_PADDING;
16533        mUserPaddingEnd = UNDEFINED_PADDING;
16534
16535        mUserPaddingLeftInitial = left;
16536        mUserPaddingRightInitial = right;
16537
16538        mLeftPaddingDefined = true;
16539        mRightPaddingDefined = true;
16540
16541        internalSetPadding(left, top, right, bottom);
16542    }
16543
16544    /**
16545     * @hide
16546     */
16547    protected void internalSetPadding(int left, int top, int right, int bottom) {
16548        mUserPaddingLeft = left;
16549        mUserPaddingRight = right;
16550        mUserPaddingBottom = bottom;
16551
16552        final int viewFlags = mViewFlags;
16553        boolean changed = false;
16554
16555        // Common case is there are no scroll bars.
16556        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16557            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16558                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16559                        ? 0 : getVerticalScrollbarWidth();
16560                switch (mVerticalScrollbarPosition) {
16561                    case SCROLLBAR_POSITION_DEFAULT:
16562                        if (isLayoutRtl()) {
16563                            left += offset;
16564                        } else {
16565                            right += offset;
16566                        }
16567                        break;
16568                    case SCROLLBAR_POSITION_RIGHT:
16569                        right += offset;
16570                        break;
16571                    case SCROLLBAR_POSITION_LEFT:
16572                        left += offset;
16573                        break;
16574                }
16575            }
16576            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16577                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16578                        ? 0 : getHorizontalScrollbarHeight();
16579            }
16580        }
16581
16582        if (mPaddingLeft != left) {
16583            changed = true;
16584            mPaddingLeft = left;
16585        }
16586        if (mPaddingTop != top) {
16587            changed = true;
16588            mPaddingTop = top;
16589        }
16590        if (mPaddingRight != right) {
16591            changed = true;
16592            mPaddingRight = right;
16593        }
16594        if (mPaddingBottom != bottom) {
16595            changed = true;
16596            mPaddingBottom = bottom;
16597        }
16598
16599        if (changed) {
16600            requestLayout();
16601        }
16602    }
16603
16604    /**
16605     * Sets the relative padding. The view may add on the space required to display
16606     * the scrollbars, depending on the style and visibility of the scrollbars.
16607     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16608     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16609     * from the values set in this call.
16610     *
16611     * @attr ref android.R.styleable#View_padding
16612     * @attr ref android.R.styleable#View_paddingBottom
16613     * @attr ref android.R.styleable#View_paddingStart
16614     * @attr ref android.R.styleable#View_paddingEnd
16615     * @attr ref android.R.styleable#View_paddingTop
16616     * @param start the start padding in pixels
16617     * @param top the top padding in pixels
16618     * @param end the end padding in pixels
16619     * @param bottom the bottom padding in pixels
16620     */
16621    public void setPaddingRelative(int start, int top, int end, int bottom) {
16622        resetResolvedPaddingInternal();
16623
16624        mUserPaddingStart = start;
16625        mUserPaddingEnd = end;
16626        mLeftPaddingDefined = true;
16627        mRightPaddingDefined = true;
16628
16629        switch(getLayoutDirection()) {
16630            case LAYOUT_DIRECTION_RTL:
16631                mUserPaddingLeftInitial = end;
16632                mUserPaddingRightInitial = start;
16633                internalSetPadding(end, top, start, bottom);
16634                break;
16635            case LAYOUT_DIRECTION_LTR:
16636            default:
16637                mUserPaddingLeftInitial = start;
16638                mUserPaddingRightInitial = end;
16639                internalSetPadding(start, top, end, bottom);
16640        }
16641    }
16642
16643    /**
16644     * Returns the top padding of this view.
16645     *
16646     * @return the top padding in pixels
16647     */
16648    public int getPaddingTop() {
16649        return mPaddingTop;
16650    }
16651
16652    /**
16653     * Returns the bottom padding of this view. If there are inset and enabled
16654     * scrollbars, this value may include the space required to display the
16655     * scrollbars as well.
16656     *
16657     * @return the bottom padding in pixels
16658     */
16659    public int getPaddingBottom() {
16660        return mPaddingBottom;
16661    }
16662
16663    /**
16664     * Returns the left padding of this view. If there are inset and enabled
16665     * scrollbars, this value may include the space required to display the
16666     * scrollbars as well.
16667     *
16668     * @return the left padding in pixels
16669     */
16670    public int getPaddingLeft() {
16671        if (!isPaddingResolved()) {
16672            resolvePadding();
16673        }
16674        return mPaddingLeft;
16675    }
16676
16677    /**
16678     * Returns the start padding of this view depending on its resolved layout direction.
16679     * If there are inset and enabled scrollbars, this value may include the space
16680     * required to display the scrollbars as well.
16681     *
16682     * @return the start padding in pixels
16683     */
16684    public int getPaddingStart() {
16685        if (!isPaddingResolved()) {
16686            resolvePadding();
16687        }
16688        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16689                mPaddingRight : mPaddingLeft;
16690    }
16691
16692    /**
16693     * Returns the right padding of this view. If there are inset and enabled
16694     * scrollbars, this value may include the space required to display the
16695     * scrollbars as well.
16696     *
16697     * @return the right padding in pixels
16698     */
16699    public int getPaddingRight() {
16700        if (!isPaddingResolved()) {
16701            resolvePadding();
16702        }
16703        return mPaddingRight;
16704    }
16705
16706    /**
16707     * Returns the end padding of this view depending on its resolved layout direction.
16708     * If there are inset and enabled scrollbars, this value may include the space
16709     * required to display the scrollbars as well.
16710     *
16711     * @return the end padding in pixels
16712     */
16713    public int getPaddingEnd() {
16714        if (!isPaddingResolved()) {
16715            resolvePadding();
16716        }
16717        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16718                mPaddingLeft : mPaddingRight;
16719    }
16720
16721    /**
16722     * Return if the padding as been set thru relative values
16723     * {@link #setPaddingRelative(int, int, int, int)} or thru
16724     * @attr ref android.R.styleable#View_paddingStart or
16725     * @attr ref android.R.styleable#View_paddingEnd
16726     *
16727     * @return true if the padding is relative or false if it is not.
16728     */
16729    public boolean isPaddingRelative() {
16730        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16731    }
16732
16733    Insets computeOpticalInsets() {
16734        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16735    }
16736
16737    /**
16738     * @hide
16739     */
16740    public void resetPaddingToInitialValues() {
16741        if (isRtlCompatibilityMode()) {
16742            mPaddingLeft = mUserPaddingLeftInitial;
16743            mPaddingRight = mUserPaddingRightInitial;
16744            return;
16745        }
16746        if (isLayoutRtl()) {
16747            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16748            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16749        } else {
16750            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16751            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16752        }
16753    }
16754
16755    /**
16756     * @hide
16757     */
16758    public Insets getOpticalInsets() {
16759        if (mLayoutInsets == null) {
16760            mLayoutInsets = computeOpticalInsets();
16761        }
16762        return mLayoutInsets;
16763    }
16764
16765    /**
16766     * Set this view's optical insets.
16767     *
16768     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16769     * property. Views that compute their own optical insets should call it as part of measurement.
16770     * This method does not request layout. If you are setting optical insets outside of
16771     * measure/layout itself you will want to call requestLayout() yourself.
16772     * </p>
16773     * @hide
16774     */
16775    public void setOpticalInsets(Insets insets) {
16776        mLayoutInsets = insets;
16777    }
16778
16779    /**
16780     * Changes the selection state of this view. A view can be selected or not.
16781     * Note that selection is not the same as focus. Views are typically
16782     * selected in the context of an AdapterView like ListView or GridView;
16783     * the selected view is the view that is highlighted.
16784     *
16785     * @param selected true if the view must be selected, false otherwise
16786     */
16787    public void setSelected(boolean selected) {
16788        //noinspection DoubleNegation
16789        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16790            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16791            if (!selected) resetPressedState();
16792            invalidate(true);
16793            refreshDrawableState();
16794            dispatchSetSelected(selected);
16795            if (selected) {
16796                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
16797            } else {
16798                notifyViewAccessibilityStateChangedIfNeeded(
16799                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16800            }
16801        }
16802    }
16803
16804    /**
16805     * Dispatch setSelected to all of this View's children.
16806     *
16807     * @see #setSelected(boolean)
16808     *
16809     * @param selected The new selected state
16810     */
16811    protected void dispatchSetSelected(boolean selected) {
16812    }
16813
16814    /**
16815     * Indicates the selection state of this view.
16816     *
16817     * @return true if the view is selected, false otherwise
16818     */
16819    @ViewDebug.ExportedProperty
16820    public boolean isSelected() {
16821        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16822    }
16823
16824    /**
16825     * Changes the activated state of this view. A view can be activated or not.
16826     * Note that activation is not the same as selection.  Selection is
16827     * a transient property, representing the view (hierarchy) the user is
16828     * currently interacting with.  Activation is a longer-term state that the
16829     * user can move views in and out of.  For example, in a list view with
16830     * single or multiple selection enabled, the views in the current selection
16831     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16832     * here.)  The activated state is propagated down to children of the view it
16833     * is set on.
16834     *
16835     * @param activated true if the view must be activated, false otherwise
16836     */
16837    public void setActivated(boolean activated) {
16838        //noinspection DoubleNegation
16839        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16840            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16841            invalidate(true);
16842            refreshDrawableState();
16843            dispatchSetActivated(activated);
16844        }
16845    }
16846
16847    /**
16848     * Dispatch setActivated to all of this View's children.
16849     *
16850     * @see #setActivated(boolean)
16851     *
16852     * @param activated The new activated state
16853     */
16854    protected void dispatchSetActivated(boolean activated) {
16855    }
16856
16857    /**
16858     * Indicates the activation state of this view.
16859     *
16860     * @return true if the view is activated, false otherwise
16861     */
16862    @ViewDebug.ExportedProperty
16863    public boolean isActivated() {
16864        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16865    }
16866
16867    /**
16868     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16869     * observer can be used to get notifications when global events, like
16870     * layout, happen.
16871     *
16872     * The returned ViewTreeObserver observer is not guaranteed to remain
16873     * valid for the lifetime of this View. If the caller of this method keeps
16874     * a long-lived reference to ViewTreeObserver, it should always check for
16875     * the return value of {@link ViewTreeObserver#isAlive()}.
16876     *
16877     * @return The ViewTreeObserver for this view's hierarchy.
16878     */
16879    public ViewTreeObserver getViewTreeObserver() {
16880        if (mAttachInfo != null) {
16881            return mAttachInfo.mTreeObserver;
16882        }
16883        if (mFloatingTreeObserver == null) {
16884            mFloatingTreeObserver = new ViewTreeObserver();
16885        }
16886        return mFloatingTreeObserver;
16887    }
16888
16889    /**
16890     * <p>Finds the topmost view in the current view hierarchy.</p>
16891     *
16892     * @return the topmost view containing this view
16893     */
16894    public View getRootView() {
16895        if (mAttachInfo != null) {
16896            final View v = mAttachInfo.mRootView;
16897            if (v != null) {
16898                return v;
16899            }
16900        }
16901
16902        View parent = this;
16903
16904        while (parent.mParent != null && parent.mParent instanceof View) {
16905            parent = (View) parent.mParent;
16906        }
16907
16908        return parent;
16909    }
16910
16911    /**
16912     * Transforms a motion event from view-local coordinates to on-screen
16913     * coordinates.
16914     *
16915     * @param ev the view-local motion event
16916     * @return false if the transformation could not be applied
16917     * @hide
16918     */
16919    public boolean toGlobalMotionEvent(MotionEvent ev) {
16920        final AttachInfo info = mAttachInfo;
16921        if (info == null) {
16922            return false;
16923        }
16924
16925        final Matrix m = info.mTmpMatrix;
16926        m.set(Matrix.IDENTITY_MATRIX);
16927        transformMatrixToGlobal(m);
16928        ev.transform(m);
16929        return true;
16930    }
16931
16932    /**
16933     * Transforms a motion event from on-screen coordinates to view-local
16934     * coordinates.
16935     *
16936     * @param ev the on-screen motion event
16937     * @return false if the transformation could not be applied
16938     * @hide
16939     */
16940    public boolean toLocalMotionEvent(MotionEvent ev) {
16941        final AttachInfo info = mAttachInfo;
16942        if (info == null) {
16943            return false;
16944        }
16945
16946        final Matrix m = info.mTmpMatrix;
16947        m.set(Matrix.IDENTITY_MATRIX);
16948        transformMatrixToLocal(m);
16949        ev.transform(m);
16950        return true;
16951    }
16952
16953    /**
16954     * Modifies the input matrix such that it maps view-local coordinates to
16955     * on-screen coordinates.
16956     *
16957     * @param m input matrix to modify
16958     * @hide
16959     */
16960    public void transformMatrixToGlobal(Matrix m) {
16961        final ViewParent parent = mParent;
16962        if (parent instanceof View) {
16963            final View vp = (View) parent;
16964            vp.transformMatrixToGlobal(m);
16965            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16966        } else if (parent instanceof ViewRootImpl) {
16967            final ViewRootImpl vr = (ViewRootImpl) parent;
16968            vr.transformMatrixToGlobal(m);
16969            m.preTranslate(0, -vr.mCurScrollY);
16970        }
16971
16972        m.preTranslate(mLeft, mTop);
16973
16974        if (!hasIdentityMatrix()) {
16975            m.preConcat(getMatrix());
16976        }
16977    }
16978
16979    /**
16980     * Modifies the input matrix such that it maps on-screen coordinates to
16981     * view-local coordinates.
16982     *
16983     * @param m input matrix to modify
16984     * @hide
16985     */
16986    public void transformMatrixToLocal(Matrix m) {
16987        final ViewParent parent = mParent;
16988        if (parent instanceof View) {
16989            final View vp = (View) parent;
16990            vp.transformMatrixToLocal(m);
16991            m.postTranslate(vp.mScrollX, vp.mScrollY);
16992        } else if (parent instanceof ViewRootImpl) {
16993            final ViewRootImpl vr = (ViewRootImpl) parent;
16994            vr.transformMatrixToLocal(m);
16995            m.postTranslate(0, vr.mCurScrollY);
16996        }
16997
16998        m.postTranslate(-mLeft, -mTop);
16999
17000        if (!hasIdentityMatrix()) {
17001            m.postConcat(getInverseMatrix());
17002        }
17003    }
17004
17005    /**
17006     * @hide
17007     */
17008    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17009            @ViewDebug.IntToString(from = 0, to = "x"),
17010            @ViewDebug.IntToString(from = 1, to = "y")
17011    })
17012    public int[] getLocationOnScreen() {
17013        int[] location = new int[2];
17014        getLocationOnScreen(location);
17015        return location;
17016    }
17017
17018    /**
17019     * <p>Computes the coordinates of this view on the screen. The argument
17020     * must be an array of two integers. After the method returns, the array
17021     * contains the x and y location in that order.</p>
17022     *
17023     * @param location an array of two integers in which to hold the coordinates
17024     */
17025    public void getLocationOnScreen(int[] location) {
17026        getLocationInWindow(location);
17027
17028        final AttachInfo info = mAttachInfo;
17029        if (info != null) {
17030            location[0] += info.mWindowLeft;
17031            location[1] += info.mWindowTop;
17032        }
17033    }
17034
17035    /**
17036     * <p>Computes the coordinates of this view in its window. The argument
17037     * must be an array of two integers. After the method returns, the array
17038     * contains the x and y location in that order.</p>
17039     *
17040     * @param location an array of two integers in which to hold the coordinates
17041     */
17042    public void getLocationInWindow(int[] location) {
17043        if (location == null || location.length < 2) {
17044            throw new IllegalArgumentException("location must be an array of two integers");
17045        }
17046
17047        if (mAttachInfo == null) {
17048            // When the view is not attached to a window, this method does not make sense
17049            location[0] = location[1] = 0;
17050            return;
17051        }
17052
17053        float[] position = mAttachInfo.mTmpTransformLocation;
17054        position[0] = position[1] = 0.0f;
17055
17056        if (!hasIdentityMatrix()) {
17057            getMatrix().mapPoints(position);
17058        }
17059
17060        position[0] += mLeft;
17061        position[1] += mTop;
17062
17063        ViewParent viewParent = mParent;
17064        while (viewParent instanceof View) {
17065            final View view = (View) viewParent;
17066
17067            position[0] -= view.mScrollX;
17068            position[1] -= view.mScrollY;
17069
17070            if (!view.hasIdentityMatrix()) {
17071                view.getMatrix().mapPoints(position);
17072            }
17073
17074            position[0] += view.mLeft;
17075            position[1] += view.mTop;
17076
17077            viewParent = view.mParent;
17078         }
17079
17080        if (viewParent instanceof ViewRootImpl) {
17081            // *cough*
17082            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17083            position[1] -= vr.mCurScrollY;
17084        }
17085
17086        location[0] = (int) (position[0] + 0.5f);
17087        location[1] = (int) (position[1] + 0.5f);
17088    }
17089
17090    /**
17091     * {@hide}
17092     * @param id the id of the view to be found
17093     * @return the view of the specified id, null if cannot be found
17094     */
17095    protected View findViewTraversal(int id) {
17096        if (id == mID) {
17097            return this;
17098        }
17099        return null;
17100    }
17101
17102    /**
17103     * {@hide}
17104     * @param tag the tag of the view to be found
17105     * @return the view of specified tag, null if cannot be found
17106     */
17107    protected View findViewWithTagTraversal(Object tag) {
17108        if (tag != null && tag.equals(mTag)) {
17109            return this;
17110        }
17111        return null;
17112    }
17113
17114    /**
17115     * {@hide}
17116     * @param predicate The predicate to evaluate.
17117     * @param childToSkip If not null, ignores this child during the recursive traversal.
17118     * @return The first view that matches the predicate or null.
17119     */
17120    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17121        if (predicate.apply(this)) {
17122            return this;
17123        }
17124        return null;
17125    }
17126
17127    /**
17128     * Look for a child view with the given id.  If this view has the given
17129     * id, return this view.
17130     *
17131     * @param id The id to search for.
17132     * @return The view that has the given id in the hierarchy or null
17133     */
17134    public final View findViewById(int id) {
17135        if (id < 0) {
17136            return null;
17137        }
17138        return findViewTraversal(id);
17139    }
17140
17141    /**
17142     * Finds a view by its unuque and stable accessibility id.
17143     *
17144     * @param accessibilityId The searched accessibility id.
17145     * @return The found view.
17146     */
17147    final View findViewByAccessibilityId(int accessibilityId) {
17148        if (accessibilityId < 0) {
17149            return null;
17150        }
17151        return findViewByAccessibilityIdTraversal(accessibilityId);
17152    }
17153
17154    /**
17155     * Performs the traversal to find a view by its unuque and stable accessibility id.
17156     *
17157     * <strong>Note:</strong>This method does not stop at the root namespace
17158     * boundary since the user can touch the screen at an arbitrary location
17159     * potentially crossing the root namespace bounday which will send an
17160     * accessibility event to accessibility services and they should be able
17161     * to obtain the event source. Also accessibility ids are guaranteed to be
17162     * unique in the window.
17163     *
17164     * @param accessibilityId The accessibility id.
17165     * @return The found view.
17166     *
17167     * @hide
17168     */
17169    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17170        if (getAccessibilityViewId() == accessibilityId) {
17171            return this;
17172        }
17173        return null;
17174    }
17175
17176    /**
17177     * Look for a child view with the given tag.  If this view has the given
17178     * tag, return this view.
17179     *
17180     * @param tag The tag to search for, using "tag.equals(getTag())".
17181     * @return The View that has the given tag in the hierarchy or null
17182     */
17183    public final View findViewWithTag(Object tag) {
17184        if (tag == null) {
17185            return null;
17186        }
17187        return findViewWithTagTraversal(tag);
17188    }
17189
17190    /**
17191     * {@hide}
17192     * Look for a child view that matches the specified predicate.
17193     * If this view matches the predicate, return this view.
17194     *
17195     * @param predicate The predicate to evaluate.
17196     * @return The first view that matches the predicate or null.
17197     */
17198    public final View findViewByPredicate(Predicate<View> predicate) {
17199        return findViewByPredicateTraversal(predicate, null);
17200    }
17201
17202    /**
17203     * {@hide}
17204     * Look for a child view that matches the specified predicate,
17205     * starting with the specified view and its descendents and then
17206     * recusively searching the ancestors and siblings of that view
17207     * until this view is reached.
17208     *
17209     * This method is useful in cases where the predicate does not match
17210     * a single unique view (perhaps multiple views use the same id)
17211     * and we are trying to find the view that is "closest" in scope to the
17212     * starting view.
17213     *
17214     * @param start The view to start from.
17215     * @param predicate The predicate to evaluate.
17216     * @return The first view that matches the predicate or null.
17217     */
17218    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17219        View childToSkip = null;
17220        for (;;) {
17221            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17222            if (view != null || start == this) {
17223                return view;
17224            }
17225
17226            ViewParent parent = start.getParent();
17227            if (parent == null || !(parent instanceof View)) {
17228                return null;
17229            }
17230
17231            childToSkip = start;
17232            start = (View) parent;
17233        }
17234    }
17235
17236    /**
17237     * Sets the identifier for this view. The identifier does not have to be
17238     * unique in this view's hierarchy. The identifier should be a positive
17239     * number.
17240     *
17241     * @see #NO_ID
17242     * @see #getId()
17243     * @see #findViewById(int)
17244     *
17245     * @param id a number used to identify the view
17246     *
17247     * @attr ref android.R.styleable#View_id
17248     */
17249    public void setId(int id) {
17250        mID = id;
17251        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17252            mID = generateViewId();
17253        }
17254    }
17255
17256    /**
17257     * {@hide}
17258     *
17259     * @param isRoot true if the view belongs to the root namespace, false
17260     *        otherwise
17261     */
17262    public void setIsRootNamespace(boolean isRoot) {
17263        if (isRoot) {
17264            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17265        } else {
17266            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17267        }
17268    }
17269
17270    /**
17271     * {@hide}
17272     *
17273     * @return true if the view belongs to the root namespace, false otherwise
17274     */
17275    public boolean isRootNamespace() {
17276        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17277    }
17278
17279    /**
17280     * Returns this view's identifier.
17281     *
17282     * @return a positive integer used to identify the view or {@link #NO_ID}
17283     *         if the view has no ID
17284     *
17285     * @see #setId(int)
17286     * @see #findViewById(int)
17287     * @attr ref android.R.styleable#View_id
17288     */
17289    @ViewDebug.CapturedViewProperty
17290    public int getId() {
17291        return mID;
17292    }
17293
17294    /**
17295     * Returns this view's tag.
17296     *
17297     * @return the Object stored in this view as a tag, or {@code null} if not
17298     *         set
17299     *
17300     * @see #setTag(Object)
17301     * @see #getTag(int)
17302     */
17303    @ViewDebug.ExportedProperty
17304    public Object getTag() {
17305        return mTag;
17306    }
17307
17308    /**
17309     * Sets the tag associated with this view. A tag can be used to mark
17310     * a view in its hierarchy and does not have to be unique within the
17311     * hierarchy. Tags can also be used to store data within a view without
17312     * resorting to another data structure.
17313     *
17314     * @param tag an Object to tag the view with
17315     *
17316     * @see #getTag()
17317     * @see #setTag(int, Object)
17318     */
17319    public void setTag(final Object tag) {
17320        mTag = tag;
17321    }
17322
17323    /**
17324     * Returns the tag associated with this view and the specified key.
17325     *
17326     * @param key The key identifying the tag
17327     *
17328     * @return the Object stored in this view as a tag, or {@code null} if not
17329     *         set
17330     *
17331     * @see #setTag(int, Object)
17332     * @see #getTag()
17333     */
17334    public Object getTag(int key) {
17335        if (mKeyedTags != null) return mKeyedTags.get(key);
17336        return null;
17337    }
17338
17339    /**
17340     * Sets a tag associated with this view and a key. A tag can be used
17341     * to mark a view in its hierarchy and does not have to be unique within
17342     * the hierarchy. Tags can also be used to store data within a view
17343     * without resorting to another data structure.
17344     *
17345     * The specified key should be an id declared in the resources of the
17346     * application to ensure it is unique (see the <a
17347     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17348     * Keys identified as belonging to
17349     * the Android framework or not associated with any package will cause
17350     * an {@link IllegalArgumentException} to be thrown.
17351     *
17352     * @param key The key identifying the tag
17353     * @param tag An Object to tag the view with
17354     *
17355     * @throws IllegalArgumentException If they specified key is not valid
17356     *
17357     * @see #setTag(Object)
17358     * @see #getTag(int)
17359     */
17360    public void setTag(int key, final Object tag) {
17361        // If the package id is 0x00 or 0x01, it's either an undefined package
17362        // or a framework id
17363        if ((key >>> 24) < 2) {
17364            throw new IllegalArgumentException("The key must be an application-specific "
17365                    + "resource id.");
17366        }
17367
17368        setKeyedTag(key, tag);
17369    }
17370
17371    /**
17372     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17373     * framework id.
17374     *
17375     * @hide
17376     */
17377    public void setTagInternal(int key, Object tag) {
17378        if ((key >>> 24) != 0x1) {
17379            throw new IllegalArgumentException("The key must be a framework-specific "
17380                    + "resource id.");
17381        }
17382
17383        setKeyedTag(key, tag);
17384    }
17385
17386    private void setKeyedTag(int key, Object tag) {
17387        if (mKeyedTags == null) {
17388            mKeyedTags = new SparseArray<Object>(2);
17389        }
17390
17391        mKeyedTags.put(key, tag);
17392    }
17393
17394    /**
17395     * Prints information about this view in the log output, with the tag
17396     * {@link #VIEW_LOG_TAG}.
17397     *
17398     * @hide
17399     */
17400    public void debug() {
17401        debug(0);
17402    }
17403
17404    /**
17405     * Prints information about this view in the log output, with the tag
17406     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17407     * indentation defined by the <code>depth</code>.
17408     *
17409     * @param depth the indentation level
17410     *
17411     * @hide
17412     */
17413    protected void debug(int depth) {
17414        String output = debugIndent(depth - 1);
17415
17416        output += "+ " + this;
17417        int id = getId();
17418        if (id != -1) {
17419            output += " (id=" + id + ")";
17420        }
17421        Object tag = getTag();
17422        if (tag != null) {
17423            output += " (tag=" + tag + ")";
17424        }
17425        Log.d(VIEW_LOG_TAG, output);
17426
17427        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17428            output = debugIndent(depth) + " FOCUSED";
17429            Log.d(VIEW_LOG_TAG, output);
17430        }
17431
17432        output = debugIndent(depth);
17433        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17434                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17435                + "} ";
17436        Log.d(VIEW_LOG_TAG, output);
17437
17438        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17439                || mPaddingBottom != 0) {
17440            output = debugIndent(depth);
17441            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17442                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17443            Log.d(VIEW_LOG_TAG, output);
17444        }
17445
17446        output = debugIndent(depth);
17447        output += "mMeasureWidth=" + mMeasuredWidth +
17448                " mMeasureHeight=" + mMeasuredHeight;
17449        Log.d(VIEW_LOG_TAG, output);
17450
17451        output = debugIndent(depth);
17452        if (mLayoutParams == null) {
17453            output += "BAD! no layout params";
17454        } else {
17455            output = mLayoutParams.debug(output);
17456        }
17457        Log.d(VIEW_LOG_TAG, output);
17458
17459        output = debugIndent(depth);
17460        output += "flags={";
17461        output += View.printFlags(mViewFlags);
17462        output += "}";
17463        Log.d(VIEW_LOG_TAG, output);
17464
17465        output = debugIndent(depth);
17466        output += "privateFlags={";
17467        output += View.printPrivateFlags(mPrivateFlags);
17468        output += "}";
17469        Log.d(VIEW_LOG_TAG, output);
17470    }
17471
17472    /**
17473     * Creates a string of whitespaces used for indentation.
17474     *
17475     * @param depth the indentation level
17476     * @return a String containing (depth * 2 + 3) * 2 white spaces
17477     *
17478     * @hide
17479     */
17480    protected static String debugIndent(int depth) {
17481        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17482        for (int i = 0; i < (depth * 2) + 3; i++) {
17483            spaces.append(' ').append(' ');
17484        }
17485        return spaces.toString();
17486    }
17487
17488    /**
17489     * <p>Return the offset of the widget's text baseline from the widget's top
17490     * boundary. If this widget does not support baseline alignment, this
17491     * method returns -1. </p>
17492     *
17493     * @return the offset of the baseline within the widget's bounds or -1
17494     *         if baseline alignment is not supported
17495     */
17496    @ViewDebug.ExportedProperty(category = "layout")
17497    public int getBaseline() {
17498        return -1;
17499    }
17500
17501    /**
17502     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17503     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17504     * a layout pass.
17505     *
17506     * @return whether the view hierarchy is currently undergoing a layout pass
17507     */
17508    public boolean isInLayout() {
17509        ViewRootImpl viewRoot = getViewRootImpl();
17510        return (viewRoot != null && viewRoot.isInLayout());
17511    }
17512
17513    /**
17514     * Call this when something has changed which has invalidated the
17515     * layout of this view. This will schedule a layout pass of the view
17516     * tree. This should not be called while the view hierarchy is currently in a layout
17517     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17518     * end of the current layout pass (and then layout will run again) or after the current
17519     * frame is drawn and the next layout occurs.
17520     *
17521     * <p>Subclasses which override this method should call the superclass method to
17522     * handle possible request-during-layout errors correctly.</p>
17523     */
17524    public void requestLayout() {
17525        if (mMeasureCache != null) mMeasureCache.clear();
17526
17527        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17528            // Only trigger request-during-layout logic if this is the view requesting it,
17529            // not the views in its parent hierarchy
17530            ViewRootImpl viewRoot = getViewRootImpl();
17531            if (viewRoot != null && viewRoot.isInLayout()) {
17532                if (!viewRoot.requestLayoutDuringLayout(this)) {
17533                    return;
17534                }
17535            }
17536            mAttachInfo.mViewRequestingLayout = this;
17537        }
17538
17539        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17540        mPrivateFlags |= PFLAG_INVALIDATED;
17541
17542        if (mParent != null && !mParent.isLayoutRequested()) {
17543            mParent.requestLayout();
17544        }
17545        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17546            mAttachInfo.mViewRequestingLayout = null;
17547        }
17548    }
17549
17550    /**
17551     * Forces this view to be laid out during the next layout pass.
17552     * This method does not call requestLayout() or forceLayout()
17553     * on the parent.
17554     */
17555    public void forceLayout() {
17556        if (mMeasureCache != null) mMeasureCache.clear();
17557
17558        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17559        mPrivateFlags |= PFLAG_INVALIDATED;
17560    }
17561
17562    /**
17563     * <p>
17564     * This is called to find out how big a view should be. The parent
17565     * supplies constraint information in the width and height parameters.
17566     * </p>
17567     *
17568     * <p>
17569     * The actual measurement work of a view is performed in
17570     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17571     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17572     * </p>
17573     *
17574     *
17575     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17576     *        parent
17577     * @param heightMeasureSpec Vertical space requirements as imposed by the
17578     *        parent
17579     *
17580     * @see #onMeasure(int, int)
17581     */
17582    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17583        boolean optical = isLayoutModeOptical(this);
17584        if (optical != isLayoutModeOptical(mParent)) {
17585            Insets insets = getOpticalInsets();
17586            int oWidth  = insets.left + insets.right;
17587            int oHeight = insets.top  + insets.bottom;
17588            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17589            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17590        }
17591
17592        // Suppress sign extension for the low bytes
17593        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17594        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17595
17596        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17597        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
17598                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
17599        final boolean matchingSize = isExactly &&
17600                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
17601                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
17602        if (forceLayout || !matchingSize &&
17603                (widthMeasureSpec != mOldWidthMeasureSpec ||
17604                        heightMeasureSpec != mOldHeightMeasureSpec)) {
17605
17606            // first clears the measured dimension flag
17607            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17608
17609            resolveRtlPropertiesIfNeeded();
17610
17611            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
17612            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17613                // measure ourselves, this should set the measured dimension flag back
17614                onMeasure(widthMeasureSpec, heightMeasureSpec);
17615                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17616            } else {
17617                long value = mMeasureCache.valueAt(cacheIndex);
17618                // Casting a long to int drops the high 32 bits, no mask needed
17619                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17620                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17621            }
17622
17623            // flag not set, setMeasuredDimension() was not invoked, we raise
17624            // an exception to warn the developer
17625            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17626                throw new IllegalStateException("onMeasure() did not set the"
17627                        + " measured dimension by calling"
17628                        + " setMeasuredDimension()");
17629            }
17630
17631            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17632        }
17633
17634        mOldWidthMeasureSpec = widthMeasureSpec;
17635        mOldHeightMeasureSpec = heightMeasureSpec;
17636
17637        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17638                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17639    }
17640
17641    /**
17642     * <p>
17643     * Measure the view and its content to determine the measured width and the
17644     * measured height. This method is invoked by {@link #measure(int, int)} and
17645     * should be overriden by subclasses to provide accurate and efficient
17646     * measurement of their contents.
17647     * </p>
17648     *
17649     * <p>
17650     * <strong>CONTRACT:</strong> When overriding this method, you
17651     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17652     * measured width and height of this view. Failure to do so will trigger an
17653     * <code>IllegalStateException</code>, thrown by
17654     * {@link #measure(int, int)}. Calling the superclass'
17655     * {@link #onMeasure(int, int)} is a valid use.
17656     * </p>
17657     *
17658     * <p>
17659     * The base class implementation of measure defaults to the background size,
17660     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17661     * override {@link #onMeasure(int, int)} to provide better measurements of
17662     * their content.
17663     * </p>
17664     *
17665     * <p>
17666     * If this method is overridden, it is the subclass's responsibility to make
17667     * sure the measured height and width are at least the view's minimum height
17668     * and width ({@link #getSuggestedMinimumHeight()} and
17669     * {@link #getSuggestedMinimumWidth()}).
17670     * </p>
17671     *
17672     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17673     *                         The requirements are encoded with
17674     *                         {@link android.view.View.MeasureSpec}.
17675     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17676     *                         The requirements are encoded with
17677     *                         {@link android.view.View.MeasureSpec}.
17678     *
17679     * @see #getMeasuredWidth()
17680     * @see #getMeasuredHeight()
17681     * @see #setMeasuredDimension(int, int)
17682     * @see #getSuggestedMinimumHeight()
17683     * @see #getSuggestedMinimumWidth()
17684     * @see android.view.View.MeasureSpec#getMode(int)
17685     * @see android.view.View.MeasureSpec#getSize(int)
17686     */
17687    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17688        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17689                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17690    }
17691
17692    /**
17693     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17694     * measured width and measured height. Failing to do so will trigger an
17695     * exception at measurement time.</p>
17696     *
17697     * @param measuredWidth The measured width of this view.  May be a complex
17698     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17699     * {@link #MEASURED_STATE_TOO_SMALL}.
17700     * @param measuredHeight The measured height of this view.  May be a complex
17701     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17702     * {@link #MEASURED_STATE_TOO_SMALL}.
17703     */
17704    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17705        boolean optical = isLayoutModeOptical(this);
17706        if (optical != isLayoutModeOptical(mParent)) {
17707            Insets insets = getOpticalInsets();
17708            int opticalWidth  = insets.left + insets.right;
17709            int opticalHeight = insets.top  + insets.bottom;
17710
17711            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17712            measuredHeight += optical ? opticalHeight : -opticalHeight;
17713        }
17714        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17715    }
17716
17717    /**
17718     * Sets the measured dimension without extra processing for things like optical bounds.
17719     * Useful for reapplying consistent values that have already been cooked with adjustments
17720     * for optical bounds, etc. such as those from the measurement cache.
17721     *
17722     * @param measuredWidth The measured width of this view.  May be a complex
17723     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17724     * {@link #MEASURED_STATE_TOO_SMALL}.
17725     * @param measuredHeight The measured height of this view.  May be a complex
17726     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17727     * {@link #MEASURED_STATE_TOO_SMALL}.
17728     */
17729    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17730        mMeasuredWidth = measuredWidth;
17731        mMeasuredHeight = measuredHeight;
17732
17733        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17734    }
17735
17736    /**
17737     * Merge two states as returned by {@link #getMeasuredState()}.
17738     * @param curState The current state as returned from a view or the result
17739     * of combining multiple views.
17740     * @param newState The new view state to combine.
17741     * @return Returns a new integer reflecting the combination of the two
17742     * states.
17743     */
17744    public static int combineMeasuredStates(int curState, int newState) {
17745        return curState | newState;
17746    }
17747
17748    /**
17749     * Version of {@link #resolveSizeAndState(int, int, int)}
17750     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17751     */
17752    public static int resolveSize(int size, int measureSpec) {
17753        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17754    }
17755
17756    /**
17757     * Utility to reconcile a desired size and state, with constraints imposed
17758     * by a MeasureSpec.  Will take the desired size, unless a different size
17759     * is imposed by the constraints.  The returned value is a compound integer,
17760     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17761     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17762     * size is smaller than the size the view wants to be.
17763     *
17764     * @param size How big the view wants to be
17765     * @param measureSpec Constraints imposed by the parent
17766     * @return Size information bit mask as defined by
17767     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17768     */
17769    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17770        int result = size;
17771        int specMode = MeasureSpec.getMode(measureSpec);
17772        int specSize =  MeasureSpec.getSize(measureSpec);
17773        switch (specMode) {
17774        case MeasureSpec.UNSPECIFIED:
17775            result = size;
17776            break;
17777        case MeasureSpec.AT_MOST:
17778            if (specSize < size) {
17779                result = specSize | MEASURED_STATE_TOO_SMALL;
17780            } else {
17781                result = size;
17782            }
17783            break;
17784        case MeasureSpec.EXACTLY:
17785            result = specSize;
17786            break;
17787        }
17788        return result | (childMeasuredState&MEASURED_STATE_MASK);
17789    }
17790
17791    /**
17792     * Utility to return a default size. Uses the supplied size if the
17793     * MeasureSpec imposed no constraints. Will get larger if allowed
17794     * by the MeasureSpec.
17795     *
17796     * @param size Default size for this view
17797     * @param measureSpec Constraints imposed by the parent
17798     * @return The size this view should be.
17799     */
17800    public static int getDefaultSize(int size, int measureSpec) {
17801        int result = size;
17802        int specMode = MeasureSpec.getMode(measureSpec);
17803        int specSize = MeasureSpec.getSize(measureSpec);
17804
17805        switch (specMode) {
17806        case MeasureSpec.UNSPECIFIED:
17807            result = size;
17808            break;
17809        case MeasureSpec.AT_MOST:
17810        case MeasureSpec.EXACTLY:
17811            result = specSize;
17812            break;
17813        }
17814        return result;
17815    }
17816
17817    /**
17818     * Returns the suggested minimum height that the view should use. This
17819     * returns the maximum of the view's minimum height
17820     * and the background's minimum height
17821     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17822     * <p>
17823     * When being used in {@link #onMeasure(int, int)}, the caller should still
17824     * ensure the returned height is within the requirements of the parent.
17825     *
17826     * @return The suggested minimum height of the view.
17827     */
17828    protected int getSuggestedMinimumHeight() {
17829        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17830
17831    }
17832
17833    /**
17834     * Returns the suggested minimum width that the view should use. This
17835     * returns the maximum of the view's minimum width)
17836     * and the background's minimum width
17837     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17838     * <p>
17839     * When being used in {@link #onMeasure(int, int)}, the caller should still
17840     * ensure the returned width is within the requirements of the parent.
17841     *
17842     * @return The suggested minimum width of the view.
17843     */
17844    protected int getSuggestedMinimumWidth() {
17845        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17846    }
17847
17848    /**
17849     * Returns the minimum height of the view.
17850     *
17851     * @return the minimum height the view will try to be.
17852     *
17853     * @see #setMinimumHeight(int)
17854     *
17855     * @attr ref android.R.styleable#View_minHeight
17856     */
17857    public int getMinimumHeight() {
17858        return mMinHeight;
17859    }
17860
17861    /**
17862     * Sets the minimum height of the view. It is not guaranteed the view will
17863     * be able to achieve this minimum height (for example, if its parent layout
17864     * constrains it with less available height).
17865     *
17866     * @param minHeight The minimum height the view will try to be.
17867     *
17868     * @see #getMinimumHeight()
17869     *
17870     * @attr ref android.R.styleable#View_minHeight
17871     */
17872    public void setMinimumHeight(int minHeight) {
17873        mMinHeight = minHeight;
17874        requestLayout();
17875    }
17876
17877    /**
17878     * Returns the minimum width of the view.
17879     *
17880     * @return the minimum width the view will try to be.
17881     *
17882     * @see #setMinimumWidth(int)
17883     *
17884     * @attr ref android.R.styleable#View_minWidth
17885     */
17886    public int getMinimumWidth() {
17887        return mMinWidth;
17888    }
17889
17890    /**
17891     * Sets the minimum width of the view. It is not guaranteed the view will
17892     * be able to achieve this minimum width (for example, if its parent layout
17893     * constrains it with less available width).
17894     *
17895     * @param minWidth The minimum width the view will try to be.
17896     *
17897     * @see #getMinimumWidth()
17898     *
17899     * @attr ref android.R.styleable#View_minWidth
17900     */
17901    public void setMinimumWidth(int minWidth) {
17902        mMinWidth = minWidth;
17903        requestLayout();
17904
17905    }
17906
17907    /**
17908     * Get the animation currently associated with this view.
17909     *
17910     * @return The animation that is currently playing or
17911     *         scheduled to play for this view.
17912     */
17913    public Animation getAnimation() {
17914        return mCurrentAnimation;
17915    }
17916
17917    /**
17918     * Start the specified animation now.
17919     *
17920     * @param animation the animation to start now
17921     */
17922    public void startAnimation(Animation animation) {
17923        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17924        setAnimation(animation);
17925        invalidateParentCaches();
17926        invalidate(true);
17927    }
17928
17929    /**
17930     * Cancels any animations for this view.
17931     */
17932    public void clearAnimation() {
17933        if (mCurrentAnimation != null) {
17934            mCurrentAnimation.detach();
17935        }
17936        mCurrentAnimation = null;
17937        invalidateParentIfNeeded();
17938    }
17939
17940    /**
17941     * Sets the next animation to play for this view.
17942     * If you want the animation to play immediately, use
17943     * {@link #startAnimation(android.view.animation.Animation)} instead.
17944     * This method provides allows fine-grained
17945     * control over the start time and invalidation, but you
17946     * must make sure that 1) the animation has a start time set, and
17947     * 2) the view's parent (which controls animations on its children)
17948     * will be invalidated when the animation is supposed to
17949     * start.
17950     *
17951     * @param animation The next animation, or null.
17952     */
17953    public void setAnimation(Animation animation) {
17954        mCurrentAnimation = animation;
17955
17956        if (animation != null) {
17957            // If the screen is off assume the animation start time is now instead of
17958            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17959            // would cause the animation to start when the screen turns back on
17960            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17961                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17962                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17963            }
17964            animation.reset();
17965        }
17966    }
17967
17968    /**
17969     * Invoked by a parent ViewGroup to notify the start of the animation
17970     * currently associated with this view. If you override this method,
17971     * always call super.onAnimationStart();
17972     *
17973     * @see #setAnimation(android.view.animation.Animation)
17974     * @see #getAnimation()
17975     */
17976    protected void onAnimationStart() {
17977        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17978    }
17979
17980    /**
17981     * Invoked by a parent ViewGroup to notify the end of the animation
17982     * currently associated with this view. If you override this method,
17983     * always call super.onAnimationEnd();
17984     *
17985     * @see #setAnimation(android.view.animation.Animation)
17986     * @see #getAnimation()
17987     */
17988    protected void onAnimationEnd() {
17989        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17990    }
17991
17992    /**
17993     * Invoked if there is a Transform that involves alpha. Subclass that can
17994     * draw themselves with the specified alpha should return true, and then
17995     * respect that alpha when their onDraw() is called. If this returns false
17996     * then the view may be redirected to draw into an offscreen buffer to
17997     * fulfill the request, which will look fine, but may be slower than if the
17998     * subclass handles it internally. The default implementation returns false.
17999     *
18000     * @param alpha The alpha (0..255) to apply to the view's drawing
18001     * @return true if the view can draw with the specified alpha.
18002     */
18003    protected boolean onSetAlpha(int alpha) {
18004        return false;
18005    }
18006
18007    /**
18008     * This is used by the RootView to perform an optimization when
18009     * the view hierarchy contains one or several SurfaceView.
18010     * SurfaceView is always considered transparent, but its children are not,
18011     * therefore all View objects remove themselves from the global transparent
18012     * region (passed as a parameter to this function).
18013     *
18014     * @param region The transparent region for this ViewAncestor (window).
18015     *
18016     * @return Returns true if the effective visibility of the view at this
18017     * point is opaque, regardless of the transparent region; returns false
18018     * if it is possible for underlying windows to be seen behind the view.
18019     *
18020     * {@hide}
18021     */
18022    public boolean gatherTransparentRegion(Region region) {
18023        final AttachInfo attachInfo = mAttachInfo;
18024        if (region != null && attachInfo != null) {
18025            final int pflags = mPrivateFlags;
18026            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18027                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18028                // remove it from the transparent region.
18029                final int[] location = attachInfo.mTransparentLocation;
18030                getLocationInWindow(location);
18031                region.op(location[0], location[1], location[0] + mRight - mLeft,
18032                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18033            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18034                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18035                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18036                // exists, so we remove the background drawable's non-transparent
18037                // parts from this transparent region.
18038                applyDrawableToTransparentRegion(mBackground, region);
18039            }
18040        }
18041        return true;
18042    }
18043
18044    /**
18045     * Play a sound effect for this view.
18046     *
18047     * <p>The framework will play sound effects for some built in actions, such as
18048     * clicking, but you may wish to play these effects in your widget,
18049     * for instance, for internal navigation.
18050     *
18051     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18052     * {@link #isSoundEffectsEnabled()} is true.
18053     *
18054     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18055     */
18056    public void playSoundEffect(int soundConstant) {
18057        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18058            return;
18059        }
18060        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18061    }
18062
18063    /**
18064     * BZZZTT!!1!
18065     *
18066     * <p>Provide haptic feedback to the user for this view.
18067     *
18068     * <p>The framework will provide haptic feedback for some built in actions,
18069     * such as long presses, but you may wish to provide feedback for your
18070     * own widget.
18071     *
18072     * <p>The feedback will only be performed if
18073     * {@link #isHapticFeedbackEnabled()} is true.
18074     *
18075     * @param feedbackConstant One of the constants defined in
18076     * {@link HapticFeedbackConstants}
18077     */
18078    public boolean performHapticFeedback(int feedbackConstant) {
18079        return performHapticFeedback(feedbackConstant, 0);
18080    }
18081
18082    /**
18083     * BZZZTT!!1!
18084     *
18085     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18086     *
18087     * @param feedbackConstant One of the constants defined in
18088     * {@link HapticFeedbackConstants}
18089     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18090     */
18091    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18092        if (mAttachInfo == null) {
18093            return false;
18094        }
18095        //noinspection SimplifiableIfStatement
18096        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18097                && !isHapticFeedbackEnabled()) {
18098            return false;
18099        }
18100        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18101                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18102    }
18103
18104    /**
18105     * Request that the visibility of the status bar or other screen/window
18106     * decorations be changed.
18107     *
18108     * <p>This method is used to put the over device UI into temporary modes
18109     * where the user's attention is focused more on the application content,
18110     * by dimming or hiding surrounding system affordances.  This is typically
18111     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18112     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18113     * to be placed behind the action bar (and with these flags other system
18114     * affordances) so that smooth transitions between hiding and showing them
18115     * can be done.
18116     *
18117     * <p>Two representative examples of the use of system UI visibility is
18118     * implementing a content browsing application (like a magazine reader)
18119     * and a video playing application.
18120     *
18121     * <p>The first code shows a typical implementation of a View in a content
18122     * browsing application.  In this implementation, the application goes
18123     * into a content-oriented mode by hiding the status bar and action bar,
18124     * and putting the navigation elements into lights out mode.  The user can
18125     * then interact with content while in this mode.  Such an application should
18126     * provide an easy way for the user to toggle out of the mode (such as to
18127     * check information in the status bar or access notifications).  In the
18128     * implementation here, this is done simply by tapping on the content.
18129     *
18130     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18131     *      content}
18132     *
18133     * <p>This second code sample shows a typical implementation of a View
18134     * in a video playing application.  In this situation, while the video is
18135     * playing the application would like to go into a complete full-screen mode,
18136     * to use as much of the display as possible for the video.  When in this state
18137     * the user can not interact with the application; the system intercepts
18138     * touching on the screen to pop the UI out of full screen mode.  See
18139     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18140     *
18141     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18142     *      content}
18143     *
18144     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18145     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18146     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18147     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18148     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18149     */
18150    public void setSystemUiVisibility(int visibility) {
18151        if (visibility != mSystemUiVisibility) {
18152            mSystemUiVisibility = visibility;
18153            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18154                mParent.recomputeViewAttributes(this);
18155            }
18156        }
18157    }
18158
18159    /**
18160     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18161     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18162     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18163     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18164     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18165     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18166     */
18167    public int getSystemUiVisibility() {
18168        return mSystemUiVisibility;
18169    }
18170
18171    /**
18172     * Returns the current system UI visibility that is currently set for
18173     * the entire window.  This is the combination of the
18174     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18175     * views in the window.
18176     */
18177    public int getWindowSystemUiVisibility() {
18178        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18179    }
18180
18181    /**
18182     * Override to find out when the window's requested system UI visibility
18183     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18184     * This is different from the callbacks received through
18185     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18186     * in that this is only telling you about the local request of the window,
18187     * not the actual values applied by the system.
18188     */
18189    public void onWindowSystemUiVisibilityChanged(int visible) {
18190    }
18191
18192    /**
18193     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18194     * the view hierarchy.
18195     */
18196    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18197        onWindowSystemUiVisibilityChanged(visible);
18198    }
18199
18200    /**
18201     * Set a listener to receive callbacks when the visibility of the system bar changes.
18202     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18203     */
18204    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18205        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18206        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18207            mParent.recomputeViewAttributes(this);
18208        }
18209    }
18210
18211    /**
18212     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18213     * the view hierarchy.
18214     */
18215    public void dispatchSystemUiVisibilityChanged(int visibility) {
18216        ListenerInfo li = mListenerInfo;
18217        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18218            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18219                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18220        }
18221    }
18222
18223    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18224        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18225        if (val != mSystemUiVisibility) {
18226            setSystemUiVisibility(val);
18227            return true;
18228        }
18229        return false;
18230    }
18231
18232    /** @hide */
18233    public void setDisabledSystemUiVisibility(int flags) {
18234        if (mAttachInfo != null) {
18235            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18236                mAttachInfo.mDisabledSystemUiVisibility = flags;
18237                if (mParent != null) {
18238                    mParent.recomputeViewAttributes(this);
18239                }
18240            }
18241        }
18242    }
18243
18244    /**
18245     * Creates an image that the system displays during the drag and drop
18246     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18247     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18248     * appearance as the given View. The default also positions the center of the drag shadow
18249     * directly under the touch point. If no View is provided (the constructor with no parameters
18250     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18251     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
18252     * default is an invisible drag shadow.
18253     * <p>
18254     * You are not required to use the View you provide to the constructor as the basis of the
18255     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18256     * anything you want as the drag shadow.
18257     * </p>
18258     * <p>
18259     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18260     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18261     *  size and position of the drag shadow. It uses this data to construct a
18262     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18263     *  so that your application can draw the shadow image in the Canvas.
18264     * </p>
18265     *
18266     * <div class="special reference">
18267     * <h3>Developer Guides</h3>
18268     * <p>For a guide to implementing drag and drop features, read the
18269     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18270     * </div>
18271     */
18272    public static class DragShadowBuilder {
18273        private final WeakReference<View> mView;
18274
18275        /**
18276         * Constructs a shadow image builder based on a View. By default, the resulting drag
18277         * shadow will have the same appearance and dimensions as the View, with the touch point
18278         * over the center of the View.
18279         * @param view A View. Any View in scope can be used.
18280         */
18281        public DragShadowBuilder(View view) {
18282            mView = new WeakReference<View>(view);
18283        }
18284
18285        /**
18286         * Construct a shadow builder object with no associated View.  This
18287         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18288         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18289         * to supply the drag shadow's dimensions and appearance without
18290         * reference to any View object. If they are not overridden, then the result is an
18291         * invisible drag shadow.
18292         */
18293        public DragShadowBuilder() {
18294            mView = new WeakReference<View>(null);
18295        }
18296
18297        /**
18298         * Returns the View object that had been passed to the
18299         * {@link #View.DragShadowBuilder(View)}
18300         * constructor.  If that View parameter was {@code null} or if the
18301         * {@link #View.DragShadowBuilder()}
18302         * constructor was used to instantiate the builder object, this method will return
18303         * null.
18304         *
18305         * @return The View object associate with this builder object.
18306         */
18307        @SuppressWarnings({"JavadocReference"})
18308        final public View getView() {
18309            return mView.get();
18310        }
18311
18312        /**
18313         * Provides the metrics for the shadow image. These include the dimensions of
18314         * the shadow image, and the point within that shadow that should
18315         * be centered under the touch location while dragging.
18316         * <p>
18317         * The default implementation sets the dimensions of the shadow to be the
18318         * same as the dimensions of the View itself and centers the shadow under
18319         * the touch point.
18320         * </p>
18321         *
18322         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18323         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18324         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18325         * image.
18326         *
18327         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18328         * shadow image that should be underneath the touch point during the drag and drop
18329         * operation. Your application must set {@link android.graphics.Point#x} to the
18330         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18331         */
18332        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18333            final View view = mView.get();
18334            if (view != null) {
18335                shadowSize.set(view.getWidth(), view.getHeight());
18336                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18337            } else {
18338                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18339            }
18340        }
18341
18342        /**
18343         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18344         * based on the dimensions it received from the
18345         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18346         *
18347         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18348         */
18349        public void onDrawShadow(Canvas canvas) {
18350            final View view = mView.get();
18351            if (view != null) {
18352                view.draw(canvas);
18353            } else {
18354                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18355            }
18356        }
18357    }
18358
18359    /**
18360     * Starts a drag and drop operation. When your application calls this method, it passes a
18361     * {@link android.view.View.DragShadowBuilder} object to the system. The
18362     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18363     * to get metrics for the drag shadow, and then calls the object's
18364     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18365     * <p>
18366     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18367     *  drag events to all the View objects in your application that are currently visible. It does
18368     *  this either by calling the View object's drag listener (an implementation of
18369     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18370     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18371     *  Both are passed a {@link android.view.DragEvent} object that has a
18372     *  {@link android.view.DragEvent#getAction()} value of
18373     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18374     * </p>
18375     * <p>
18376     * Your application can invoke startDrag() on any attached View object. The View object does not
18377     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18378     * be related to the View the user selected for dragging.
18379     * </p>
18380     * @param data A {@link android.content.ClipData} object pointing to the data to be
18381     * transferred by the drag and drop operation.
18382     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18383     * drag shadow.
18384     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18385     * drop operation. This Object is put into every DragEvent object sent by the system during the
18386     * current drag.
18387     * <p>
18388     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18389     * to the target Views. For example, it can contain flags that differentiate between a
18390     * a copy operation and a move operation.
18391     * </p>
18392     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18393     * so the parameter should be set to 0.
18394     * @return {@code true} if the method completes successfully, or
18395     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18396     * do a drag, and so no drag operation is in progress.
18397     */
18398    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18399            Object myLocalState, int flags) {
18400        if (ViewDebug.DEBUG_DRAG) {
18401            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18402        }
18403        boolean okay = false;
18404
18405        Point shadowSize = new Point();
18406        Point shadowTouchPoint = new Point();
18407        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18408
18409        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18410                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18411            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18412        }
18413
18414        if (ViewDebug.DEBUG_DRAG) {
18415            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18416                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18417        }
18418        Surface surface = new Surface();
18419        try {
18420            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18421                    flags, shadowSize.x, shadowSize.y, surface);
18422            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18423                    + " surface=" + surface);
18424            if (token != null) {
18425                Canvas canvas = surface.lockCanvas(null);
18426                try {
18427                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18428                    shadowBuilder.onDrawShadow(canvas);
18429                } finally {
18430                    surface.unlockCanvasAndPost(canvas);
18431                }
18432
18433                final ViewRootImpl root = getViewRootImpl();
18434
18435                // Cache the local state object for delivery with DragEvents
18436                root.setLocalDragState(myLocalState);
18437
18438                // repurpose 'shadowSize' for the last touch point
18439                root.getLastTouchPoint(shadowSize);
18440
18441                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18442                        shadowSize.x, shadowSize.y,
18443                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18444                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18445
18446                // Off and running!  Release our local surface instance; the drag
18447                // shadow surface is now managed by the system process.
18448                surface.release();
18449            }
18450        } catch (Exception e) {
18451            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18452            surface.destroy();
18453        }
18454
18455        return okay;
18456    }
18457
18458    /**
18459     * Handles drag events sent by the system following a call to
18460     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18461     *<p>
18462     * When the system calls this method, it passes a
18463     * {@link android.view.DragEvent} object. A call to
18464     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18465     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18466     * operation.
18467     * @param event The {@link android.view.DragEvent} sent by the system.
18468     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18469     * in DragEvent, indicating the type of drag event represented by this object.
18470     * @return {@code true} if the method was successful, otherwise {@code false}.
18471     * <p>
18472     *  The method should return {@code true} in response to an action type of
18473     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18474     *  operation.
18475     * </p>
18476     * <p>
18477     *  The method should also return {@code true} in response to an action type of
18478     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18479     *  {@code false} if it didn't.
18480     * </p>
18481     */
18482    public boolean onDragEvent(DragEvent event) {
18483        return false;
18484    }
18485
18486    /**
18487     * Detects if this View is enabled and has a drag event listener.
18488     * If both are true, then it calls the drag event listener with the
18489     * {@link android.view.DragEvent} it received. If the drag event listener returns
18490     * {@code true}, then dispatchDragEvent() returns {@code true}.
18491     * <p>
18492     * For all other cases, the method calls the
18493     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18494     * method and returns its result.
18495     * </p>
18496     * <p>
18497     * This ensures that a drag event is always consumed, even if the View does not have a drag
18498     * event listener. However, if the View has a listener and the listener returns true, then
18499     * onDragEvent() is not called.
18500     * </p>
18501     */
18502    public boolean dispatchDragEvent(DragEvent event) {
18503        ListenerInfo li = mListenerInfo;
18504        //noinspection SimplifiableIfStatement
18505        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18506                && li.mOnDragListener.onDrag(this, event)) {
18507            return true;
18508        }
18509        return onDragEvent(event);
18510    }
18511
18512    boolean canAcceptDrag() {
18513        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18514    }
18515
18516    /**
18517     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18518     * it is ever exposed at all.
18519     * @hide
18520     */
18521    public void onCloseSystemDialogs(String reason) {
18522    }
18523
18524    /**
18525     * Given a Drawable whose bounds have been set to draw into this view,
18526     * update a Region being computed for
18527     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18528     * that any non-transparent parts of the Drawable are removed from the
18529     * given transparent region.
18530     *
18531     * @param dr The Drawable whose transparency is to be applied to the region.
18532     * @param region A Region holding the current transparency information,
18533     * where any parts of the region that are set are considered to be
18534     * transparent.  On return, this region will be modified to have the
18535     * transparency information reduced by the corresponding parts of the
18536     * Drawable that are not transparent.
18537     * {@hide}
18538     */
18539    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18540        if (DBG) {
18541            Log.i("View", "Getting transparent region for: " + this);
18542        }
18543        final Region r = dr.getTransparentRegion();
18544        final Rect db = dr.getBounds();
18545        final AttachInfo attachInfo = mAttachInfo;
18546        if (r != null && attachInfo != null) {
18547            final int w = getRight()-getLeft();
18548            final int h = getBottom()-getTop();
18549            if (db.left > 0) {
18550                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18551                r.op(0, 0, db.left, h, Region.Op.UNION);
18552            }
18553            if (db.right < w) {
18554                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18555                r.op(db.right, 0, w, h, Region.Op.UNION);
18556            }
18557            if (db.top > 0) {
18558                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18559                r.op(0, 0, w, db.top, Region.Op.UNION);
18560            }
18561            if (db.bottom < h) {
18562                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18563                r.op(0, db.bottom, w, h, Region.Op.UNION);
18564            }
18565            final int[] location = attachInfo.mTransparentLocation;
18566            getLocationInWindow(location);
18567            r.translate(location[0], location[1]);
18568            region.op(r, Region.Op.INTERSECT);
18569        } else {
18570            region.op(db, Region.Op.DIFFERENCE);
18571        }
18572    }
18573
18574    private void checkForLongClick(int delayOffset) {
18575        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18576            mHasPerformedLongPress = false;
18577
18578            if (mPendingCheckForLongPress == null) {
18579                mPendingCheckForLongPress = new CheckForLongPress();
18580            }
18581            mPendingCheckForLongPress.rememberWindowAttachCount();
18582            postDelayed(mPendingCheckForLongPress,
18583                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18584        }
18585    }
18586
18587    /**
18588     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18589     * LayoutInflater} class, which provides a full range of options for view inflation.
18590     *
18591     * @param context The Context object for your activity or application.
18592     * @param resource The resource ID to inflate
18593     * @param root A view group that will be the parent.  Used to properly inflate the
18594     * layout_* parameters.
18595     * @see LayoutInflater
18596     */
18597    public static View inflate(Context context, int resource, ViewGroup root) {
18598        LayoutInflater factory = LayoutInflater.from(context);
18599        return factory.inflate(resource, root);
18600    }
18601
18602    /**
18603     * Scroll the view with standard behavior for scrolling beyond the normal
18604     * content boundaries. Views that call this method should override
18605     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18606     * results of an over-scroll operation.
18607     *
18608     * Views can use this method to handle any touch or fling-based scrolling.
18609     *
18610     * @param deltaX Change in X in pixels
18611     * @param deltaY Change in Y in pixels
18612     * @param scrollX Current X scroll value in pixels before applying deltaX
18613     * @param scrollY Current Y scroll value in pixels before applying deltaY
18614     * @param scrollRangeX Maximum content scroll range along the X axis
18615     * @param scrollRangeY Maximum content scroll range along the Y axis
18616     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18617     *          along the X axis.
18618     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18619     *          along the Y axis.
18620     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18621     * @return true if scrolling was clamped to an over-scroll boundary along either
18622     *          axis, false otherwise.
18623     */
18624    @SuppressWarnings({"UnusedParameters"})
18625    protected boolean overScrollBy(int deltaX, int deltaY,
18626            int scrollX, int scrollY,
18627            int scrollRangeX, int scrollRangeY,
18628            int maxOverScrollX, int maxOverScrollY,
18629            boolean isTouchEvent) {
18630        final int overScrollMode = mOverScrollMode;
18631        final boolean canScrollHorizontal =
18632                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18633        final boolean canScrollVertical =
18634                computeVerticalScrollRange() > computeVerticalScrollExtent();
18635        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18636                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18637        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18638                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18639
18640        int newScrollX = scrollX + deltaX;
18641        if (!overScrollHorizontal) {
18642            maxOverScrollX = 0;
18643        }
18644
18645        int newScrollY = scrollY + deltaY;
18646        if (!overScrollVertical) {
18647            maxOverScrollY = 0;
18648        }
18649
18650        // Clamp values if at the limits and record
18651        final int left = -maxOverScrollX;
18652        final int right = maxOverScrollX + scrollRangeX;
18653        final int top = -maxOverScrollY;
18654        final int bottom = maxOverScrollY + scrollRangeY;
18655
18656        boolean clampedX = false;
18657        if (newScrollX > right) {
18658            newScrollX = right;
18659            clampedX = true;
18660        } else if (newScrollX < left) {
18661            newScrollX = left;
18662            clampedX = true;
18663        }
18664
18665        boolean clampedY = false;
18666        if (newScrollY > bottom) {
18667            newScrollY = bottom;
18668            clampedY = true;
18669        } else if (newScrollY < top) {
18670            newScrollY = top;
18671            clampedY = true;
18672        }
18673
18674        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18675
18676        return clampedX || clampedY;
18677    }
18678
18679    /**
18680     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18681     * respond to the results of an over-scroll operation.
18682     *
18683     * @param scrollX New X scroll value in pixels
18684     * @param scrollY New Y scroll value in pixels
18685     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18686     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18687     */
18688    protected void onOverScrolled(int scrollX, int scrollY,
18689            boolean clampedX, boolean clampedY) {
18690        // Intentionally empty.
18691    }
18692
18693    /**
18694     * Returns the over-scroll mode for this view. The result will be
18695     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18696     * (allow over-scrolling only if the view content is larger than the container),
18697     * or {@link #OVER_SCROLL_NEVER}.
18698     *
18699     * @return This view's over-scroll mode.
18700     */
18701    public int getOverScrollMode() {
18702        return mOverScrollMode;
18703    }
18704
18705    /**
18706     * Set the over-scroll mode for this view. Valid over-scroll modes are
18707     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18708     * (allow over-scrolling only if the view content is larger than the container),
18709     * or {@link #OVER_SCROLL_NEVER}.
18710     *
18711     * Setting the over-scroll mode of a view will have an effect only if the
18712     * view is capable of scrolling.
18713     *
18714     * @param overScrollMode The new over-scroll mode for this view.
18715     */
18716    public void setOverScrollMode(int overScrollMode) {
18717        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18718                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18719                overScrollMode != OVER_SCROLL_NEVER) {
18720            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18721        }
18722        mOverScrollMode = overScrollMode;
18723    }
18724
18725    /**
18726     * Enable or disable nested scrolling for this view.
18727     *
18728     * <p>If this property is set to true the view will be permitted to initiate nested
18729     * scrolling operations with a compatible parent view in the current hierarchy. If this
18730     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18731     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18732     * the nested scroll.</p>
18733     *
18734     * @param enabled true to enable nested scrolling, false to disable
18735     *
18736     * @see #isNestedScrollingEnabled()
18737     */
18738    public void setNestedScrollingEnabled(boolean enabled) {
18739        if (enabled) {
18740            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18741        } else {
18742            stopNestedScroll();
18743            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18744        }
18745    }
18746
18747    /**
18748     * Returns true if nested scrolling is enabled for this view.
18749     *
18750     * <p>If nested scrolling is enabled and this View class implementation supports it,
18751     * this view will act as a nested scrolling child view when applicable, forwarding data
18752     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18753     * parent.</p>
18754     *
18755     * @return true if nested scrolling is enabled
18756     *
18757     * @see #setNestedScrollingEnabled(boolean)
18758     */
18759    public boolean isNestedScrollingEnabled() {
18760        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18761                PFLAG3_NESTED_SCROLLING_ENABLED;
18762    }
18763
18764    /**
18765     * Begin a nestable scroll operation along the given axes.
18766     *
18767     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18768     *
18769     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18770     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18771     * In the case of touch scrolling the nested scroll will be terminated automatically in
18772     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18773     * In the event of programmatic scrolling the caller must explicitly call
18774     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18775     *
18776     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18777     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18778     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18779     *
18780     * <p>At each incremental step of the scroll the caller should invoke
18781     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18782     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18783     * parent at least partially consumed the scroll and the caller should adjust the amount it
18784     * scrolls by.</p>
18785     *
18786     * <p>After applying the remainder of the scroll delta the caller should invoke
18787     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18788     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18789     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18790     * </p>
18791     *
18792     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18793     *             {@link #SCROLL_AXIS_VERTICAL}.
18794     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18795     *         the current gesture.
18796     *
18797     * @see #stopNestedScroll()
18798     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18799     * @see #dispatchNestedScroll(int, int, int, int, int[])
18800     */
18801    public boolean startNestedScroll(int axes) {
18802        if (hasNestedScrollingParent()) {
18803            // Already in progress
18804            return true;
18805        }
18806        if (isNestedScrollingEnabled()) {
18807            ViewParent p = getParent();
18808            View child = this;
18809            while (p != null) {
18810                try {
18811                    if (p.onStartNestedScroll(child, this, axes)) {
18812                        mNestedScrollingParent = p;
18813                        p.onNestedScrollAccepted(child, this, axes);
18814                        return true;
18815                    }
18816                } catch (AbstractMethodError e) {
18817                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18818                            "method onStartNestedScroll", e);
18819                    // Allow the search upward to continue
18820                }
18821                if (p instanceof View) {
18822                    child = (View) p;
18823                }
18824                p = p.getParent();
18825            }
18826        }
18827        return false;
18828    }
18829
18830    /**
18831     * Stop a nested scroll in progress.
18832     *
18833     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18834     *
18835     * @see #startNestedScroll(int)
18836     */
18837    public void stopNestedScroll() {
18838        if (mNestedScrollingParent != null) {
18839            mNestedScrollingParent.onStopNestedScroll(this);
18840            mNestedScrollingParent = null;
18841        }
18842    }
18843
18844    /**
18845     * Returns true if this view has a nested scrolling parent.
18846     *
18847     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18848     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18849     *
18850     * @return whether this view has a nested scrolling parent
18851     */
18852    public boolean hasNestedScrollingParent() {
18853        return mNestedScrollingParent != null;
18854    }
18855
18856    /**
18857     * Dispatch one step of a nested scroll in progress.
18858     *
18859     * <p>Implementations of views that support nested scrolling should call this to report
18860     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18861     * is not currently in progress or nested scrolling is not
18862     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18863     *
18864     * <p>Compatible View implementations should also call
18865     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18866     * consuming a component of the scroll event themselves.</p>
18867     *
18868     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18869     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18870     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18871     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18872     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18873     *                       in local view coordinates of this view from before this operation
18874     *                       to after it completes. View implementations may use this to adjust
18875     *                       expected input coordinate tracking.
18876     * @return true if the event was dispatched, false if it could not be dispatched.
18877     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18878     */
18879    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18880            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18881        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18882            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18883                int startX = 0;
18884                int startY = 0;
18885                if (offsetInWindow != null) {
18886                    getLocationInWindow(offsetInWindow);
18887                    startX = offsetInWindow[0];
18888                    startY = offsetInWindow[1];
18889                }
18890
18891                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18892                        dxUnconsumed, dyUnconsumed);
18893
18894                if (offsetInWindow != null) {
18895                    getLocationInWindow(offsetInWindow);
18896                    offsetInWindow[0] -= startX;
18897                    offsetInWindow[1] -= startY;
18898                }
18899                return true;
18900            } else if (offsetInWindow != null) {
18901                // No motion, no dispatch. Keep offsetInWindow up to date.
18902                offsetInWindow[0] = 0;
18903                offsetInWindow[1] = 0;
18904            }
18905        }
18906        return false;
18907    }
18908
18909    /**
18910     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18911     *
18912     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18913     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18914     * scrolling operation to consume some or all of the scroll operation before the child view
18915     * consumes it.</p>
18916     *
18917     * @param dx Horizontal scroll distance in pixels
18918     * @param dy Vertical scroll distance in pixels
18919     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18920     *                 and consumed[1] the consumed dy.
18921     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18922     *                       in local view coordinates of this view from before this operation
18923     *                       to after it completes. View implementations may use this to adjust
18924     *                       expected input coordinate tracking.
18925     * @return true if the parent consumed some or all of the scroll delta
18926     * @see #dispatchNestedScroll(int, int, int, int, int[])
18927     */
18928    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18929        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18930            if (dx != 0 || dy != 0) {
18931                int startX = 0;
18932                int startY = 0;
18933                if (offsetInWindow != null) {
18934                    getLocationInWindow(offsetInWindow);
18935                    startX = offsetInWindow[0];
18936                    startY = offsetInWindow[1];
18937                }
18938
18939                if (consumed == null) {
18940                    if (mTempNestedScrollConsumed == null) {
18941                        mTempNestedScrollConsumed = new int[2];
18942                    }
18943                    consumed = mTempNestedScrollConsumed;
18944                }
18945                consumed[0] = 0;
18946                consumed[1] = 0;
18947                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18948
18949                if (offsetInWindow != null) {
18950                    getLocationInWindow(offsetInWindow);
18951                    offsetInWindow[0] -= startX;
18952                    offsetInWindow[1] -= startY;
18953                }
18954                return consumed[0] != 0 || consumed[1] != 0;
18955            } else if (offsetInWindow != null) {
18956                offsetInWindow[0] = 0;
18957                offsetInWindow[1] = 0;
18958            }
18959        }
18960        return false;
18961    }
18962
18963    /**
18964     * Dispatch a fling to a nested scrolling parent.
18965     *
18966     * <p>This method should be used to indicate that a nested scrolling child has detected
18967     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18968     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18969     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18970     * along a scrollable axis.</p>
18971     *
18972     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18973     * its own content, it can use this method to delegate the fling to its nested scrolling
18974     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18975     *
18976     * @param velocityX Horizontal fling velocity in pixels per second
18977     * @param velocityY Vertical fling velocity in pixels per second
18978     * @param consumed true if the child consumed the fling, false otherwise
18979     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18980     */
18981    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18982        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18983            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18984        }
18985        return false;
18986    }
18987
18988    /**
18989     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18990     *
18991     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18992     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18993     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18994     * before the child view consumes it. If this method returns <code>true</code>, a nested
18995     * parent view consumed the fling and this view should not scroll as a result.</p>
18996     *
18997     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18998     * the fling at a time. If a parent view consumed the fling this method will return false.
18999     * Custom view implementations should account for this in two ways:</p>
19000     *
19001     * <ul>
19002     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19003     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19004     *     position regardless.</li>
19005     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19006     *     even to settle back to a valid idle position.</li>
19007     * </ul>
19008     *
19009     * <p>Views should also not offer fling velocities to nested parent views along an axis
19010     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19011     * should not offer a horizontal fling velocity to its parents since scrolling along that
19012     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19013     *
19014     * @param velocityX Horizontal fling velocity in pixels per second
19015     * @param velocityY Vertical fling velocity in pixels per second
19016     * @return true if a nested scrolling parent consumed the fling
19017     */
19018    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19019        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19020            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19021        }
19022        return false;
19023    }
19024
19025    /**
19026     * Gets a scale factor that determines the distance the view should scroll
19027     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19028     * @return The vertical scroll scale factor.
19029     * @hide
19030     */
19031    protected float getVerticalScrollFactor() {
19032        if (mVerticalScrollFactor == 0) {
19033            TypedValue outValue = new TypedValue();
19034            if (!mContext.getTheme().resolveAttribute(
19035                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19036                throw new IllegalStateException(
19037                        "Expected theme to define listPreferredItemHeight.");
19038            }
19039            mVerticalScrollFactor = outValue.getDimension(
19040                    mContext.getResources().getDisplayMetrics());
19041        }
19042        return mVerticalScrollFactor;
19043    }
19044
19045    /**
19046     * Gets a scale factor that determines the distance the view should scroll
19047     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19048     * @return The horizontal scroll scale factor.
19049     * @hide
19050     */
19051    protected float getHorizontalScrollFactor() {
19052        // TODO: Should use something else.
19053        return getVerticalScrollFactor();
19054    }
19055
19056    /**
19057     * Return the value specifying the text direction or policy that was set with
19058     * {@link #setTextDirection(int)}.
19059     *
19060     * @return the defined text direction. It can be one of:
19061     *
19062     * {@link #TEXT_DIRECTION_INHERIT},
19063     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19064     * {@link #TEXT_DIRECTION_ANY_RTL},
19065     * {@link #TEXT_DIRECTION_LTR},
19066     * {@link #TEXT_DIRECTION_RTL},
19067     * {@link #TEXT_DIRECTION_LOCALE}
19068     *
19069     * @attr ref android.R.styleable#View_textDirection
19070     *
19071     * @hide
19072     */
19073    @ViewDebug.ExportedProperty(category = "text", mapping = {
19074            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19075            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19076            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19077            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19078            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19079            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19080    })
19081    public int getRawTextDirection() {
19082        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19083    }
19084
19085    /**
19086     * Set the text direction.
19087     *
19088     * @param textDirection the direction to set. Should be one of:
19089     *
19090     * {@link #TEXT_DIRECTION_INHERIT},
19091     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19092     * {@link #TEXT_DIRECTION_ANY_RTL},
19093     * {@link #TEXT_DIRECTION_LTR},
19094     * {@link #TEXT_DIRECTION_RTL},
19095     * {@link #TEXT_DIRECTION_LOCALE}
19096     *
19097     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19098     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19099     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19100     *
19101     * @attr ref android.R.styleable#View_textDirection
19102     */
19103    public void setTextDirection(int textDirection) {
19104        if (getRawTextDirection() != textDirection) {
19105            // Reset the current text direction and the resolved one
19106            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19107            resetResolvedTextDirection();
19108            // Set the new text direction
19109            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19110            // Do resolution
19111            resolveTextDirection();
19112            // Notify change
19113            onRtlPropertiesChanged(getLayoutDirection());
19114            // Refresh
19115            requestLayout();
19116            invalidate(true);
19117        }
19118    }
19119
19120    /**
19121     * Return the resolved text direction.
19122     *
19123     * @return the resolved text direction. Returns one of:
19124     *
19125     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19126     * {@link #TEXT_DIRECTION_ANY_RTL},
19127     * {@link #TEXT_DIRECTION_LTR},
19128     * {@link #TEXT_DIRECTION_RTL},
19129     * {@link #TEXT_DIRECTION_LOCALE}
19130     *
19131     * @attr ref android.R.styleable#View_textDirection
19132     */
19133    @ViewDebug.ExportedProperty(category = "text", mapping = {
19134            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19135            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19136            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19137            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19138            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19139            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19140    })
19141    public int getTextDirection() {
19142        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19143    }
19144
19145    /**
19146     * Resolve the text direction.
19147     *
19148     * @return true if resolution has been done, false otherwise.
19149     *
19150     * @hide
19151     */
19152    public boolean resolveTextDirection() {
19153        // Reset any previous text direction resolution
19154        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19155
19156        if (hasRtlSupport()) {
19157            // Set resolved text direction flag depending on text direction flag
19158            final int textDirection = getRawTextDirection();
19159            switch(textDirection) {
19160                case TEXT_DIRECTION_INHERIT:
19161                    if (!canResolveTextDirection()) {
19162                        // We cannot do the resolution if there is no parent, so use the default one
19163                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19164                        // Resolution will need to happen again later
19165                        return false;
19166                    }
19167
19168                    // Parent has not yet resolved, so we still return the default
19169                    try {
19170                        if (!mParent.isTextDirectionResolved()) {
19171                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19172                            // Resolution will need to happen again later
19173                            return false;
19174                        }
19175                    } catch (AbstractMethodError e) {
19176                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19177                                " does not fully implement ViewParent", e);
19178                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19179                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19180                        return true;
19181                    }
19182
19183                    // Set current resolved direction to the same value as the parent's one
19184                    int parentResolvedDirection;
19185                    try {
19186                        parentResolvedDirection = mParent.getTextDirection();
19187                    } catch (AbstractMethodError e) {
19188                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19189                                " does not fully implement ViewParent", e);
19190                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19191                    }
19192                    switch (parentResolvedDirection) {
19193                        case TEXT_DIRECTION_FIRST_STRONG:
19194                        case TEXT_DIRECTION_ANY_RTL:
19195                        case TEXT_DIRECTION_LTR:
19196                        case TEXT_DIRECTION_RTL:
19197                        case TEXT_DIRECTION_LOCALE:
19198                            mPrivateFlags2 |=
19199                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19200                            break;
19201                        default:
19202                            // Default resolved direction is "first strong" heuristic
19203                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19204                    }
19205                    break;
19206                case TEXT_DIRECTION_FIRST_STRONG:
19207                case TEXT_DIRECTION_ANY_RTL:
19208                case TEXT_DIRECTION_LTR:
19209                case TEXT_DIRECTION_RTL:
19210                case TEXT_DIRECTION_LOCALE:
19211                    // Resolved direction is the same as text direction
19212                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19213                    break;
19214                default:
19215                    // Default resolved direction is "first strong" heuristic
19216                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19217            }
19218        } else {
19219            // Default resolved direction is "first strong" heuristic
19220            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19221        }
19222
19223        // Set to resolved
19224        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19225        return true;
19226    }
19227
19228    /**
19229     * Check if text direction resolution can be done.
19230     *
19231     * @return true if text direction resolution can be done otherwise return false.
19232     */
19233    public boolean canResolveTextDirection() {
19234        switch (getRawTextDirection()) {
19235            case TEXT_DIRECTION_INHERIT:
19236                if (mParent != null) {
19237                    try {
19238                        return mParent.canResolveTextDirection();
19239                    } catch (AbstractMethodError e) {
19240                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19241                                " does not fully implement ViewParent", e);
19242                    }
19243                }
19244                return false;
19245
19246            default:
19247                return true;
19248        }
19249    }
19250
19251    /**
19252     * Reset resolved text direction. Text direction will be resolved during a call to
19253     * {@link #onMeasure(int, int)}.
19254     *
19255     * @hide
19256     */
19257    public void resetResolvedTextDirection() {
19258        // Reset any previous text direction resolution
19259        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19260        // Set to default value
19261        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19262    }
19263
19264    /**
19265     * @return true if text direction is inherited.
19266     *
19267     * @hide
19268     */
19269    public boolean isTextDirectionInherited() {
19270        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19271    }
19272
19273    /**
19274     * @return true if text direction is resolved.
19275     */
19276    public boolean isTextDirectionResolved() {
19277        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19278    }
19279
19280    /**
19281     * Return the value specifying the text alignment or policy that was set with
19282     * {@link #setTextAlignment(int)}.
19283     *
19284     * @return the defined text alignment. It can be one of:
19285     *
19286     * {@link #TEXT_ALIGNMENT_INHERIT},
19287     * {@link #TEXT_ALIGNMENT_GRAVITY},
19288     * {@link #TEXT_ALIGNMENT_CENTER},
19289     * {@link #TEXT_ALIGNMENT_TEXT_START},
19290     * {@link #TEXT_ALIGNMENT_TEXT_END},
19291     * {@link #TEXT_ALIGNMENT_VIEW_START},
19292     * {@link #TEXT_ALIGNMENT_VIEW_END}
19293     *
19294     * @attr ref android.R.styleable#View_textAlignment
19295     *
19296     * @hide
19297     */
19298    @ViewDebug.ExportedProperty(category = "text", mapping = {
19299            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19300            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19301            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19302            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19303            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19304            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19305            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19306    })
19307    @TextAlignment
19308    public int getRawTextAlignment() {
19309        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19310    }
19311
19312    /**
19313     * Set the text alignment.
19314     *
19315     * @param textAlignment The text alignment to set. Should be one of
19316     *
19317     * {@link #TEXT_ALIGNMENT_INHERIT},
19318     * {@link #TEXT_ALIGNMENT_GRAVITY},
19319     * {@link #TEXT_ALIGNMENT_CENTER},
19320     * {@link #TEXT_ALIGNMENT_TEXT_START},
19321     * {@link #TEXT_ALIGNMENT_TEXT_END},
19322     * {@link #TEXT_ALIGNMENT_VIEW_START},
19323     * {@link #TEXT_ALIGNMENT_VIEW_END}
19324     *
19325     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19326     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19327     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19328     *
19329     * @attr ref android.R.styleable#View_textAlignment
19330     */
19331    public void setTextAlignment(@TextAlignment int textAlignment) {
19332        if (textAlignment != getRawTextAlignment()) {
19333            // Reset the current and resolved text alignment
19334            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19335            resetResolvedTextAlignment();
19336            // Set the new text alignment
19337            mPrivateFlags2 |=
19338                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19339            // Do resolution
19340            resolveTextAlignment();
19341            // Notify change
19342            onRtlPropertiesChanged(getLayoutDirection());
19343            // Refresh
19344            requestLayout();
19345            invalidate(true);
19346        }
19347    }
19348
19349    /**
19350     * Return the resolved text alignment.
19351     *
19352     * @return the resolved text alignment. Returns one of:
19353     *
19354     * {@link #TEXT_ALIGNMENT_GRAVITY},
19355     * {@link #TEXT_ALIGNMENT_CENTER},
19356     * {@link #TEXT_ALIGNMENT_TEXT_START},
19357     * {@link #TEXT_ALIGNMENT_TEXT_END},
19358     * {@link #TEXT_ALIGNMENT_VIEW_START},
19359     * {@link #TEXT_ALIGNMENT_VIEW_END}
19360     *
19361     * @attr ref android.R.styleable#View_textAlignment
19362     */
19363    @ViewDebug.ExportedProperty(category = "text", mapping = {
19364            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19365            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19366            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19367            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19368            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19369            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19370            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19371    })
19372    @TextAlignment
19373    public int getTextAlignment() {
19374        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19375                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19376    }
19377
19378    /**
19379     * Resolve the text alignment.
19380     *
19381     * @return true if resolution has been done, false otherwise.
19382     *
19383     * @hide
19384     */
19385    public boolean resolveTextAlignment() {
19386        // Reset any previous text alignment resolution
19387        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19388
19389        if (hasRtlSupport()) {
19390            // Set resolved text alignment flag depending on text alignment flag
19391            final int textAlignment = getRawTextAlignment();
19392            switch (textAlignment) {
19393                case TEXT_ALIGNMENT_INHERIT:
19394                    // Check if we can resolve the text alignment
19395                    if (!canResolveTextAlignment()) {
19396                        // We cannot do the resolution if there is no parent so use the default
19397                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19398                        // Resolution will need to happen again later
19399                        return false;
19400                    }
19401
19402                    // Parent has not yet resolved, so we still return the default
19403                    try {
19404                        if (!mParent.isTextAlignmentResolved()) {
19405                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19406                            // Resolution will need to happen again later
19407                            return false;
19408                        }
19409                    } catch (AbstractMethodError e) {
19410                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19411                                " does not fully implement ViewParent", e);
19412                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19413                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19414                        return true;
19415                    }
19416
19417                    int parentResolvedTextAlignment;
19418                    try {
19419                        parentResolvedTextAlignment = mParent.getTextAlignment();
19420                    } catch (AbstractMethodError e) {
19421                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19422                                " does not fully implement ViewParent", e);
19423                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19424                    }
19425                    switch (parentResolvedTextAlignment) {
19426                        case TEXT_ALIGNMENT_GRAVITY:
19427                        case TEXT_ALIGNMENT_TEXT_START:
19428                        case TEXT_ALIGNMENT_TEXT_END:
19429                        case TEXT_ALIGNMENT_CENTER:
19430                        case TEXT_ALIGNMENT_VIEW_START:
19431                        case TEXT_ALIGNMENT_VIEW_END:
19432                            // Resolved text alignment is the same as the parent resolved
19433                            // text alignment
19434                            mPrivateFlags2 |=
19435                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19436                            break;
19437                        default:
19438                            // Use default resolved text alignment
19439                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19440                    }
19441                    break;
19442                case TEXT_ALIGNMENT_GRAVITY:
19443                case TEXT_ALIGNMENT_TEXT_START:
19444                case TEXT_ALIGNMENT_TEXT_END:
19445                case TEXT_ALIGNMENT_CENTER:
19446                case TEXT_ALIGNMENT_VIEW_START:
19447                case TEXT_ALIGNMENT_VIEW_END:
19448                    // Resolved text alignment is the same as text alignment
19449                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19450                    break;
19451                default:
19452                    // Use default resolved text alignment
19453                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19454            }
19455        } else {
19456            // Use default resolved text alignment
19457            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19458        }
19459
19460        // Set the resolved
19461        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19462        return true;
19463    }
19464
19465    /**
19466     * Check if text alignment resolution can be done.
19467     *
19468     * @return true if text alignment resolution can be done otherwise return false.
19469     */
19470    public boolean canResolveTextAlignment() {
19471        switch (getRawTextAlignment()) {
19472            case TEXT_DIRECTION_INHERIT:
19473                if (mParent != null) {
19474                    try {
19475                        return mParent.canResolveTextAlignment();
19476                    } catch (AbstractMethodError e) {
19477                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19478                                " does not fully implement ViewParent", e);
19479                    }
19480                }
19481                return false;
19482
19483            default:
19484                return true;
19485        }
19486    }
19487
19488    /**
19489     * Reset resolved text alignment. Text alignment will be resolved during a call to
19490     * {@link #onMeasure(int, int)}.
19491     *
19492     * @hide
19493     */
19494    public void resetResolvedTextAlignment() {
19495        // Reset any previous text alignment resolution
19496        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19497        // Set to default
19498        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19499    }
19500
19501    /**
19502     * @return true if text alignment is inherited.
19503     *
19504     * @hide
19505     */
19506    public boolean isTextAlignmentInherited() {
19507        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19508    }
19509
19510    /**
19511     * @return true if text alignment is resolved.
19512     */
19513    public boolean isTextAlignmentResolved() {
19514        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19515    }
19516
19517    /**
19518     * Generate a value suitable for use in {@link #setId(int)}.
19519     * This value will not collide with ID values generated at build time by aapt for R.id.
19520     *
19521     * @return a generated ID value
19522     */
19523    public static int generateViewId() {
19524        for (;;) {
19525            final int result = sNextGeneratedId.get();
19526            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19527            int newValue = result + 1;
19528            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19529            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19530                return result;
19531            }
19532        }
19533    }
19534
19535    /**
19536     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19537     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19538     *                           a normal View or a ViewGroup with
19539     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19540     * @hide
19541     */
19542    public void captureTransitioningViews(List<View> transitioningViews) {
19543        if (getVisibility() == View.VISIBLE) {
19544            transitioningViews.add(this);
19545        }
19546    }
19547
19548    /**
19549     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19550     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19551     * @hide
19552     */
19553    public void findNamedViews(Map<String, View> namedElements) {
19554        if (getVisibility() == VISIBLE || mGhostView != null) {
19555            String transitionName = getTransitionName();
19556            if (transitionName != null) {
19557                namedElements.put(transitionName, this);
19558            }
19559        }
19560    }
19561
19562    //
19563    // Properties
19564    //
19565    /**
19566     * A Property wrapper around the <code>alpha</code> functionality handled by the
19567     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19568     */
19569    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19570        @Override
19571        public void setValue(View object, float value) {
19572            object.setAlpha(value);
19573        }
19574
19575        @Override
19576        public Float get(View object) {
19577            return object.getAlpha();
19578        }
19579    };
19580
19581    /**
19582     * A Property wrapper around the <code>translationX</code> functionality handled by the
19583     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19584     */
19585    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19586        @Override
19587        public void setValue(View object, float value) {
19588            object.setTranslationX(value);
19589        }
19590
19591                @Override
19592        public Float get(View object) {
19593            return object.getTranslationX();
19594        }
19595    };
19596
19597    /**
19598     * A Property wrapper around the <code>translationY</code> functionality handled by the
19599     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19600     */
19601    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19602        @Override
19603        public void setValue(View object, float value) {
19604            object.setTranslationY(value);
19605        }
19606
19607        @Override
19608        public Float get(View object) {
19609            return object.getTranslationY();
19610        }
19611    };
19612
19613    /**
19614     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19615     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19616     */
19617    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19618        @Override
19619        public void setValue(View object, float value) {
19620            object.setTranslationZ(value);
19621        }
19622
19623        @Override
19624        public Float get(View object) {
19625            return object.getTranslationZ();
19626        }
19627    };
19628
19629    /**
19630     * A Property wrapper around the <code>x</code> functionality handled by the
19631     * {@link View#setX(float)} and {@link View#getX()} methods.
19632     */
19633    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19634        @Override
19635        public void setValue(View object, float value) {
19636            object.setX(value);
19637        }
19638
19639        @Override
19640        public Float get(View object) {
19641            return object.getX();
19642        }
19643    };
19644
19645    /**
19646     * A Property wrapper around the <code>y</code> functionality handled by the
19647     * {@link View#setY(float)} and {@link View#getY()} methods.
19648     */
19649    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19650        @Override
19651        public void setValue(View object, float value) {
19652            object.setY(value);
19653        }
19654
19655        @Override
19656        public Float get(View object) {
19657            return object.getY();
19658        }
19659    };
19660
19661    /**
19662     * A Property wrapper around the <code>z</code> functionality handled by the
19663     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19664     */
19665    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19666        @Override
19667        public void setValue(View object, float value) {
19668            object.setZ(value);
19669        }
19670
19671        @Override
19672        public Float get(View object) {
19673            return object.getZ();
19674        }
19675    };
19676
19677    /**
19678     * A Property wrapper around the <code>rotation</code> functionality handled by the
19679     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19680     */
19681    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19682        @Override
19683        public void setValue(View object, float value) {
19684            object.setRotation(value);
19685        }
19686
19687        @Override
19688        public Float get(View object) {
19689            return object.getRotation();
19690        }
19691    };
19692
19693    /**
19694     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19695     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19696     */
19697    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19698        @Override
19699        public void setValue(View object, float value) {
19700            object.setRotationX(value);
19701        }
19702
19703        @Override
19704        public Float get(View object) {
19705            return object.getRotationX();
19706        }
19707    };
19708
19709    /**
19710     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19711     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19712     */
19713    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19714        @Override
19715        public void setValue(View object, float value) {
19716            object.setRotationY(value);
19717        }
19718
19719        @Override
19720        public Float get(View object) {
19721            return object.getRotationY();
19722        }
19723    };
19724
19725    /**
19726     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19727     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19728     */
19729    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19730        @Override
19731        public void setValue(View object, float value) {
19732            object.setScaleX(value);
19733        }
19734
19735        @Override
19736        public Float get(View object) {
19737            return object.getScaleX();
19738        }
19739    };
19740
19741    /**
19742     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19743     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19744     */
19745    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19746        @Override
19747        public void setValue(View object, float value) {
19748            object.setScaleY(value);
19749        }
19750
19751        @Override
19752        public Float get(View object) {
19753            return object.getScaleY();
19754        }
19755    };
19756
19757    /**
19758     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19759     * Each MeasureSpec represents a requirement for either the width or the height.
19760     * A MeasureSpec is comprised of a size and a mode. There are three possible
19761     * modes:
19762     * <dl>
19763     * <dt>UNSPECIFIED</dt>
19764     * <dd>
19765     * The parent has not imposed any constraint on the child. It can be whatever size
19766     * it wants.
19767     * </dd>
19768     *
19769     * <dt>EXACTLY</dt>
19770     * <dd>
19771     * The parent has determined an exact size for the child. The child is going to be
19772     * given those bounds regardless of how big it wants to be.
19773     * </dd>
19774     *
19775     * <dt>AT_MOST</dt>
19776     * <dd>
19777     * The child can be as large as it wants up to the specified size.
19778     * </dd>
19779     * </dl>
19780     *
19781     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19782     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19783     */
19784    public static class MeasureSpec {
19785        private static final int MODE_SHIFT = 30;
19786        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19787
19788        /**
19789         * Measure specification mode: The parent has not imposed any constraint
19790         * on the child. It can be whatever size it wants.
19791         */
19792        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19793
19794        /**
19795         * Measure specification mode: The parent has determined an exact size
19796         * for the child. The child is going to be given those bounds regardless
19797         * of how big it wants to be.
19798         */
19799        public static final int EXACTLY     = 1 << MODE_SHIFT;
19800
19801        /**
19802         * Measure specification mode: The child can be as large as it wants up
19803         * to the specified size.
19804         */
19805        public static final int AT_MOST     = 2 << MODE_SHIFT;
19806
19807        /**
19808         * Creates a measure specification based on the supplied size and mode.
19809         *
19810         * The mode must always be one of the following:
19811         * <ul>
19812         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19813         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19814         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19815         * </ul>
19816         *
19817         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19818         * implementation was such that the order of arguments did not matter
19819         * and overflow in either value could impact the resulting MeasureSpec.
19820         * {@link android.widget.RelativeLayout} was affected by this bug.
19821         * Apps targeting API levels greater than 17 will get the fixed, more strict
19822         * behavior.</p>
19823         *
19824         * @param size the size of the measure specification
19825         * @param mode the mode of the measure specification
19826         * @return the measure specification based on size and mode
19827         */
19828        public static int makeMeasureSpec(int size, int mode) {
19829            if (sUseBrokenMakeMeasureSpec) {
19830                return size + mode;
19831            } else {
19832                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19833            }
19834        }
19835
19836        /**
19837         * Extracts the mode from the supplied measure specification.
19838         *
19839         * @param measureSpec the measure specification to extract the mode from
19840         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19841         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19842         *         {@link android.view.View.MeasureSpec#EXACTLY}
19843         */
19844        public static int getMode(int measureSpec) {
19845            return (measureSpec & MODE_MASK);
19846        }
19847
19848        /**
19849         * Extracts the size from the supplied measure specification.
19850         *
19851         * @param measureSpec the measure specification to extract the size from
19852         * @return the size in pixels defined in the supplied measure specification
19853         */
19854        public static int getSize(int measureSpec) {
19855            return (measureSpec & ~MODE_MASK);
19856        }
19857
19858        static int adjust(int measureSpec, int delta) {
19859            final int mode = getMode(measureSpec);
19860            if (mode == UNSPECIFIED) {
19861                // No need to adjust size for UNSPECIFIED mode.
19862                return makeMeasureSpec(0, UNSPECIFIED);
19863            }
19864            int size = getSize(measureSpec) + delta;
19865            if (size < 0) {
19866                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19867                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19868                size = 0;
19869            }
19870            return makeMeasureSpec(size, mode);
19871        }
19872
19873        /**
19874         * Returns a String representation of the specified measure
19875         * specification.
19876         *
19877         * @param measureSpec the measure specification to convert to a String
19878         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19879         */
19880        public static String toString(int measureSpec) {
19881            int mode = getMode(measureSpec);
19882            int size = getSize(measureSpec);
19883
19884            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19885
19886            if (mode == UNSPECIFIED)
19887                sb.append("UNSPECIFIED ");
19888            else if (mode == EXACTLY)
19889                sb.append("EXACTLY ");
19890            else if (mode == AT_MOST)
19891                sb.append("AT_MOST ");
19892            else
19893                sb.append(mode).append(" ");
19894
19895            sb.append(size);
19896            return sb.toString();
19897        }
19898    }
19899
19900    private final class CheckForLongPress implements Runnable {
19901        private int mOriginalWindowAttachCount;
19902
19903        @Override
19904        public void run() {
19905            if (isPressed() && (mParent != null)
19906                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19907                if (performLongClick()) {
19908                    mHasPerformedLongPress = true;
19909                }
19910            }
19911        }
19912
19913        public void rememberWindowAttachCount() {
19914            mOriginalWindowAttachCount = mWindowAttachCount;
19915        }
19916    }
19917
19918    private final class CheckForTap implements Runnable {
19919        public float x;
19920        public float y;
19921
19922        @Override
19923        public void run() {
19924            mPrivateFlags &= ~PFLAG_PREPRESSED;
19925            setPressed(true, x, y);
19926            checkForLongClick(ViewConfiguration.getTapTimeout());
19927        }
19928    }
19929
19930    private final class PerformClick implements Runnable {
19931        @Override
19932        public void run() {
19933            performClick();
19934        }
19935    }
19936
19937    /** @hide */
19938    public void hackTurnOffWindowResizeAnim(boolean off) {
19939        mAttachInfo.mTurnOffWindowResizeAnim = off;
19940    }
19941
19942    /**
19943     * This method returns a ViewPropertyAnimator object, which can be used to animate
19944     * specific properties on this View.
19945     *
19946     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19947     */
19948    public ViewPropertyAnimator animate() {
19949        if (mAnimator == null) {
19950            mAnimator = new ViewPropertyAnimator(this);
19951        }
19952        return mAnimator;
19953    }
19954
19955    /**
19956     * Sets the name of the View to be used to identify Views in Transitions.
19957     * Names should be unique in the View hierarchy.
19958     *
19959     * @param transitionName The name of the View to uniquely identify it for Transitions.
19960     */
19961    public final void setTransitionName(String transitionName) {
19962        mTransitionName = transitionName;
19963    }
19964
19965    /**
19966     * Returns the name of the View to be used to identify Views in Transitions.
19967     * Names should be unique in the View hierarchy.
19968     *
19969     * <p>This returns null if the View has not been given a name.</p>
19970     *
19971     * @return The name used of the View to be used to identify Views in Transitions or null
19972     * if no name has been given.
19973     */
19974    @ViewDebug.ExportedProperty
19975    public String getTransitionName() {
19976        return mTransitionName;
19977    }
19978
19979    /**
19980     * Interface definition for a callback to be invoked when a hardware key event is
19981     * dispatched to this view. The callback will be invoked before the key event is
19982     * given to the view. This is only useful for hardware keyboards; a software input
19983     * method has no obligation to trigger this listener.
19984     */
19985    public interface OnKeyListener {
19986        /**
19987         * Called when a hardware key is dispatched to a view. This allows listeners to
19988         * get a chance to respond before the target view.
19989         * <p>Key presses in software keyboards will generally NOT trigger this method,
19990         * although some may elect to do so in some situations. Do not assume a
19991         * software input method has to be key-based; even if it is, it may use key presses
19992         * in a different way than you expect, so there is no way to reliably catch soft
19993         * input key presses.
19994         *
19995         * @param v The view the key has been dispatched to.
19996         * @param keyCode The code for the physical key that was pressed
19997         * @param event The KeyEvent object containing full information about
19998         *        the event.
19999         * @return True if the listener has consumed the event, false otherwise.
20000         */
20001        boolean onKey(View v, int keyCode, KeyEvent event);
20002    }
20003
20004    /**
20005     * Interface definition for a callback to be invoked when a touch event is
20006     * dispatched to this view. The callback will be invoked before the touch
20007     * event is given to the view.
20008     */
20009    public interface OnTouchListener {
20010        /**
20011         * Called when a touch event is dispatched to a view. This allows listeners to
20012         * get a chance to respond before the target view.
20013         *
20014         * @param v The view the touch event has been dispatched to.
20015         * @param event The MotionEvent object containing full information about
20016         *        the event.
20017         * @return True if the listener has consumed the event, false otherwise.
20018         */
20019        boolean onTouch(View v, MotionEvent event);
20020    }
20021
20022    /**
20023     * Interface definition for a callback to be invoked when a hover event is
20024     * dispatched to this view. The callback will be invoked before the hover
20025     * event is given to the view.
20026     */
20027    public interface OnHoverListener {
20028        /**
20029         * Called when a hover event is dispatched to a view. This allows listeners to
20030         * get a chance to respond before the target view.
20031         *
20032         * @param v The view the hover event has been dispatched to.
20033         * @param event The MotionEvent object containing full information about
20034         *        the event.
20035         * @return True if the listener has consumed the event, false otherwise.
20036         */
20037        boolean onHover(View v, MotionEvent event);
20038    }
20039
20040    /**
20041     * Interface definition for a callback to be invoked when a generic motion event is
20042     * dispatched to this view. The callback will be invoked before the generic motion
20043     * event is given to the view.
20044     */
20045    public interface OnGenericMotionListener {
20046        /**
20047         * Called when a generic motion event is dispatched to a view. This allows listeners to
20048         * get a chance to respond before the target view.
20049         *
20050         * @param v The view the generic motion event has been dispatched to.
20051         * @param event The MotionEvent object containing full information about
20052         *        the event.
20053         * @return True if the listener has consumed the event, false otherwise.
20054         */
20055        boolean onGenericMotion(View v, MotionEvent event);
20056    }
20057
20058    /**
20059     * Interface definition for a callback to be invoked when a view has been clicked and held.
20060     */
20061    public interface OnLongClickListener {
20062        /**
20063         * Called when a view has been clicked and held.
20064         *
20065         * @param v The view that was clicked and held.
20066         *
20067         * @return true if the callback consumed the long click, false otherwise.
20068         */
20069        boolean onLongClick(View v);
20070    }
20071
20072    /**
20073     * Interface definition for a callback to be invoked when a drag is being dispatched
20074     * to this view.  The callback will be invoked before the hosting view's own
20075     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20076     * onDrag(event) behavior, it should return 'false' from this callback.
20077     *
20078     * <div class="special reference">
20079     * <h3>Developer Guides</h3>
20080     * <p>For a guide to implementing drag and drop features, read the
20081     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20082     * </div>
20083     */
20084    public interface OnDragListener {
20085        /**
20086         * Called when a drag event is dispatched to a view. This allows listeners
20087         * to get a chance to override base View behavior.
20088         *
20089         * @param v The View that received the drag event.
20090         * @param event The {@link android.view.DragEvent} object for the drag event.
20091         * @return {@code true} if the drag event was handled successfully, or {@code false}
20092         * if the drag event was not handled. Note that {@code false} will trigger the View
20093         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20094         */
20095        boolean onDrag(View v, DragEvent event);
20096    }
20097
20098    /**
20099     * Interface definition for a callback to be invoked when the focus state of
20100     * a view changed.
20101     */
20102    public interface OnFocusChangeListener {
20103        /**
20104         * Called when the focus state of a view has changed.
20105         *
20106         * @param v The view whose state has changed.
20107         * @param hasFocus The new focus state of v.
20108         */
20109        void onFocusChange(View v, boolean hasFocus);
20110    }
20111
20112    /**
20113     * Interface definition for a callback to be invoked when a view is clicked.
20114     */
20115    public interface OnClickListener {
20116        /**
20117         * Called when a view has been clicked.
20118         *
20119         * @param v The view that was clicked.
20120         */
20121        void onClick(View v);
20122    }
20123
20124    /**
20125     * Interface definition for a callback to be invoked when the context menu
20126     * for this view is being built.
20127     */
20128    public interface OnCreateContextMenuListener {
20129        /**
20130         * Called when the context menu for this view is being built. It is not
20131         * safe to hold onto the menu after this method returns.
20132         *
20133         * @param menu The context menu that is being built
20134         * @param v The view for which the context menu is being built
20135         * @param menuInfo Extra information about the item for which the
20136         *            context menu should be shown. This information will vary
20137         *            depending on the class of v.
20138         */
20139        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20140    }
20141
20142    /**
20143     * Interface definition for a callback to be invoked when the status bar changes
20144     * visibility.  This reports <strong>global</strong> changes to the system UI
20145     * state, not what the application is requesting.
20146     *
20147     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20148     */
20149    public interface OnSystemUiVisibilityChangeListener {
20150        /**
20151         * Called when the status bar changes visibility because of a call to
20152         * {@link View#setSystemUiVisibility(int)}.
20153         *
20154         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20155         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20156         * This tells you the <strong>global</strong> state of these UI visibility
20157         * flags, not what your app is currently applying.
20158         */
20159        public void onSystemUiVisibilityChange(int visibility);
20160    }
20161
20162    /**
20163     * Interface definition for a callback to be invoked when this view is attached
20164     * or detached from its window.
20165     */
20166    public interface OnAttachStateChangeListener {
20167        /**
20168         * Called when the view is attached to a window.
20169         * @param v The view that was attached
20170         */
20171        public void onViewAttachedToWindow(View v);
20172        /**
20173         * Called when the view is detached from a window.
20174         * @param v The view that was detached
20175         */
20176        public void onViewDetachedFromWindow(View v);
20177    }
20178
20179    /**
20180     * Listener for applying window insets on a view in a custom way.
20181     *
20182     * <p>Apps may choose to implement this interface if they want to apply custom policy
20183     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20184     * is set, its
20185     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20186     * method will be called instead of the View's own
20187     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20188     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20189     * the View's normal behavior as part of its own.</p>
20190     */
20191    public interface OnApplyWindowInsetsListener {
20192        /**
20193         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20194         * on a View, this listener method will be called instead of the view's own
20195         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20196         *
20197         * @param v The view applying window insets
20198         * @param insets The insets to apply
20199         * @return The insets supplied, minus any insets that were consumed
20200         */
20201        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20202    }
20203
20204    private final class UnsetPressedState implements Runnable {
20205        @Override
20206        public void run() {
20207            setPressed(false);
20208        }
20209    }
20210
20211    /**
20212     * Base class for derived classes that want to save and restore their own
20213     * state in {@link android.view.View#onSaveInstanceState()}.
20214     */
20215    public static class BaseSavedState extends AbsSavedState {
20216        /**
20217         * Constructor used when reading from a parcel. Reads the state of the superclass.
20218         *
20219         * @param source
20220         */
20221        public BaseSavedState(Parcel source) {
20222            super(source);
20223        }
20224
20225        /**
20226         * Constructor called by derived classes when creating their SavedState objects
20227         *
20228         * @param superState The state of the superclass of this view
20229         */
20230        public BaseSavedState(Parcelable superState) {
20231            super(superState);
20232        }
20233
20234        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20235                new Parcelable.Creator<BaseSavedState>() {
20236            public BaseSavedState createFromParcel(Parcel in) {
20237                return new BaseSavedState(in);
20238            }
20239
20240            public BaseSavedState[] newArray(int size) {
20241                return new BaseSavedState[size];
20242            }
20243        };
20244    }
20245
20246    /**
20247     * A set of information given to a view when it is attached to its parent
20248     * window.
20249     */
20250    final static class AttachInfo {
20251        interface Callbacks {
20252            void playSoundEffect(int effectId);
20253            boolean performHapticFeedback(int effectId, boolean always);
20254        }
20255
20256        /**
20257         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20258         * to a Handler. This class contains the target (View) to invalidate and
20259         * the coordinates of the dirty rectangle.
20260         *
20261         * For performance purposes, this class also implements a pool of up to
20262         * POOL_LIMIT objects that get reused. This reduces memory allocations
20263         * whenever possible.
20264         */
20265        static class InvalidateInfo {
20266            private static final int POOL_LIMIT = 10;
20267
20268            private static final SynchronizedPool<InvalidateInfo> sPool =
20269                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20270
20271            View target;
20272
20273            int left;
20274            int top;
20275            int right;
20276            int bottom;
20277
20278            public static InvalidateInfo obtain() {
20279                InvalidateInfo instance = sPool.acquire();
20280                return (instance != null) ? instance : new InvalidateInfo();
20281            }
20282
20283            public void recycle() {
20284                target = null;
20285                sPool.release(this);
20286            }
20287        }
20288
20289        final IWindowSession mSession;
20290
20291        final IWindow mWindow;
20292
20293        final IBinder mWindowToken;
20294
20295        final Display mDisplay;
20296
20297        final Callbacks mRootCallbacks;
20298
20299        IWindowId mIWindowId;
20300        WindowId mWindowId;
20301
20302        /**
20303         * The top view of the hierarchy.
20304         */
20305        View mRootView;
20306
20307        IBinder mPanelParentWindowToken;
20308
20309        boolean mHardwareAccelerated;
20310        boolean mHardwareAccelerationRequested;
20311        HardwareRenderer mHardwareRenderer;
20312        List<RenderNode> mPendingAnimatingRenderNodes;
20313
20314        /**
20315         * The state of the display to which the window is attached, as reported
20316         * by {@link Display#getState()}.  Note that the display state constants
20317         * declared by {@link Display} do not exactly line up with the screen state
20318         * constants declared by {@link View} (there are more display states than
20319         * screen states).
20320         */
20321        int mDisplayState = Display.STATE_UNKNOWN;
20322
20323        /**
20324         * Scale factor used by the compatibility mode
20325         */
20326        float mApplicationScale;
20327
20328        /**
20329         * Indicates whether the application is in compatibility mode
20330         */
20331        boolean mScalingRequired;
20332
20333        /**
20334         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20335         */
20336        boolean mTurnOffWindowResizeAnim;
20337
20338        /**
20339         * Left position of this view's window
20340         */
20341        int mWindowLeft;
20342
20343        /**
20344         * Top position of this view's window
20345         */
20346        int mWindowTop;
20347
20348        /**
20349         * Indicates whether views need to use 32-bit drawing caches
20350         */
20351        boolean mUse32BitDrawingCache;
20352
20353        /**
20354         * For windows that are full-screen but using insets to layout inside
20355         * of the screen areas, these are the current insets to appear inside
20356         * the overscan area of the display.
20357         */
20358        final Rect mOverscanInsets = new Rect();
20359
20360        /**
20361         * For windows that are full-screen but using insets to layout inside
20362         * of the screen decorations, these are the current insets for the
20363         * content of the window.
20364         */
20365        final Rect mContentInsets = new Rect();
20366
20367        /**
20368         * For windows that are full-screen but using insets to layout inside
20369         * of the screen decorations, these are the current insets for the
20370         * actual visible parts of the window.
20371         */
20372        final Rect mVisibleInsets = new Rect();
20373
20374        /**
20375         * For windows that are full-screen but using insets to layout inside
20376         * of the screen decorations, these are the current insets for the
20377         * stable system windows.
20378         */
20379        final Rect mStableInsets = new Rect();
20380
20381        /**
20382         * The internal insets given by this window.  This value is
20383         * supplied by the client (through
20384         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20385         * be given to the window manager when changed to be used in laying
20386         * out windows behind it.
20387         */
20388        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20389                = new ViewTreeObserver.InternalInsetsInfo();
20390
20391        /**
20392         * Set to true when mGivenInternalInsets is non-empty.
20393         */
20394        boolean mHasNonEmptyGivenInternalInsets;
20395
20396        /**
20397         * All views in the window's hierarchy that serve as scroll containers,
20398         * used to determine if the window can be resized or must be panned
20399         * to adjust for a soft input area.
20400         */
20401        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20402
20403        final KeyEvent.DispatcherState mKeyDispatchState
20404                = new KeyEvent.DispatcherState();
20405
20406        /**
20407         * Indicates whether the view's window currently has the focus.
20408         */
20409        boolean mHasWindowFocus;
20410
20411        /**
20412         * The current visibility of the window.
20413         */
20414        int mWindowVisibility;
20415
20416        /**
20417         * Indicates the time at which drawing started to occur.
20418         */
20419        long mDrawingTime;
20420
20421        /**
20422         * Indicates whether or not ignoring the DIRTY_MASK flags.
20423         */
20424        boolean mIgnoreDirtyState;
20425
20426        /**
20427         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20428         * to avoid clearing that flag prematurely.
20429         */
20430        boolean mSetIgnoreDirtyState = false;
20431
20432        /**
20433         * Indicates whether the view's window is currently in touch mode.
20434         */
20435        boolean mInTouchMode;
20436
20437        /**
20438         * Indicates whether the view has requested unbuffered input dispatching for the current
20439         * event stream.
20440         */
20441        boolean mUnbufferedDispatchRequested;
20442
20443        /**
20444         * Indicates that ViewAncestor should trigger a global layout change
20445         * the next time it performs a traversal
20446         */
20447        boolean mRecomputeGlobalAttributes;
20448
20449        /**
20450         * Always report new attributes at next traversal.
20451         */
20452        boolean mForceReportNewAttributes;
20453
20454        /**
20455         * Set during a traveral if any views want to keep the screen on.
20456         */
20457        boolean mKeepScreenOn;
20458
20459        /**
20460         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20461         */
20462        int mSystemUiVisibility;
20463
20464        /**
20465         * Hack to force certain system UI visibility flags to be cleared.
20466         */
20467        int mDisabledSystemUiVisibility;
20468
20469        /**
20470         * Last global system UI visibility reported by the window manager.
20471         */
20472        int mGlobalSystemUiVisibility;
20473
20474        /**
20475         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20476         * attached.
20477         */
20478        boolean mHasSystemUiListeners;
20479
20480        /**
20481         * Set if the window has requested to extend into the overscan region
20482         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20483         */
20484        boolean mOverscanRequested;
20485
20486        /**
20487         * Set if the visibility of any views has changed.
20488         */
20489        boolean mViewVisibilityChanged;
20490
20491        /**
20492         * Set to true if a view has been scrolled.
20493         */
20494        boolean mViewScrollChanged;
20495
20496        /**
20497         * Set to true if high contrast mode enabled
20498         */
20499        boolean mHighContrastText;
20500
20501        /**
20502         * Global to the view hierarchy used as a temporary for dealing with
20503         * x/y points in the transparent region computations.
20504         */
20505        final int[] mTransparentLocation = new int[2];
20506
20507        /**
20508         * Global to the view hierarchy used as a temporary for dealing with
20509         * x/y points in the ViewGroup.invalidateChild implementation.
20510         */
20511        final int[] mInvalidateChildLocation = new int[2];
20512
20513        /**
20514         * Global to the view hierarchy used as a temporary for dealng with
20515         * computing absolute on-screen location.
20516         */
20517        final int[] mTmpLocation = new int[2];
20518
20519        /**
20520         * Global to the view hierarchy used as a temporary for dealing with
20521         * x/y location when view is transformed.
20522         */
20523        final float[] mTmpTransformLocation = new float[2];
20524
20525        /**
20526         * The view tree observer used to dispatch global events like
20527         * layout, pre-draw, touch mode change, etc.
20528         */
20529        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20530
20531        /**
20532         * A Canvas used by the view hierarchy to perform bitmap caching.
20533         */
20534        Canvas mCanvas;
20535
20536        /**
20537         * The view root impl.
20538         */
20539        final ViewRootImpl mViewRootImpl;
20540
20541        /**
20542         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20543         * handler can be used to pump events in the UI events queue.
20544         */
20545        final Handler mHandler;
20546
20547        /**
20548         * Temporary for use in computing invalidate rectangles while
20549         * calling up the hierarchy.
20550         */
20551        final Rect mTmpInvalRect = new Rect();
20552
20553        /**
20554         * Temporary for use in computing hit areas with transformed views
20555         */
20556        final RectF mTmpTransformRect = new RectF();
20557
20558        /**
20559         * Temporary for use in computing hit areas with transformed views
20560         */
20561        final RectF mTmpTransformRect1 = new RectF();
20562
20563        /**
20564         * Temporary list of rectanges.
20565         */
20566        final List<RectF> mTmpRectList = new ArrayList<>();
20567
20568        /**
20569         * Temporary for use in transforming invalidation rect
20570         */
20571        final Matrix mTmpMatrix = new Matrix();
20572
20573        /**
20574         * Temporary for use in transforming invalidation rect
20575         */
20576        final Transformation mTmpTransformation = new Transformation();
20577
20578        /**
20579         * Temporary for use in querying outlines from OutlineProviders
20580         */
20581        final Outline mTmpOutline = new Outline();
20582
20583        /**
20584         * Temporary list for use in collecting focusable descendents of a view.
20585         */
20586        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20587
20588        /**
20589         * The id of the window for accessibility purposes.
20590         */
20591        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20592
20593        /**
20594         * Flags related to accessibility processing.
20595         *
20596         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20597         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20598         */
20599        int mAccessibilityFetchFlags;
20600
20601        /**
20602         * The drawable for highlighting accessibility focus.
20603         */
20604        Drawable mAccessibilityFocusDrawable;
20605
20606        /**
20607         * Show where the margins, bounds and layout bounds are for each view.
20608         */
20609        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20610
20611        /**
20612         * Point used to compute visible regions.
20613         */
20614        final Point mPoint = new Point();
20615
20616        /**
20617         * Used to track which View originated a requestLayout() call, used when
20618         * requestLayout() is called during layout.
20619         */
20620        View mViewRequestingLayout;
20621
20622        /**
20623         * Creates a new set of attachment information with the specified
20624         * events handler and thread.
20625         *
20626         * @param handler the events handler the view must use
20627         */
20628        AttachInfo(IWindowSession session, IWindow window, Display display,
20629                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20630            mSession = session;
20631            mWindow = window;
20632            mWindowToken = window.asBinder();
20633            mDisplay = display;
20634            mViewRootImpl = viewRootImpl;
20635            mHandler = handler;
20636            mRootCallbacks = effectPlayer;
20637        }
20638    }
20639
20640    /**
20641     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20642     * is supported. This avoids keeping too many unused fields in most
20643     * instances of View.</p>
20644     */
20645    private static class ScrollabilityCache implements Runnable {
20646
20647        /**
20648         * Scrollbars are not visible
20649         */
20650        public static final int OFF = 0;
20651
20652        /**
20653         * Scrollbars are visible
20654         */
20655        public static final int ON = 1;
20656
20657        /**
20658         * Scrollbars are fading away
20659         */
20660        public static final int FADING = 2;
20661
20662        public boolean fadeScrollBars;
20663
20664        public int fadingEdgeLength;
20665        public int scrollBarDefaultDelayBeforeFade;
20666        public int scrollBarFadeDuration;
20667
20668        public int scrollBarSize;
20669        public ScrollBarDrawable scrollBar;
20670        public float[] interpolatorValues;
20671        public View host;
20672
20673        public final Paint paint;
20674        public final Matrix matrix;
20675        public Shader shader;
20676
20677        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20678
20679        private static final float[] OPAQUE = { 255 };
20680        private static final float[] TRANSPARENT = { 0.0f };
20681
20682        /**
20683         * When fading should start. This time moves into the future every time
20684         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20685         */
20686        public long fadeStartTime;
20687
20688
20689        /**
20690         * The current state of the scrollbars: ON, OFF, or FADING
20691         */
20692        public int state = OFF;
20693
20694        private int mLastColor;
20695
20696        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20697            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20698            scrollBarSize = configuration.getScaledScrollBarSize();
20699            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20700            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20701
20702            paint = new Paint();
20703            matrix = new Matrix();
20704            // use use a height of 1, and then wack the matrix each time we
20705            // actually use it.
20706            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20707            paint.setShader(shader);
20708            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20709
20710            this.host = host;
20711        }
20712
20713        public void setFadeColor(int color) {
20714            if (color != mLastColor) {
20715                mLastColor = color;
20716
20717                if (color != 0) {
20718                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20719                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20720                    paint.setShader(shader);
20721                    // Restore the default transfer mode (src_over)
20722                    paint.setXfermode(null);
20723                } else {
20724                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20725                    paint.setShader(shader);
20726                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20727                }
20728            }
20729        }
20730
20731        public void run() {
20732            long now = AnimationUtils.currentAnimationTimeMillis();
20733            if (now >= fadeStartTime) {
20734
20735                // the animation fades the scrollbars out by changing
20736                // the opacity (alpha) from fully opaque to fully
20737                // transparent
20738                int nextFrame = (int) now;
20739                int framesCount = 0;
20740
20741                Interpolator interpolator = scrollBarInterpolator;
20742
20743                // Start opaque
20744                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20745
20746                // End transparent
20747                nextFrame += scrollBarFadeDuration;
20748                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20749
20750                state = FADING;
20751
20752                // Kick off the fade animation
20753                host.invalidate(true);
20754            }
20755        }
20756    }
20757
20758    /**
20759     * Resuable callback for sending
20760     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20761     */
20762    private class SendViewScrolledAccessibilityEvent implements Runnable {
20763        public volatile boolean mIsPending;
20764
20765        public void run() {
20766            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20767            mIsPending = false;
20768        }
20769    }
20770
20771    /**
20772     * <p>
20773     * This class represents a delegate that can be registered in a {@link View}
20774     * to enhance accessibility support via composition rather via inheritance.
20775     * It is specifically targeted to widget developers that extend basic View
20776     * classes i.e. classes in package android.view, that would like their
20777     * applications to be backwards compatible.
20778     * </p>
20779     * <div class="special reference">
20780     * <h3>Developer Guides</h3>
20781     * <p>For more information about making applications accessible, read the
20782     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20783     * developer guide.</p>
20784     * </div>
20785     * <p>
20786     * A scenario in which a developer would like to use an accessibility delegate
20787     * is overriding a method introduced in a later API version then the minimal API
20788     * version supported by the application. For example, the method
20789     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20790     * in API version 4 when the accessibility APIs were first introduced. If a
20791     * developer would like his application to run on API version 4 devices (assuming
20792     * all other APIs used by the application are version 4 or lower) and take advantage
20793     * of this method, instead of overriding the method which would break the application's
20794     * backwards compatibility, he can override the corresponding method in this
20795     * delegate and register the delegate in the target View if the API version of
20796     * the system is high enough i.e. the API version is same or higher to the API
20797     * version that introduced
20798     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20799     * </p>
20800     * <p>
20801     * Here is an example implementation:
20802     * </p>
20803     * <code><pre><p>
20804     * if (Build.VERSION.SDK_INT >= 14) {
20805     *     // If the API version is equal of higher than the version in
20806     *     // which onInitializeAccessibilityNodeInfo was introduced we
20807     *     // register a delegate with a customized implementation.
20808     *     View view = findViewById(R.id.view_id);
20809     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20810     *         public void onInitializeAccessibilityNodeInfo(View host,
20811     *                 AccessibilityNodeInfo info) {
20812     *             // Let the default implementation populate the info.
20813     *             super.onInitializeAccessibilityNodeInfo(host, info);
20814     *             // Set some other information.
20815     *             info.setEnabled(host.isEnabled());
20816     *         }
20817     *     });
20818     * }
20819     * </code></pre></p>
20820     * <p>
20821     * This delegate contains methods that correspond to the accessibility methods
20822     * in View. If a delegate has been specified the implementation in View hands
20823     * off handling to the corresponding method in this delegate. The default
20824     * implementation the delegate methods behaves exactly as the corresponding
20825     * method in View for the case of no accessibility delegate been set. Hence,
20826     * to customize the behavior of a View method, clients can override only the
20827     * corresponding delegate method without altering the behavior of the rest
20828     * accessibility related methods of the host view.
20829     * </p>
20830     */
20831    public static class AccessibilityDelegate {
20832
20833        /**
20834         * Sends an accessibility event of the given type. If accessibility is not
20835         * enabled this method has no effect.
20836         * <p>
20837         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20838         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20839         * been set.
20840         * </p>
20841         *
20842         * @param host The View hosting the delegate.
20843         * @param eventType The type of the event to send.
20844         *
20845         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20846         */
20847        public void sendAccessibilityEvent(View host, int eventType) {
20848            host.sendAccessibilityEventInternal(eventType);
20849        }
20850
20851        /**
20852         * Performs the specified accessibility action on the view. For
20853         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20854         * <p>
20855         * The default implementation behaves as
20856         * {@link View#performAccessibilityAction(int, Bundle)
20857         *  View#performAccessibilityAction(int, Bundle)} for the case of
20858         *  no accessibility delegate been set.
20859         * </p>
20860         *
20861         * @param action The action to perform.
20862         * @return Whether the action was performed.
20863         *
20864         * @see View#performAccessibilityAction(int, Bundle)
20865         *      View#performAccessibilityAction(int, Bundle)
20866         */
20867        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20868            return host.performAccessibilityActionInternal(action, args);
20869        }
20870
20871        /**
20872         * Sends an accessibility event. This method behaves exactly as
20873         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20874         * empty {@link AccessibilityEvent} and does not perform a check whether
20875         * accessibility is enabled.
20876         * <p>
20877         * The default implementation behaves as
20878         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20879         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20880         * the case of no accessibility delegate been set.
20881         * </p>
20882         *
20883         * @param host The View hosting the delegate.
20884         * @param event The event to send.
20885         *
20886         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20887         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20888         */
20889        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20890            host.sendAccessibilityEventUncheckedInternal(event);
20891        }
20892
20893        /**
20894         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20895         * to its children for adding their text content to the event.
20896         * <p>
20897         * The default implementation behaves as
20898         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20899         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20900         * the case of no accessibility delegate been set.
20901         * </p>
20902         *
20903         * @param host The View hosting the delegate.
20904         * @param event The event.
20905         * @return True if the event population was completed.
20906         *
20907         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20908         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20909         */
20910        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20911            return host.dispatchPopulateAccessibilityEventInternal(event);
20912        }
20913
20914        /**
20915         * Gives a chance to the host View to populate the accessibility event with its
20916         * text content.
20917         * <p>
20918         * The default implementation behaves as
20919         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20920         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20921         * the case of no accessibility delegate been set.
20922         * </p>
20923         *
20924         * @param host The View hosting the delegate.
20925         * @param event The accessibility event which to populate.
20926         *
20927         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20928         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20929         */
20930        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20931            host.onPopulateAccessibilityEventInternal(event);
20932        }
20933
20934        /**
20935         * Initializes an {@link AccessibilityEvent} with information about the
20936         * the host View which is the event source.
20937         * <p>
20938         * The default implementation behaves as
20939         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20940         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20941         * the case of no accessibility delegate been set.
20942         * </p>
20943         *
20944         * @param host The View hosting the delegate.
20945         * @param event The event to initialize.
20946         *
20947         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20948         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20949         */
20950        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20951            host.onInitializeAccessibilityEventInternal(event);
20952        }
20953
20954        /**
20955         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20956         * <p>
20957         * The default implementation behaves as
20958         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20959         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20960         * the case of no accessibility delegate been set.
20961         * </p>
20962         *
20963         * @param host The View hosting the delegate.
20964         * @param info The instance to initialize.
20965         *
20966         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20967         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20968         */
20969        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20970            host.onInitializeAccessibilityNodeInfoInternal(info);
20971        }
20972
20973        /**
20974         * Called when a child of the host View has requested sending an
20975         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20976         * to augment the event.
20977         * <p>
20978         * The default implementation behaves as
20979         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20980         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20981         * the case of no accessibility delegate been set.
20982         * </p>
20983         *
20984         * @param host The View hosting the delegate.
20985         * @param child The child which requests sending the event.
20986         * @param event The event to be sent.
20987         * @return True if the event should be sent
20988         *
20989         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20990         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20991         */
20992        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20993                AccessibilityEvent event) {
20994            return host.onRequestSendAccessibilityEventInternal(child, event);
20995        }
20996
20997        /**
20998         * Gets the provider for managing a virtual view hierarchy rooted at this View
20999         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21000         * that explore the window content.
21001         * <p>
21002         * The default implementation behaves as
21003         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21004         * the case of no accessibility delegate been set.
21005         * </p>
21006         *
21007         * @return The provider.
21008         *
21009         * @see AccessibilityNodeProvider
21010         */
21011        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21012            return null;
21013        }
21014
21015        /**
21016         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21017         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21018         * This method is responsible for obtaining an accessibility node info from a
21019         * pool of reusable instances and calling
21020         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21021         * view to initialize the former.
21022         * <p>
21023         * <strong>Note:</strong> The client is responsible for recycling the obtained
21024         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21025         * creation.
21026         * </p>
21027         * <p>
21028         * The default implementation behaves as
21029         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21030         * the case of no accessibility delegate been set.
21031         * </p>
21032         * @return A populated {@link AccessibilityNodeInfo}.
21033         *
21034         * @see AccessibilityNodeInfo
21035         *
21036         * @hide
21037         */
21038        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21039            return host.createAccessibilityNodeInfoInternal();
21040        }
21041    }
21042
21043    private class MatchIdPredicate implements Predicate<View> {
21044        public int mId;
21045
21046        @Override
21047        public boolean apply(View view) {
21048            return (view.mID == mId);
21049        }
21050    }
21051
21052    private class MatchLabelForPredicate implements Predicate<View> {
21053        private int mLabeledId;
21054
21055        @Override
21056        public boolean apply(View view) {
21057            return (view.mLabelForId == mLabeledId);
21058        }
21059    }
21060
21061    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21062        private int mChangeTypes = 0;
21063        private boolean mPosted;
21064        private boolean mPostedWithDelay;
21065        private long mLastEventTimeMillis;
21066
21067        @Override
21068        public void run() {
21069            mPosted = false;
21070            mPostedWithDelay = false;
21071            mLastEventTimeMillis = SystemClock.uptimeMillis();
21072            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21073                final AccessibilityEvent event = AccessibilityEvent.obtain();
21074                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21075                event.setContentChangeTypes(mChangeTypes);
21076                sendAccessibilityEventUnchecked(event);
21077            }
21078            mChangeTypes = 0;
21079        }
21080
21081        public void runOrPost(int changeType) {
21082            mChangeTypes |= changeType;
21083
21084            // If this is a live region or the child of a live region, collect
21085            // all events from this frame and send them on the next frame.
21086            if (inLiveRegion()) {
21087                // If we're already posted with a delay, remove that.
21088                if (mPostedWithDelay) {
21089                    removeCallbacks(this);
21090                    mPostedWithDelay = false;
21091                }
21092                // Only post if we're not already posted.
21093                if (!mPosted) {
21094                    post(this);
21095                    mPosted = true;
21096                }
21097                return;
21098            }
21099
21100            if (mPosted) {
21101                return;
21102            }
21103
21104            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21105            final long minEventIntevalMillis =
21106                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21107            if (timeSinceLastMillis >= minEventIntevalMillis) {
21108                removeCallbacks(this);
21109                run();
21110            } else {
21111                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21112                mPostedWithDelay = true;
21113            }
21114        }
21115    }
21116
21117    private boolean inLiveRegion() {
21118        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21119            return true;
21120        }
21121
21122        ViewParent parent = getParent();
21123        while (parent instanceof View) {
21124            if (((View) parent).getAccessibilityLiveRegion()
21125                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21126                return true;
21127            }
21128            parent = parent.getParent();
21129        }
21130
21131        return false;
21132    }
21133
21134    /**
21135     * Dump all private flags in readable format, useful for documentation and
21136     * sanity checking.
21137     */
21138    private static void dumpFlags() {
21139        final HashMap<String, String> found = Maps.newHashMap();
21140        try {
21141            for (Field field : View.class.getDeclaredFields()) {
21142                final int modifiers = field.getModifiers();
21143                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21144                    if (field.getType().equals(int.class)) {
21145                        final int value = field.getInt(null);
21146                        dumpFlag(found, field.getName(), value);
21147                    } else if (field.getType().equals(int[].class)) {
21148                        final int[] values = (int[]) field.get(null);
21149                        for (int i = 0; i < values.length; i++) {
21150                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21151                        }
21152                    }
21153                }
21154            }
21155        } catch (IllegalAccessException e) {
21156            throw new RuntimeException(e);
21157        }
21158
21159        final ArrayList<String> keys = Lists.newArrayList();
21160        keys.addAll(found.keySet());
21161        Collections.sort(keys);
21162        for (String key : keys) {
21163            Log.d(VIEW_LOG_TAG, found.get(key));
21164        }
21165    }
21166
21167    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21168        // Sort flags by prefix, then by bits, always keeping unique keys
21169        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21170        final int prefix = name.indexOf('_');
21171        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21172        final String output = bits + " " + name;
21173        found.put(key, output);
21174    }
21175}
21176