View.java revision fb410d219fae2e07a6be3c7365bedc3e11c96f6c
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.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.hardware.display.DisplayManagerGlobal;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.text.TextUtils;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.LayoutDirection;
55import android.util.Log;
56import android.util.LongSparseLongArray;
57import android.util.Pools.SynchronizedPool;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.view.transition.Scene;
78import android.widget.ScrollBarDrawable;
79
80import static android.os.Build.VERSION_CODES.*;
81import static java.lang.Math.max;
82
83import com.android.internal.R;
84import com.android.internal.util.Predicate;
85import com.android.internal.view.menu.MenuBuilder;
86import com.google.android.collect.Lists;
87import com.google.android.collect.Maps;
88
89import java.lang.ref.WeakReference;
90import java.lang.reflect.Field;
91import java.lang.reflect.InvocationTargetException;
92import java.lang.reflect.Method;
93import java.lang.reflect.Modifier;
94import java.util.ArrayList;
95import java.util.Arrays;
96import java.util.Collections;
97import java.util.HashMap;
98import java.util.Locale;
99import java.util.concurrent.CopyOnWriteArrayList;
100import java.util.concurrent.atomic.AtomicInteger;
101
102/**
103 * <p>
104 * This class represents the basic building block for user interface components. A View
105 * occupies a rectangular area on the screen and is responsible for drawing and
106 * event handling. View is the base class for <em>widgets</em>, which are
107 * used to create interactive UI components (buttons, text fields, etc.). The
108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
109 * are invisible containers that hold other Views (or other ViewGroups) and define
110 * their layout properties.
111 * </p>
112 *
113 * <div class="special reference">
114 * <h3>Developer Guides</h3>
115 * <p>For information about using this class to develop your application's user interface,
116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
117 * </div>
118 *
119 * <a name="Using"></a>
120 * <h3>Using Views</h3>
121 * <p>
122 * All of the views in a window are arranged in a single tree. You can add views
123 * either from code or by specifying a tree of views in one or more XML layout
124 * files. There are many specialized subclasses of views that act as controls or
125 * are capable of displaying text, images, or other content.
126 * </p>
127 * <p>
128 * Once you have created a tree of views, there are typically a few types of
129 * common operations you may wish to perform:
130 * <ul>
131 * <li><strong>Set properties:</strong> for example setting the text of a
132 * {@link android.widget.TextView}. The available properties and the methods
133 * that set them will vary among the different subclasses of views. Note that
134 * properties that are known at build time can be set in the XML layout
135 * files.</li>
136 * <li><strong>Set focus:</strong> The framework will handled moving focus in
137 * response to user input. To force focus to a specific view, call
138 * {@link #requestFocus}.</li>
139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
140 * that will be notified when something interesting happens to the view. For
141 * example, all views will let you set a listener to be notified when the view
142 * gains or loses focus. You can register such a listener using
143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
144 * Other view subclasses offer more specialized listeners. For example, a Button
145 * exposes a listener to notify clients when the button is clicked.</li>
146 * <li><strong>Set visibility:</strong> You can hide or show views using
147 * {@link #setVisibility(int)}.</li>
148 * </ul>
149 * </p>
150 * <p><em>
151 * Note: The Android framework is responsible for measuring, laying out and
152 * drawing views. You should not call methods that perform these actions on
153 * views yourself unless you are actually implementing a
154 * {@link android.view.ViewGroup}.
155 * </em></p>
156 *
157 * <a name="Lifecycle"></a>
158 * <h3>Implementing a Custom View</h3>
159 *
160 * <p>
161 * To implement a custom view, you will usually begin by providing overrides for
162 * some of the standard methods that the framework calls on all views. You do
163 * not need to override all of these methods. In fact, you can start by just
164 * overriding {@link #onDraw(android.graphics.Canvas)}.
165 * <table border="2" width="85%" align="center" cellpadding="5">
166 *     <thead>
167 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
168 *     </thead>
169 *
170 *     <tbody>
171 *     <tr>
172 *         <td rowspan="2">Creation</td>
173 *         <td>Constructors</td>
174 *         <td>There is a form of the constructor that are called when the view
175 *         is created from code and a form that is called when the view is
176 *         inflated from a layout file. The second form should parse and apply
177 *         any attributes defined in the layout file.
178 *         </td>
179 *     </tr>
180 *     <tr>
181 *         <td><code>{@link #onFinishInflate()}</code></td>
182 *         <td>Called after a view and all of its children has been inflated
183 *         from XML.</td>
184 *     </tr>
185 *
186 *     <tr>
187 *         <td rowspan="3">Layout</td>
188 *         <td><code>{@link #onMeasure(int, int)}</code></td>
189 *         <td>Called to determine the size requirements for this view and all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
195 *         <td>Called when this view should assign a size and position to all
196 *         of its children.
197 *         </td>
198 *     </tr>
199 *     <tr>
200 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
201 *         <td>Called when the size of this view has changed.
202 *         </td>
203 *     </tr>
204 *
205 *     <tr>
206 *         <td>Drawing</td>
207 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
208 *         <td>Called when the view should render its content.
209 *         </td>
210 *     </tr>
211 *
212 *     <tr>
213 *         <td rowspan="4">Event processing</td>
214 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
215 *         <td>Called when a new hardware key event occurs.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
220 *         <td>Called when a hardware key up event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
225 *         <td>Called when a trackball motion event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
230 *         <td>Called when a touch screen motion event occurs.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="2">Focus</td>
236 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
237 *         <td>Called when the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
243 *         <td>Called when the window containing the view gains or loses focus.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="3">Attaching</td>
249 *         <td><code>{@link #onAttachedToWindow()}</code></td>
250 *         <td>Called when the view is attached to a window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onDetachedFromWindow}</code></td>
256 *         <td>Called when the view is detached from its window.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
262 *         <td>Called when the visibility of the window containing the view
263 *         has changed.
264 *         </td>
265 *     </tr>
266 *     </tbody>
267 *
268 * </table>
269 * </p>
270 *
271 * <a name="IDs"></a>
272 * <h3>IDs</h3>
273 * Views may have an integer id associated with them. These ids are typically
274 * assigned in the layout XML files, and are used to find specific views within
275 * the view tree. A common pattern is to:
276 * <ul>
277 * <li>Define a Button in the layout file and assign it a unique ID.
278 * <pre>
279 * &lt;Button
280 *     android:id="@+id/my_button"
281 *     android:layout_width="wrap_content"
282 *     android:layout_height="wrap_content"
283 *     android:text="@string/my_button_text"/&gt;
284 * </pre></li>
285 * <li>From the onCreate method of an Activity, find the Button
286 * <pre class="prettyprint">
287 *      Button myButton = (Button) findViewById(R.id.my_button);
288 * </pre></li>
289 * </ul>
290 * <p>
291 * View IDs need not be unique throughout the tree, but it is good practice to
292 * ensure that they are at least unique within the part of the tree you are
293 * searching.
294 * </p>
295 *
296 * <a name="Position"></a>
297 * <h3>Position</h3>
298 * <p>
299 * The geometry of a view is that of a rectangle. A view has a location,
300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
301 * two dimensions, expressed as a width and a height. The unit for location
302 * and dimensions is the pixel.
303 * </p>
304 *
305 * <p>
306 * It is possible to retrieve the location of a view by invoking the methods
307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
308 * coordinate of the rectangle representing the view. The latter returns the
309 * top, or Y, coordinate of the rectangle representing the view. These methods
310 * both return the location of the view relative to its parent. For instance,
311 * when getLeft() returns 20, that means the view is located 20 pixels to the
312 * right of the left edge of its direct parent.
313 * </p>
314 *
315 * <p>
316 * In addition, several convenience methods are offered to avoid unnecessary
317 * computations, namely {@link #getRight()} and {@link #getBottom()}.
318 * These methods return the coordinates of the right and bottom edges of the
319 * rectangle representing the view. For instance, calling {@link #getRight()}
320 * is similar to the following computation: <code>getLeft() + getWidth()</code>
321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
322 * </p>
323 *
324 * <a name="SizePaddingMargins"></a>
325 * <h3>Size, padding and margins</h3>
326 * <p>
327 * The size of a view is expressed with a width and a height. A view actually
328 * possess two pairs of width and height values.
329 * </p>
330 *
331 * <p>
332 * The first pair is known as <em>measured width</em> and
333 * <em>measured height</em>. These dimensions define how big a view wants to be
334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
336 * and {@link #getMeasuredHeight()}.
337 * </p>
338 *
339 * <p>
340 * The second pair is simply known as <em>width</em> and <em>height</em>, or
341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
342 * dimensions define the actual size of the view on screen, at drawing time and
343 * after layout. These values may, but do not have to, be different from the
344 * measured width and height. The width and height can be obtained by calling
345 * {@link #getWidth()} and {@link #getHeight()}.
346 * </p>
347 *
348 * <p>
349 * To measure its dimensions, a view takes into account its padding. The padding
350 * is expressed in pixels for the left, top, right and bottom parts of the view.
351 * Padding can be used to offset the content of the view by a specific amount of
352 * pixels. For instance, a left padding of 2 will push the view's content by
353 * 2 pixels to the right of the left edge. Padding can be set using the
354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
357 * {@link #getPaddingEnd()}.
358 * </p>
359 *
360 * <p>
361 * Even though a view can define a padding, it does not provide any support for
362 * margins. However, view groups provide such a support. Refer to
363 * {@link android.view.ViewGroup} and
364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
365 * </p>
366 *
367 * <a name="Layout"></a>
368 * <h3>Layout</h3>
369 * <p>
370 * Layout is a two pass process: a measure pass and a layout pass. The measuring
371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
372 * of the view tree. Each view pushes dimension specifications down the tree
373 * during the recursion. At the end of the measure pass, every view has stored
374 * its measurements. The second pass happens in
375 * {@link #layout(int,int,int,int)} and is also top-down. During
376 * this pass each parent is responsible for positioning all of its children
377 * using the sizes computed in the measure pass.
378 * </p>
379 *
380 * <p>
381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
382 * {@link #getMeasuredHeight()} values must be set, along with those for all of
383 * that view's descendants. A view's measured width and measured height values
384 * must respect the constraints imposed by the view's parents. This guarantees
385 * that at the end of the measure pass, all parents accept all of their
386 * children's measurements. A parent view may call measure() more than once on
387 * its children. For example, the parent may measure each child once with
388 * unspecified dimensions to find out how big they want to be, then call
389 * measure() on them again with actual numbers if the sum of all the children's
390 * unconstrained sizes is too big or too small.
391 * </p>
392 *
393 * <p>
394 * The measure pass uses two classes to communicate dimensions. The
395 * {@link MeasureSpec} class is used by views to tell their parents how they
396 * want to be measured and positioned. The base LayoutParams class just
397 * describes how big the view wants to be for both width and height. For each
398 * dimension, it can specify one of:
399 * <ul>
400 * <li> an exact number
401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
402 * (minus padding)
403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
404 * enclose its content (plus padding).
405 * </ul>
406 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
408 * an X and Y value.
409 * </p>
410 *
411 * <p>
412 * MeasureSpecs are used to push requirements down the tree from parent to
413 * child. A MeasureSpec can be in one of three modes:
414 * <ul>
415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
416 * of a child view. For example, a LinearLayout may call measure() on its child
417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
418 * tall the child view wants to be given a width of 240 pixels.
419 * <li>EXACTLY: This is used by the parent to impose an exact size on the
420 * child. The child must use this size, and guarantee that all of its
421 * descendants will fit within this size.
422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
423 * child. The child must gurantee that it and all of its descendants will fit
424 * within this size.
425 * </ul>
426 * </p>
427 *
428 * <p>
429 * To intiate a layout, call {@link #requestLayout}. This method is typically
430 * called by a view on itself when it believes that is can no longer fit within
431 * its current bounds.
432 * </p>
433 *
434 * <a name="Drawing"></a>
435 * <h3>Drawing</h3>
436 * <p>
437 * Drawing is handled by walking the tree and rendering each view that
438 * intersects the invalid region. Because the tree is traversed in-order,
439 * this means that parents will draw before (i.e., behind) their children, with
440 * siblings drawn in the order they appear in the tree.
441 * If you set a background drawable for a View, then the View will draw it for you
442 * before calling back to its <code>onDraw()</code> method.
443 * </p>
444 *
445 * <p>
446 * Note that the framework will not draw views that are not in the invalid region.
447 * </p>
448 *
449 * <p>
450 * To force a view to draw, call {@link #invalidate()}.
451 * </p>
452 *
453 * <a name="EventHandlingThreading"></a>
454 * <h3>Event Handling and Threading</h3>
455 * <p>
456 * The basic cycle of a view is as follows:
457 * <ol>
458 * <li>An event comes in and is dispatched to the appropriate view. The view
459 * handles the event and notifies any listeners.</li>
460 * <li>If in the course of processing the event, the view's bounds may need
461 * to be changed, the view will call {@link #requestLayout()}.</li>
462 * <li>Similarly, if in the course of processing the event the view's appearance
463 * may need to be changed, the view will call {@link #invalidate()}.</li>
464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
465 * the framework will take care of measuring, laying out, and drawing the tree
466 * as appropriate.</li>
467 * </ol>
468 * </p>
469 *
470 * <p><em>Note: The entire view tree is single threaded. You must always be on
471 * the UI thread when calling any method on any view.</em>
472 * If you are doing work on other threads and want to update the state of a view
473 * from that thread, you should use a {@link Handler}.
474 * </p>
475 *
476 * <a name="FocusHandling"></a>
477 * <h3>Focus Handling</h3>
478 * <p>
479 * The framework will handle routine focus movement in response to user input.
480 * This includes changing the focus as views are removed or hidden, or as new
481 * views become available. Views indicate their willingness to take focus
482 * through the {@link #isFocusable} method. To change whether a view can take
483 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
485 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
486 * </p>
487 * <p>
488 * Focus movement is based on an algorithm which finds the nearest neighbor in a
489 * given direction. In rare cases, the default algorithm may not match the
490 * intended behavior of the developer. In these situations, you can provide
491 * explicit overrides by using these XML attributes in the layout file:
492 * <pre>
493 * nextFocusDown
494 * nextFocusLeft
495 * nextFocusRight
496 * nextFocusUp
497 * </pre>
498 * </p>
499 *
500 *
501 * <p>
502 * To get a particular view to take focus, call {@link #requestFocus()}.
503 * </p>
504 *
505 * <a name="TouchMode"></a>
506 * <h3>Touch Mode</h3>
507 * <p>
508 * When a user is navigating a user interface via directional keys such as a D-pad, it is
509 * necessary to give focus to actionable items such as buttons so the user can see
510 * what will take input.  If the device has touch capabilities, however, and the user
511 * begins interacting with the interface by touching it, it is no longer necessary to
512 * always highlight, or give focus to, a particular view.  This motivates a mode
513 * for interaction named 'touch mode'.
514 * </p>
515 * <p>
516 * For a touch capable device, once the user touches the screen, the device
517 * will enter touch mode.  From this point onward, only views for which
518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
519 * Other views that are touchable, like buttons, will not take focus when touched; they will
520 * only fire the on click listeners.
521 * </p>
522 * <p>
523 * Any time a user hits a directional key, such as a D-pad direction, the view device will
524 * exit touch mode, and find a view to take focus, so that the user may resume interacting
525 * with the user interface without touching the screen again.
526 * </p>
527 * <p>
528 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
529 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
530 * </p>
531 *
532 * <a name="Scrolling"></a>
533 * <h3>Scrolling</h3>
534 * <p>
535 * The framework provides basic support for views that wish to internally
536 * scroll their content. This includes keeping track of the X and Y scroll
537 * offset as well as mechanisms for drawing scrollbars. See
538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
539 * {@link #awakenScrollBars()} for more details.
540 * </p>
541 *
542 * <a name="Tags"></a>
543 * <h3>Tags</h3>
544 * <p>
545 * Unlike IDs, tags are not used to identify views. Tags are essentially an
546 * extra piece of information that can be associated with a view. They are most
547 * often used as a convenience to store data related to views in the views
548 * themselves rather than by putting them in a separate structure.
549 * </p>
550 *
551 * <a name="Properties"></a>
552 * <h3>Properties</h3>
553 * <p>
554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
556 * available both in the {@link Property} form as well as in similarly-named setter/getter
557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
558 * be used to set persistent state associated with these rendering-related properties on the view.
559 * The properties and methods can also be used in conjunction with
560 * {@link android.animation.Animator Animator}-based animations, described more in the
561 * <a href="#Animation">Animation</a> section.
562 * </p>
563 *
564 * <a name="Animation"></a>
565 * <h3>Animation</h3>
566 * <p>
567 * Starting with Android 3.0, the preferred way of animating views is to use the
568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
573 * makes animating these View properties particularly easy and efficient.
574 * </p>
575 * <p>
576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
577 * You can attach an {@link Animation} object to a view using
578 * {@link #setAnimation(Animation)} or
579 * {@link #startAnimation(Animation)}. The animation can alter the scale,
580 * rotation, translation and alpha of a view over time. If the animation is
581 * attached to a view that has children, the animation will affect the entire
582 * subtree rooted by that node. When an animation is started, the framework will
583 * take care of redrawing the appropriate views until the animation completes.
584 * </p>
585 *
586 * <a name="Security"></a>
587 * <h3>Security</h3>
588 * <p>
589 * Sometimes it is essential that an application be able to verify that an action
590 * is being performed with the full knowledge and consent of the user, such as
591 * granting a permission request, making a purchase or clicking on an advertisement.
592 * Unfortunately, a malicious application could try to spoof the user into
593 * performing these actions, unaware, by concealing the intended purpose of the view.
594 * As a remedy, the framework offers a touch filtering mechanism that can be used to
595 * improve the security of views that provide access to sensitive functionality.
596 * </p><p>
597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
598 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
599 * will discard touches that are received whenever the view's window is obscured by
600 * another visible window.  As a result, the view will not receive touches whenever a
601 * toast, dialog or other window appears above the view's window.
602 * </p><p>
603 * For more fine-grained control over security, consider overriding the
604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
606 * </p>
607 *
608 * @attr ref android.R.styleable#View_alpha
609 * @attr ref android.R.styleable#View_background
610 * @attr ref android.R.styleable#View_clickable
611 * @attr ref android.R.styleable#View_contentDescription
612 * @attr ref android.R.styleable#View_drawingCacheQuality
613 * @attr ref android.R.styleable#View_duplicateParentState
614 * @attr ref android.R.styleable#View_id
615 * @attr ref android.R.styleable#View_requiresFadingEdge
616 * @attr ref android.R.styleable#View_fadeScrollbars
617 * @attr ref android.R.styleable#View_fadingEdgeLength
618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
619 * @attr ref android.R.styleable#View_fitsSystemWindows
620 * @attr ref android.R.styleable#View_isScrollContainer
621 * @attr ref android.R.styleable#View_focusable
622 * @attr ref android.R.styleable#View_focusableInTouchMode
623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
624 * @attr ref android.R.styleable#View_keepScreenOn
625 * @attr ref android.R.styleable#View_layerType
626 * @attr ref android.R.styleable#View_layoutDirection
627 * @attr ref android.R.styleable#View_longClickable
628 * @attr ref android.R.styleable#View_minHeight
629 * @attr ref android.R.styleable#View_minWidth
630 * @attr ref android.R.styleable#View_nextFocusDown
631 * @attr ref android.R.styleable#View_nextFocusLeft
632 * @attr ref android.R.styleable#View_nextFocusRight
633 * @attr ref android.R.styleable#View_nextFocusUp
634 * @attr ref android.R.styleable#View_onClick
635 * @attr ref android.R.styleable#View_padding
636 * @attr ref android.R.styleable#View_paddingBottom
637 * @attr ref android.R.styleable#View_paddingLeft
638 * @attr ref android.R.styleable#View_paddingRight
639 * @attr ref android.R.styleable#View_paddingTop
640 * @attr ref android.R.styleable#View_paddingStart
641 * @attr ref android.R.styleable#View_paddingEnd
642 * @attr ref android.R.styleable#View_saveEnabled
643 * @attr ref android.R.styleable#View_rotation
644 * @attr ref android.R.styleable#View_rotationX
645 * @attr ref android.R.styleable#View_rotationY
646 * @attr ref android.R.styleable#View_scaleX
647 * @attr ref android.R.styleable#View_scaleY
648 * @attr ref android.R.styleable#View_scrollX
649 * @attr ref android.R.styleable#View_scrollY
650 * @attr ref android.R.styleable#View_scrollbarSize
651 * @attr ref android.R.styleable#View_scrollbarStyle
652 * @attr ref android.R.styleable#View_scrollbars
653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
654 * @attr ref android.R.styleable#View_scrollbarFadeDuration
655 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
657 * @attr ref android.R.styleable#View_scrollbarThumbVertical
658 * @attr ref android.R.styleable#View_scrollbarTrackVertical
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
661 * @attr ref android.R.styleable#View_soundEffectsEnabled
662 * @attr ref android.R.styleable#View_tag
663 * @attr ref android.R.styleable#View_textAlignment
664 * @attr ref android.R.styleable#View_textDirection
665 * @attr ref android.R.styleable#View_transformPivotX
666 * @attr ref android.R.styleable#View_transformPivotY
667 * @attr ref android.R.styleable#View_translationX
668 * @attr ref android.R.styleable#View_translationY
669 * @attr ref android.R.styleable#View_visibility
670 *
671 * @see android.view.ViewGroup
672 */
673public class View implements Drawable.Callback, KeyEvent.Callback,
674        AccessibilityEventSource {
675    private static final boolean DBG = false;
676
677    /**
678     * The logging tag used by this class with android.util.Log.
679     */
680    protected static final String VIEW_LOG_TAG = "View";
681
682    /**
683     * When set to true, apps will draw debugging information about their layouts.
684     *
685     * @hide
686     */
687    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
688
689    /**
690     * Used to mark a View that has no ID.
691     */
692    public static final int NO_ID = -1;
693
694    private static boolean sUseBrokenMakeMeasureSpec = false;
695
696    /**
697     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
698     * calling setFlags.
699     */
700    private static final int NOT_FOCUSABLE = 0x00000000;
701
702    /**
703     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
704     * setFlags.
705     */
706    private static final int FOCUSABLE = 0x00000001;
707
708    /**
709     * Mask for use with setFlags indicating bits used for focus.
710     */
711    private static final int FOCUSABLE_MASK = 0x00000001;
712
713    /**
714     * This view will adjust its padding to fit sytem windows (e.g. status bar)
715     */
716    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
717
718    /**
719     * This view is visible.
720     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
721     * android:visibility}.
722     */
723    public static final int VISIBLE = 0x00000000;
724
725    /**
726     * This view is invisible, but it still takes up space for layout purposes.
727     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
728     * android:visibility}.
729     */
730    public static final int INVISIBLE = 0x00000004;
731
732    /**
733     * This view is invisible, and it doesn't take any space for layout
734     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
735     * android:visibility}.
736     */
737    public static final int GONE = 0x00000008;
738
739    /**
740     * Mask for use with setFlags indicating bits used for visibility.
741     * {@hide}
742     */
743    static final int VISIBILITY_MASK = 0x0000000C;
744
745    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
746
747    /**
748     * This view is enabled. Interpretation varies by subclass.
749     * Use with ENABLED_MASK when calling setFlags.
750     * {@hide}
751     */
752    static final int ENABLED = 0x00000000;
753
754    /**
755     * This view is disabled. Interpretation varies by subclass.
756     * Use with ENABLED_MASK when calling setFlags.
757     * {@hide}
758     */
759    static final int DISABLED = 0x00000020;
760
761   /**
762    * Mask for use with setFlags indicating bits used for indicating whether
763    * this view is enabled
764    * {@hide}
765    */
766    static final int ENABLED_MASK = 0x00000020;
767
768    /**
769     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
770     * called and further optimizations will be performed. It is okay to have
771     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
772     * {@hide}
773     */
774    static final int WILL_NOT_DRAW = 0x00000080;
775
776    /**
777     * Mask for use with setFlags indicating bits used for indicating whether
778     * this view is will draw
779     * {@hide}
780     */
781    static final int DRAW_MASK = 0x00000080;
782
783    /**
784     * <p>This view doesn't show scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_NONE = 0x00000000;
788
789    /**
790     * <p>This view shows horizontal scrollbars.</p>
791     * {@hide}
792     */
793    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
794
795    /**
796     * <p>This view shows vertical scrollbars.</p>
797     * {@hide}
798     */
799    static final int SCROLLBARS_VERTICAL = 0x00000200;
800
801    /**
802     * <p>Mask for use with setFlags indicating bits used for indicating which
803     * scrollbars are enabled.</p>
804     * {@hide}
805     */
806    static final int SCROLLBARS_MASK = 0x00000300;
807
808    /**
809     * Indicates that the view should filter touches when its window is obscured.
810     * Refer to the class comments for more information about this security feature.
811     * {@hide}
812     */
813    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
814
815    /**
816     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
817     * that they are optional and should be skipped if the window has
818     * requested system UI flags that ignore those insets for layout.
819     */
820    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
821
822    /**
823     * <p>This view doesn't show fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_NONE = 0x00000000;
827
828    /**
829     * <p>This view shows horizontal fading edges.</p>
830     * {@hide}
831     */
832    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
833
834    /**
835     * <p>This view shows vertical fading edges.</p>
836     * {@hide}
837     */
838    static final int FADING_EDGE_VERTICAL = 0x00002000;
839
840    /**
841     * <p>Mask for use with setFlags indicating bits used for indicating which
842     * fading edges are enabled.</p>
843     * {@hide}
844     */
845    static final int FADING_EDGE_MASK = 0x00003000;
846
847    /**
848     * <p>Indicates this view can be clicked. When clickable, a View reacts
849     * to clicks by notifying the OnClickListener.<p>
850     * {@hide}
851     */
852    static final int CLICKABLE = 0x00004000;
853
854    /**
855     * <p>Indicates this view is caching its drawing into a bitmap.</p>
856     * {@hide}
857     */
858    static final int DRAWING_CACHE_ENABLED = 0x00008000;
859
860    /**
861     * <p>Indicates that no icicle should be saved for this view.<p>
862     * {@hide}
863     */
864    static final int SAVE_DISABLED = 0x000010000;
865
866    /**
867     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
868     * property.</p>
869     * {@hide}
870     */
871    static final int SAVE_DISABLED_MASK = 0x000010000;
872
873    /**
874     * <p>Indicates that no drawing cache should ever be created for this view.<p>
875     * {@hide}
876     */
877    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
878
879    /**
880     * <p>Indicates this view can take / keep focus when int touch mode.</p>
881     * {@hide}
882     */
883    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
884
885    /**
886     * <p>Enables low quality mode for the drawing cache.</p>
887     */
888    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
889
890    /**
891     * <p>Enables high quality mode for the drawing cache.</p>
892     */
893    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
894
895    /**
896     * <p>Enables automatic quality mode for the drawing cache.</p>
897     */
898    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
899
900    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
901            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
902    };
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the cache
906     * quality property.</p>
907     * {@hide}
908     */
909    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
910
911    /**
912     * <p>
913     * Indicates this view can be long clicked. When long clickable, a View
914     * reacts to long clicks by notifying the OnLongClickListener or showing a
915     * context menu.
916     * </p>
917     * {@hide}
918     */
919    static final int LONG_CLICKABLE = 0x00200000;
920
921    /**
922     * <p>Indicates that this view gets its drawable states from its direct parent
923     * and ignores its original internal states.</p>
924     *
925     * @hide
926     */
927    static final int DUPLICATE_PARENT_STATE = 0x00400000;
928
929    /**
930     * The scrollbar style to display the scrollbars inside the content area,
931     * without increasing the padding. The scrollbars will be overlaid with
932     * translucency on the view's content.
933     */
934    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
935
936    /**
937     * The scrollbar style to display the scrollbars inside the padded area,
938     * increasing the padding of the view. The scrollbars will not overlap the
939     * content area of the view.
940     */
941    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
942
943    /**
944     * The scrollbar style to display the scrollbars at the edge of the view,
945     * without increasing the padding. The scrollbars will be overlaid with
946     * translucency.
947     */
948    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
949
950    /**
951     * The scrollbar style to display the scrollbars at the edge of the view,
952     * increasing the padding of the view. The scrollbars will only overlap the
953     * background, if any.
954     */
955    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
956
957    /**
958     * Mask to check if the scrollbar style is overlay or inset.
959     * {@hide}
960     */
961    static final int SCROLLBARS_INSET_MASK = 0x01000000;
962
963    /**
964     * Mask to check if the scrollbar style is inside or outside.
965     * {@hide}
966     */
967    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
968
969    /**
970     * Mask for scrollbar style.
971     * {@hide}
972     */
973    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
974
975    /**
976     * View flag indicating that the screen should remain on while the
977     * window containing this view is visible to the user.  This effectively
978     * takes care of automatically setting the WindowManager's
979     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
980     */
981    public static final int KEEP_SCREEN_ON = 0x04000000;
982
983    /**
984     * View flag indicating whether this view should have sound effects enabled
985     * for events such as clicking and touching.
986     */
987    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
988
989    /**
990     * View flag indicating whether this view should have haptic feedback
991     * enabled for events such as long presses.
992     */
993    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
994
995    /**
996     * <p>Indicates that the view hierarchy should stop saving state when
997     * it reaches this view.  If state saving is initiated immediately at
998     * the view, it will be allowed.
999     * {@hide}
1000     */
1001    static final int PARENT_SAVE_DISABLED = 0x20000000;
1002
1003    /**
1004     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1005     * {@hide}
1006     */
1007    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add all focusable Views regardless if they are focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_ALL = 0x00000000;
1014
1015    /**
1016     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1017     * should add only Views focusable in touch mode.
1018     */
1019    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1023     * item.
1024     */
1025    public static final int FOCUS_BACKWARD = 0x00000001;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1029     * item.
1030     */
1031    public static final int FOCUS_FORWARD = 0x00000002;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move focus to the left.
1035     */
1036    public static final int FOCUS_LEFT = 0x00000011;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move focus up.
1040     */
1041    public static final int FOCUS_UP = 0x00000021;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move focus to the right.
1045     */
1046    public static final int FOCUS_RIGHT = 0x00000042;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus down.
1050     */
1051    public static final int FOCUS_DOWN = 0x00000082;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1056     */
1057    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1058
1059    /**
1060     * Bits of {@link #getMeasuredWidthAndState()} and
1061     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1062     */
1063    public static final int MEASURED_STATE_MASK = 0xff000000;
1064
1065    /**
1066     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1067     * for functions that combine both width and height into a single int,
1068     * such as {@link #getMeasuredState()} and the childState argument of
1069     * {@link #resolveSizeAndState(int, int, int)}.
1070     */
1071    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1072
1073    /**
1074     * Bit of {@link #getMeasuredWidthAndState()} and
1075     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1076     * is smaller that the space the view would like to have.
1077     */
1078    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1079
1080    /**
1081     * Base View state sets
1082     */
1083    // Singles
1084    /**
1085     * Indicates the view has no states set. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] EMPTY_STATE_SET;
1093    /**
1094     * Indicates the view is enabled. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] ENABLED_STATE_SET;
1102    /**
1103     * Indicates the view is focused. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] FOCUSED_STATE_SET;
1111    /**
1112     * Indicates the view is selected. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     */
1119    protected static final int[] SELECTED_STATE_SET;
1120    /**
1121     * Indicates the view is pressed. States are used with
1122     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1123     * view depending on its state.
1124     *
1125     * @see android.graphics.drawable.Drawable
1126     * @see #getDrawableState()
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Accessibility event types that are dispatched for text population.
1488     */
1489    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1490            AccessibilityEvent.TYPE_VIEW_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1492            | AccessibilityEvent.TYPE_VIEW_SELECTED
1493            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1494            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1496            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1499            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1500            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1501
1502    /**
1503     * Temporary Rect currently for use in setBackground().  This will probably
1504     * be extended in the future to hold our own class with more than just
1505     * a Rect. :)
1506     */
1507    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1508
1509    /**
1510     * Map used to store views' tags.
1511     */
1512    private SparseArray<Object> mKeyedTags;
1513
1514    /**
1515     * The next available accessibility id.
1516     */
1517    private static int sNextAccessibilityViewId;
1518
1519    /**
1520     * The animation currently associated with this view.
1521     * @hide
1522     */
1523    protected Animation mCurrentAnimation = null;
1524
1525    /**
1526     * Width as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredWidth;
1531
1532    /**
1533     * Height as measured during measure pass.
1534     * {@hide}
1535     */
1536    @ViewDebug.ExportedProperty(category = "measurement")
1537    int mMeasuredHeight;
1538
1539    /**
1540     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1541     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1542     * its display list. This flag, used only when hw accelerated, allows us to clear the
1543     * flag while retaining this information until it's needed (at getDisplayList() time and
1544     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1545     *
1546     * {@hide}
1547     */
1548    boolean mRecreateDisplayList = false;
1549
1550    /**
1551     * The view's identifier.
1552     * {@hide}
1553     *
1554     * @see #setId(int)
1555     * @see #getId()
1556     */
1557    @ViewDebug.ExportedProperty(resolveId = true)
1558    int mID = NO_ID;
1559
1560    /**
1561     * The stable ID of this view for accessibility purposes.
1562     */
1563    int mAccessibilityViewId = NO_ID;
1564
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1568
1569    /**
1570     * The view's tag.
1571     * {@hide}
1572     *
1573     * @see #setTag(Object)
1574     * @see #getTag()
1575     */
1576    protected Object mTag;
1577
1578    private Scene mCurrentScene = null;
1579
1580    // for mPrivateFlags:
1581    /** {@hide} */
1582    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1583    /** {@hide} */
1584    static final int PFLAG_FOCUSED                     = 0x00000002;
1585    /** {@hide} */
1586    static final int PFLAG_SELECTED                    = 0x00000004;
1587    /** {@hide} */
1588    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1589    /** {@hide} */
1590    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1591    /** {@hide} */
1592    static final int PFLAG_DRAWN                       = 0x00000020;
1593    /**
1594     * When this flag is set, this view is running an animation on behalf of its
1595     * children and should therefore not cancel invalidate requests, even if they
1596     * lie outside of this view's bounds.
1597     *
1598     * {@hide}
1599     */
1600    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1601    /** {@hide} */
1602    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1603    /** {@hide} */
1604    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1605    /** {@hide} */
1606    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1607    /** {@hide} */
1608    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1609    /** {@hide} */
1610    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1611    /** {@hide} */
1612    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1613    /** {@hide} */
1614    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1615
1616    private static final int PFLAG_PRESSED             = 0x00004000;
1617
1618    /** {@hide} */
1619    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1620    /**
1621     * Flag used to indicate that this view should be drawn once more (and only once
1622     * more) after its animation has completed.
1623     * {@hide}
1624     */
1625    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1626
1627    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1628
1629    /**
1630     * Indicates that the View returned true when onSetAlpha() was called and that
1631     * the alpha must be restored.
1632     * {@hide}
1633     */
1634    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1640
1641    /**
1642     * Set by {@link #setScrollContainer(boolean)}.
1643     */
1644    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated (fully or partially.)
1648     *
1649     * @hide
1650     */
1651    static final int PFLAG_DIRTY                       = 0x00200000;
1652
1653    /**
1654     * View flag indicating whether this view was invalidated by an opaque
1655     * invalidate request.
1656     *
1657     * @hide
1658     */
1659    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1660
1661    /**
1662     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1663     *
1664     * @hide
1665     */
1666    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1667
1668    /**
1669     * Indicates whether the background is opaque.
1670     *
1671     * @hide
1672     */
1673    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1674
1675    /**
1676     * Indicates whether the scrollbars are opaque.
1677     *
1678     * @hide
1679     */
1680    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1681
1682    /**
1683     * Indicates whether the view is opaque.
1684     *
1685     * @hide
1686     */
1687    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1688
1689    /**
1690     * Indicates a prepressed state;
1691     * the short time between ACTION_DOWN and recognizing
1692     * a 'real' press. Prepressed is used to recognize quick taps
1693     * even when they are shorter than ViewConfiguration.getTapTimeout().
1694     *
1695     * @hide
1696     */
1697    private static final int PFLAG_PREPRESSED          = 0x02000000;
1698
1699    /**
1700     * Indicates whether the view is temporarily detached.
1701     *
1702     * @hide
1703     */
1704    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1705
1706    /**
1707     * Indicates that we should awaken scroll bars once attached
1708     *
1709     * @hide
1710     */
1711    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1712
1713    /**
1714     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1715     * @hide
1716     */
1717    private static final int PFLAG_HOVERED             = 0x10000000;
1718
1719    /**
1720     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1721     * for transform operations
1722     *
1723     * @hide
1724     */
1725    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1726
1727    /** {@hide} */
1728    static final int PFLAG_ACTIVATED                   = 0x40000000;
1729
1730    /**
1731     * Indicates that this view was specifically invalidated, not just dirtied because some
1732     * child view was invalidated. The flag is used to determine when we need to recreate
1733     * a view's display list (as opposed to just returning a reference to its existing
1734     * display list).
1735     *
1736     * @hide
1737     */
1738    static final int PFLAG_INVALIDATED                 = 0x80000000;
1739
1740    /**
1741     * Masks for mPrivateFlags2, as generated by dumpFlags():
1742     *
1743     * -------|-------|-------|-------|
1744     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1745     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1746     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1747     *                               1  PFLAG2_DRAG_HOVERED
1748     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1749     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1750     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1751     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1752     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1753     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1754     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1755     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1756     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1757     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1758     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1759     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1760     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1761     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1762     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1763     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1764     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1765     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1766     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1767     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1768     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1769     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1770     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1771     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1772     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1773     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1774     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1775     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1776     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1777     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1778     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1779     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1780     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1781     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1782     *   1                              PFLAG2_PADDING_RESOLVED
1783     * -------|-------|-------|-------|
1784     */
1785
1786    /**
1787     * Indicates that this view has reported that it can accept the current drag's content.
1788     * Cleared when the drag operation concludes.
1789     * @hide
1790     */
1791    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1792
1793    /**
1794     * Indicates that this view is currently directly under the drag location in a
1795     * drag-and-drop operation involving content that it can accept.  Cleared when
1796     * the drag exits the view, or when the drag operation concludes.
1797     * @hide
1798     */
1799    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1800
1801    /**
1802     * Horizontal layout direction of this view is from Left to Right.
1803     * Use with {@link #setLayoutDirection}.
1804     */
1805    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1806
1807    /**
1808     * Horizontal layout direction of this view is from Right to Left.
1809     * Use with {@link #setLayoutDirection}.
1810     */
1811    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1812
1813    /**
1814     * Horizontal layout direction of this view is inherited from its parent.
1815     * Use with {@link #setLayoutDirection}.
1816     */
1817    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1818
1819    /**
1820     * Horizontal layout direction of this view is from deduced from the default language
1821     * script for the locale. Use with {@link #setLayoutDirection}.
1822     */
1823    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1824
1825    /**
1826     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1827     * @hide
1828     */
1829    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for horizontal layout direction.
1833     * @hide
1834     */
1835    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /**
1838     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1839     * right-to-left direction.
1840     * @hide
1841     */
1842    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1843
1844    /**
1845     * Indicates whether the view horizontal layout direction has been resolved.
1846     * @hide
1847     */
1848    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1849
1850    /**
1851     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1852     * @hide
1853     */
1854    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1855            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1856
1857    /*
1858     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1859     * flag value.
1860     * @hide
1861     */
1862    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1863            LAYOUT_DIRECTION_LTR,
1864            LAYOUT_DIRECTION_RTL,
1865            LAYOUT_DIRECTION_INHERIT,
1866            LAYOUT_DIRECTION_LOCALE
1867    };
1868
1869    /**
1870     * Default horizontal layout direction.
1871     */
1872    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1873
1874    /**
1875     * Default horizontal layout direction.
1876     * @hide
1877     */
1878    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1879
1880    /**
1881     * Indicates that the view is tracking some sort of transient state
1882     * that the app should not need to be aware of, but that the framework
1883     * should take special care to preserve.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1888
1889    /**
1890     * Text direction is inherited thru {@link ViewGroup}
1891     */
1892    public static final int TEXT_DIRECTION_INHERIT = 0;
1893
1894    /**
1895     * Text direction is using "first strong algorithm". The first strong directional character
1896     * determines the paragraph direction. If there is no strong directional character, the
1897     * paragraph direction is the view's resolved layout direction.
1898     */
1899    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1900
1901    /**
1902     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1903     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1904     * If there are neither, the paragraph direction is the view's resolved layout direction.
1905     */
1906    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1907
1908    /**
1909     * Text direction is forced to LTR.
1910     */
1911    public static final int TEXT_DIRECTION_LTR = 3;
1912
1913    /**
1914     * Text direction is forced to RTL.
1915     */
1916    public static final int TEXT_DIRECTION_RTL = 4;
1917
1918    /**
1919     * Text direction is coming from the system Locale.
1920     */
1921    public static final int TEXT_DIRECTION_LOCALE = 5;
1922
1923    /**
1924     * Default text direction is inherited
1925     */
1926    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1927
1928    /**
1929     * Default resolved text direction
1930     * @hide
1931     */
1932    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1933
1934    /**
1935     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1936     * @hide
1937     */
1938    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1939
1940    /**
1941     * Mask for use with private flags indicating bits used for text direction.
1942     * @hide
1943     */
1944    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1945            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1946
1947    /**
1948     * Array of text direction flags for mapping attribute "textDirection" to correct
1949     * flag value.
1950     * @hide
1951     */
1952    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1953            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1958            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1959    };
1960
1961    /**
1962     * Indicates whether the view text direction has been resolved.
1963     * @hide
1964     */
1965    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1966            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1967
1968    /**
1969     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1970     * @hide
1971     */
1972    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1973
1974    /**
1975     * Mask for use with private flags indicating bits used for resolved text direction.
1976     * @hide
1977     */
1978    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1979            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1980
1981    /**
1982     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1983     * @hide
1984     */
1985    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1986            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1987
1988    /*
1989     * Default text alignment. The text alignment of this View is inherited from its parent.
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1993
1994    /**
1995     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1996     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     */
2000    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2001
2002    /**
2003     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2004     *
2005     * Use with {@link #setTextAlignment(int)}
2006     */
2007    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2008
2009    /**
2010     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2015
2016    /**
2017     * Center the paragraph, e.g. ALIGN_CENTER.
2018     *
2019     * Use with {@link #setTextAlignment(int)}
2020     */
2021    public static final int TEXT_ALIGNMENT_CENTER = 4;
2022
2023    /**
2024     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2025     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2026     *
2027     * Use with {@link #setTextAlignment(int)}
2028     */
2029    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2030
2031    /**
2032     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2033     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2034     *
2035     * Use with {@link #setTextAlignment(int)}
2036     */
2037    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2038
2039    /**
2040     * Default text alignment is inherited
2041     */
2042    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2043
2044    /**
2045     * Default resolved text alignment
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2049
2050    /**
2051      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2052      * @hide
2053      */
2054    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2055
2056    /**
2057      * Mask for use with private flags indicating bits used for text alignment.
2058      * @hide
2059      */
2060    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Array of text direction flags for mapping attribute "textAlignment" to correct
2064     * flag value.
2065     * @hide
2066     */
2067    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2068            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2074            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2075    };
2076
2077    /**
2078     * Indicates whether the view text alignment has been resolved.
2079     * @hide
2080     */
2081    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2082
2083    /**
2084     * Bit shift to get the resolved text alignment.
2085     * @hide
2086     */
2087    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2088
2089    /**
2090     * Mask for use with private flags indicating bits used for text alignment.
2091     * @hide
2092     */
2093    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2094            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2095
2096    /**
2097     * Indicates whether if the view text alignment has been resolved to gravity
2098     */
2099    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2100            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2101
2102    // Accessiblity constants for mPrivateFlags2
2103
2104    /**
2105     * Shift for the bits in {@link #mPrivateFlags2} related to the
2106     * "importantForAccessibility" attribute.
2107     */
2108    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2109
2110    /**
2111     * Automatically determine whether a view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2114
2115    /**
2116     * The view is important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2119
2120    /**
2121     * The view is not important for accessibility.
2122     */
2123    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2124
2125    /**
2126     * The default whether the view is important for accessibility.
2127     */
2128    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2129
2130    /**
2131     * Mask for obtainig the bits which specify how to determine
2132     * whether a view is important for accessibility.
2133     */
2134    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2135        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2136        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view has accessibility focus.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2142
2143    /**
2144     * Flag whether the accessibility state of the subtree rooted at this view changed.
2145     */
2146    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2147
2148    /**
2149     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2150     * is used to check whether later changes to the view's transform should invalidate the
2151     * view to force the quickReject test to run again.
2152     */
2153    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2154
2155    /**
2156     * Flag indicating that start/end padding has been resolved into left/right padding
2157     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2158     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2159     * during measurement. In some special cases this is required such as when an adapter-based
2160     * view measures prospective children without attaching them to a window.
2161     */
2162    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2163
2164    /**
2165     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2166     */
2167    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2168
2169    /**
2170     * Group of bits indicating that RTL properties resolution is done.
2171     */
2172    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_DIRECTION_RESOLVED |
2174            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2175            PFLAG2_PADDING_RESOLVED |
2176            PFLAG2_DRAWABLE_RESOLVED;
2177
2178    // There are a couple of flags left in mPrivateFlags2
2179
2180    /* End of masks for mPrivateFlags2 */
2181
2182    /* Masks for mPrivateFlags3 */
2183
2184    /**
2185     * Flag indicating that view has a transform animation set on it. This is used to track whether
2186     * an animation is cleared between successive frames, in order to tell the associated
2187     * DisplayList to clear its animation matrix.
2188     */
2189    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2190
2191    /**
2192     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2193     * animation is cleared between successive frames, in order to tell the associated
2194     * DisplayList to restore its alpha value.
2195     */
2196    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2197
2198    /**
2199     * Flag indicating that the view has been through at least one layout since it
2200     * was last attached to a window.
2201     */
2202    static final int PFLAG3_IS_LAID_OUT = 0x4;
2203
2204    /**
2205     * Flag indicating that a call to measure() was skipped and should be done
2206     * instead when layout() is invoked.
2207     */
2208    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2209
2210
2211    /* End of masks for mPrivateFlags3 */
2212
2213    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2214
2215    /**
2216     * Always allow a user to over-scroll this view, provided it is a
2217     * view that can scroll.
2218     *
2219     * @see #getOverScrollMode()
2220     * @see #setOverScrollMode(int)
2221     */
2222    public static final int OVER_SCROLL_ALWAYS = 0;
2223
2224    /**
2225     * Allow a user to over-scroll this view only if the content is large
2226     * enough to meaningfully scroll, provided it is a view that can scroll.
2227     *
2228     * @see #getOverScrollMode()
2229     * @see #setOverScrollMode(int)
2230     */
2231    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2232
2233    /**
2234     * Never allow a user to over-scroll this view.
2235     *
2236     * @see #getOverScrollMode()
2237     * @see #setOverScrollMode(int)
2238     */
2239    public static final int OVER_SCROLL_NEVER = 2;
2240
2241    /**
2242     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2243     * requested the system UI (status bar) to be visible (the default).
2244     *
2245     * @see #setSystemUiVisibility(int)
2246     */
2247    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2248
2249    /**
2250     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2251     * system UI to enter an unobtrusive "low profile" mode.
2252     *
2253     * <p>This is for use in games, book readers, video players, or any other
2254     * "immersive" application where the usual system chrome is deemed too distracting.
2255     *
2256     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2257     *
2258     * @see #setSystemUiVisibility(int)
2259     */
2260    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2261
2262    /**
2263     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2264     * system navigation be temporarily hidden.
2265     *
2266     * <p>This is an even less obtrusive state than that called for by
2267     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2268     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2269     * those to disappear. This is useful (in conjunction with the
2270     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2271     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2272     * window flags) for displaying content using every last pixel on the display.
2273     *
2274     * <p>There is a limitation: because navigation controls are so important, the least user
2275     * interaction will cause them to reappear immediately.  When this happens, both
2276     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2277     * so that both elements reappear at the same time.
2278     *
2279     * @see #setSystemUiVisibility(int)
2280     */
2281    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2282
2283    /**
2284     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2285     * into the normal fullscreen mode so that its content can take over the screen
2286     * while still allowing the user to interact with the application.
2287     *
2288     * <p>This has the same visual effect as
2289     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2290     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2291     * meaning that non-critical screen decorations (such as the status bar) will be
2292     * hidden while the user is in the View's window, focusing the experience on
2293     * that content.  Unlike the window flag, if you are using ActionBar in
2294     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2295     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2296     * hide the action bar.
2297     *
2298     * <p>This approach to going fullscreen is best used over the window flag when
2299     * it is a transient state -- that is, the application does this at certain
2300     * points in its user interaction where it wants to allow the user to focus
2301     * on content, but not as a continuous state.  For situations where the application
2302     * would like to simply stay full screen the entire time (such as a game that
2303     * wants to take over the screen), the
2304     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2305     * is usually a better approach.  The state set here will be removed by the system
2306     * in various situations (such as the user moving to another application) like
2307     * the other system UI states.
2308     *
2309     * <p>When using this flag, the application should provide some easy facility
2310     * for the user to go out of it.  A common example would be in an e-book
2311     * reader, where tapping on the screen brings back whatever screen and UI
2312     * decorations that had been hidden while the user was immersed in reading
2313     * the book.
2314     *
2315     * @see #setSystemUiVisibility(int)
2316     */
2317    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2318
2319    /**
2320     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2321     * flags, we would like a stable view of the content insets given to
2322     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2323     * will always represent the worst case that the application can expect
2324     * as a continuous state.  In the stock Android UI this is the space for
2325     * the system bar, nav bar, and status bar, but not more transient elements
2326     * such as an input method.
2327     *
2328     * The stable layout your UI sees is based on the system UI modes you can
2329     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2330     * then you will get a stable layout for changes of the
2331     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2332     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2333     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2334     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2335     * with a stable layout.  (Note that you should avoid using
2336     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2337     *
2338     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2339     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2340     * then a hidden status bar will be considered a "stable" state for purposes
2341     * here.  This allows your UI to continually hide the status bar, while still
2342     * using the system UI flags to hide the action bar while still retaining
2343     * a stable layout.  Note that changing the window fullscreen flag will never
2344     * provide a stable layout for a clean transition.
2345     *
2346     * <p>If you are using ActionBar in
2347     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2348     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2349     * insets it adds to those given to the application.
2350     */
2351    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2352
2353    /**
2354     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2355     * to be layed out as if it has requested
2356     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2357     * allows it to avoid artifacts when switching in and out of that mode, at
2358     * the expense that some of its user interface may be covered by screen
2359     * decorations when they are shown.  You can perform layout of your inner
2360     * UI elements to account for the navigation system UI through the
2361     * {@link #fitSystemWindows(Rect)} method.
2362     */
2363    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2364
2365    /**
2366     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2367     * to be layed out as if it has requested
2368     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2369     * allows it to avoid artifacts when switching in and out of that mode, at
2370     * the expense that some of its user interface may be covered by screen
2371     * decorations when they are shown.  You can perform layout of your inner
2372     * UI elements to account for non-fullscreen system UI through the
2373     * {@link #fitSystemWindows(Rect)} method.
2374     */
2375    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2376
2377    /**
2378     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2379     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2380     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2381     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2382     * semi-transparent system bars while also delivering the event.
2383     */
2384    public static final int SYSTEM_UI_FLAG_ALLOW_TRANSIENT = 0x00000800;
2385
2386    /**
2387     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2388     * transparency.
2389     *
2390     * <p>The transparency request may be denied if the bar is in another mode with a specific
2391     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2392     */
2393    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2394
2395    /**
2396     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2397     * transparency.
2398     *
2399     * <p>The transparency request may be denied if the bar is in another mode with a specific
2400     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2401     */
2402    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2403
2404    /**
2405     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2406     */
2407    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2408
2409    /**
2410     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2411     */
2412    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2413
2414    /**
2415     * @hide
2416     *
2417     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2418     * out of the public fields to keep the undefined bits out of the developer's way.
2419     *
2420     * Flag to make the status bar not expandable.  Unless you also
2421     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2422     */
2423    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide notification icons and scrolling ticker text.
2432     */
2433    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2434
2435    /**
2436     * @hide
2437     *
2438     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2439     * out of the public fields to keep the undefined bits out of the developer's way.
2440     *
2441     * Flag to disable incoming notification alerts.  This will not block
2442     * icons, but it will block sound, vibrating and other visual or aural notifications.
2443     */
2444    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2445
2446    /**
2447     * @hide
2448     *
2449     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2450     * out of the public fields to keep the undefined bits out of the developer's way.
2451     *
2452     * Flag to hide only the scrolling ticker.  Note that
2453     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2454     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2455     */
2456    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide the center system info area.
2465     */
2466    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2467
2468    /**
2469     * @hide
2470     *
2471     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2472     * out of the public fields to keep the undefined bits out of the developer's way.
2473     *
2474     * Flag to hide only the home button.  Don't use this
2475     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2476     */
2477    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2478
2479    /**
2480     * @hide
2481     *
2482     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2483     * out of the public fields to keep the undefined bits out of the developer's way.
2484     *
2485     * Flag to hide only the back button. Don't use this
2486     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2487     */
2488    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2489
2490    /**
2491     * @hide
2492     *
2493     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2494     * out of the public fields to keep the undefined bits out of the developer's way.
2495     *
2496     * Flag to hide only the clock.  You might use this if your activity has
2497     * its own clock making the status bar's clock redundant.
2498     */
2499    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2500
2501    /**
2502     * @hide
2503     *
2504     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2505     * out of the public fields to keep the undefined bits out of the developer's way.
2506     *
2507     * Flag to hide only the recent apps button. Don't use this
2508     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2509     */
2510    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2511
2512    /**
2513     * @hide
2514     *
2515     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2516     * out of the public fields to keep the undefined bits out of the developer's way.
2517     *
2518     * Flag to disable the global search gesture. Don't use this
2519     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2520     */
2521    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2522
2523    /**
2524     * @hide
2525     *
2526     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2527     * out of the public fields to keep the undefined bits out of the developer's way.
2528     *
2529     * Flag to specify that the status bar is displayed in transient mode.
2530     */
2531    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2532
2533    /**
2534     * @hide
2535     *
2536     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2537     * out of the public fields to keep the undefined bits out of the developer's way.
2538     *
2539     * Flag to specify that the navigation bar is displayed in transient mode.
2540     */
2541    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2542
2543    /**
2544     * @hide
2545     *
2546     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2547     * out of the public fields to keep the undefined bits out of the developer's way.
2548     *
2549     * Flag to specify that the hidden status bar would like to be shown.
2550     */
2551    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2552
2553    /**
2554     * @hide
2555     *
2556     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2557     * out of the public fields to keep the undefined bits out of the developer's way.
2558     *
2559     * Flag to specify that the hidden navigation bar would like to be shown.
2560     */
2561    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2562
2563    /**
2564     * @hide
2565     */
2566    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2567
2568    /**
2569     * These are the system UI flags that can be cleared by events outside
2570     * of an application.  Currently this is just the ability to tap on the
2571     * screen while hiding the navigation bar to have it return.
2572     * @hide
2573     */
2574    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2575            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2576            | SYSTEM_UI_FLAG_FULLSCREEN;
2577
2578    /**
2579     * Flags that can impact the layout in relation to system UI.
2580     */
2581    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2582            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2583            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2584
2585    /**
2586     * Find views that render the specified text.
2587     *
2588     * @see #findViewsWithText(ArrayList, CharSequence, int)
2589     */
2590    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2591
2592    /**
2593     * Find find views that contain the specified content description.
2594     *
2595     * @see #findViewsWithText(ArrayList, CharSequence, int)
2596     */
2597    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2598
2599    /**
2600     * Find views that contain {@link AccessibilityNodeProvider}. Such
2601     * a View is a root of virtual view hierarchy and may contain the searched
2602     * text. If this flag is set Views with providers are automatically
2603     * added and it is a responsibility of the client to call the APIs of
2604     * the provider to determine whether the virtual tree rooted at this View
2605     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2606     * represeting the virtual views with this text.
2607     *
2608     * @see #findViewsWithText(ArrayList, CharSequence, int)
2609     *
2610     * @hide
2611     */
2612    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2613
2614    /**
2615     * The undefined cursor position.
2616     *
2617     * @hide
2618     */
2619    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2620
2621    /**
2622     * Indicates that the screen has changed state and is now off.
2623     *
2624     * @see #onScreenStateChanged(int)
2625     */
2626    public static final int SCREEN_STATE_OFF = 0x0;
2627
2628    /**
2629     * Indicates that the screen has changed state and is now on.
2630     *
2631     * @see #onScreenStateChanged(int)
2632     */
2633    public static final int SCREEN_STATE_ON = 0x1;
2634
2635    /**
2636     * Controls the over-scroll mode for this view.
2637     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2638     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2639     * and {@link #OVER_SCROLL_NEVER}.
2640     */
2641    private int mOverScrollMode;
2642
2643    /**
2644     * The parent this view is attached to.
2645     * {@hide}
2646     *
2647     * @see #getParent()
2648     */
2649    protected ViewParent mParent;
2650
2651    /**
2652     * {@hide}
2653     */
2654    AttachInfo mAttachInfo;
2655
2656    /**
2657     * {@hide}
2658     */
2659    @ViewDebug.ExportedProperty(flagMapping = {
2660        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2661                name = "FORCE_LAYOUT"),
2662        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2663                name = "LAYOUT_REQUIRED"),
2664        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2665            name = "DRAWING_CACHE_INVALID", outputIf = false),
2666        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2667        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2668        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2669        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2670    })
2671    int mPrivateFlags;
2672    int mPrivateFlags2;
2673    int mPrivateFlags3;
2674
2675    /**
2676     * This view's request for the visibility of the status bar.
2677     * @hide
2678     */
2679    @ViewDebug.ExportedProperty(flagMapping = {
2680        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2681                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2682                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2683        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2684                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2685                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2686        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2687                                equals = SYSTEM_UI_FLAG_VISIBLE,
2688                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2689    })
2690    int mSystemUiVisibility;
2691
2692    /**
2693     * Reference count for transient state.
2694     * @see #setHasTransientState(boolean)
2695     */
2696    int mTransientStateCount = 0;
2697
2698    /**
2699     * Count of how many windows this view has been attached to.
2700     */
2701    int mWindowAttachCount;
2702
2703    /**
2704     * The layout parameters associated with this view and used by the parent
2705     * {@link android.view.ViewGroup} to determine how this view should be
2706     * laid out.
2707     * {@hide}
2708     */
2709    protected ViewGroup.LayoutParams mLayoutParams;
2710
2711    /**
2712     * The view flags hold various views states.
2713     * {@hide}
2714     */
2715    @ViewDebug.ExportedProperty
2716    int mViewFlags;
2717
2718    static class TransformationInfo {
2719        /**
2720         * The transform matrix for the View. This transform is calculated internally
2721         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2722         * is used by default. Do *not* use this variable directly; instead call
2723         * getMatrix(), which will automatically recalculate the matrix if necessary
2724         * to get the correct matrix based on the latest rotation and scale properties.
2725         */
2726        private final Matrix mMatrix = new Matrix();
2727
2728        /**
2729         * The transform matrix for the View. This transform is calculated internally
2730         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2731         * is used by default. Do *not* use this variable directly; instead call
2732         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2733         * to get the correct matrix based on the latest rotation and scale properties.
2734         */
2735        private Matrix mInverseMatrix;
2736
2737        /**
2738         * An internal variable that tracks whether we need to recalculate the
2739         * transform matrix, based on whether the rotation or scaleX/Y properties
2740         * have changed since the matrix was last calculated.
2741         */
2742        boolean mMatrixDirty = false;
2743
2744        /**
2745         * An internal variable that tracks whether we need to recalculate the
2746         * transform matrix, based on whether the rotation or scaleX/Y properties
2747         * have changed since the matrix was last calculated.
2748         */
2749        private boolean mInverseMatrixDirty = true;
2750
2751        /**
2752         * A variable that tracks whether we need to recalculate the
2753         * transform matrix, based on whether the rotation or scaleX/Y properties
2754         * have changed since the matrix was last calculated. This variable
2755         * is only valid after a call to updateMatrix() or to a function that
2756         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2757         */
2758        private boolean mMatrixIsIdentity = true;
2759
2760        /**
2761         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2762         */
2763        private Camera mCamera = null;
2764
2765        /**
2766         * This matrix is used when computing the matrix for 3D rotations.
2767         */
2768        private Matrix matrix3D = null;
2769
2770        /**
2771         * These prev values are used to recalculate a centered pivot point when necessary. The
2772         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2773         * set), so thes values are only used then as well.
2774         */
2775        private int mPrevWidth = -1;
2776        private int mPrevHeight = -1;
2777
2778        /**
2779         * The degrees rotation around the vertical axis through the pivot point.
2780         */
2781        @ViewDebug.ExportedProperty
2782        float mRotationY = 0f;
2783
2784        /**
2785         * The degrees rotation around the horizontal axis through the pivot point.
2786         */
2787        @ViewDebug.ExportedProperty
2788        float mRotationX = 0f;
2789
2790        /**
2791         * The degrees rotation around the pivot point.
2792         */
2793        @ViewDebug.ExportedProperty
2794        float mRotation = 0f;
2795
2796        /**
2797         * The amount of translation of the object away from its left property (post-layout).
2798         */
2799        @ViewDebug.ExportedProperty
2800        float mTranslationX = 0f;
2801
2802        /**
2803         * The amount of translation of the object away from its top property (post-layout).
2804         */
2805        @ViewDebug.ExportedProperty
2806        float mTranslationY = 0f;
2807
2808        /**
2809         * The amount of scale in the x direction around the pivot point. A
2810         * value of 1 means no scaling is applied.
2811         */
2812        @ViewDebug.ExportedProperty
2813        float mScaleX = 1f;
2814
2815        /**
2816         * The amount of scale in the y direction around the pivot point. A
2817         * value of 1 means no scaling is applied.
2818         */
2819        @ViewDebug.ExportedProperty
2820        float mScaleY = 1f;
2821
2822        /**
2823         * The x location of the point around which the view is rotated and scaled.
2824         */
2825        @ViewDebug.ExportedProperty
2826        float mPivotX = 0f;
2827
2828        /**
2829         * The y location of the point around which the view is rotated and scaled.
2830         */
2831        @ViewDebug.ExportedProperty
2832        float mPivotY = 0f;
2833
2834        /**
2835         * The opacity of the View. This is a value from 0 to 1, where 0 means
2836         * completely transparent and 1 means completely opaque.
2837         */
2838        @ViewDebug.ExportedProperty
2839        float mAlpha = 1f;
2840    }
2841
2842    TransformationInfo mTransformationInfo;
2843
2844    /**
2845     * Current clip bounds. to which all drawing of this view are constrained.
2846     */
2847    private Rect mClipBounds = null;
2848
2849    private boolean mLastIsOpaque;
2850
2851    /**
2852     * Convenience value to check for float values that are close enough to zero to be considered
2853     * zero.
2854     */
2855    private static final float NONZERO_EPSILON = .001f;
2856
2857    /**
2858     * The distance in pixels from the left edge of this view's parent
2859     * to the left edge of this view.
2860     * {@hide}
2861     */
2862    @ViewDebug.ExportedProperty(category = "layout")
2863    protected int mLeft;
2864    /**
2865     * The distance in pixels from the left edge of this view's parent
2866     * to the right edge of this view.
2867     * {@hide}
2868     */
2869    @ViewDebug.ExportedProperty(category = "layout")
2870    protected int mRight;
2871    /**
2872     * The distance in pixels from the top edge of this view's parent
2873     * to the top edge of this view.
2874     * {@hide}
2875     */
2876    @ViewDebug.ExportedProperty(category = "layout")
2877    protected int mTop;
2878    /**
2879     * The distance in pixels from the top edge of this view's parent
2880     * to the bottom edge of this view.
2881     * {@hide}
2882     */
2883    @ViewDebug.ExportedProperty(category = "layout")
2884    protected int mBottom;
2885
2886    /**
2887     * The offset, in pixels, by which the content of this view is scrolled
2888     * horizontally.
2889     * {@hide}
2890     */
2891    @ViewDebug.ExportedProperty(category = "scrolling")
2892    protected int mScrollX;
2893    /**
2894     * The offset, in pixels, by which the content of this view is scrolled
2895     * vertically.
2896     * {@hide}
2897     */
2898    @ViewDebug.ExportedProperty(category = "scrolling")
2899    protected int mScrollY;
2900
2901    /**
2902     * The left padding in pixels, that is the distance in pixels between the
2903     * left edge of this view and the left edge of its content.
2904     * {@hide}
2905     */
2906    @ViewDebug.ExportedProperty(category = "padding")
2907    protected int mPaddingLeft = 0;
2908    /**
2909     * The right padding in pixels, that is the distance in pixels between the
2910     * right edge of this view and the right edge of its content.
2911     * {@hide}
2912     */
2913    @ViewDebug.ExportedProperty(category = "padding")
2914    protected int mPaddingRight = 0;
2915    /**
2916     * The top padding in pixels, that is the distance in pixels between the
2917     * top edge of this view and the top edge of its content.
2918     * {@hide}
2919     */
2920    @ViewDebug.ExportedProperty(category = "padding")
2921    protected int mPaddingTop;
2922    /**
2923     * The bottom padding in pixels, that is the distance in pixels between the
2924     * bottom edge of this view and the bottom edge of its content.
2925     * {@hide}
2926     */
2927    @ViewDebug.ExportedProperty(category = "padding")
2928    protected int mPaddingBottom;
2929
2930    /**
2931     * The layout insets in pixels, that is the distance in pixels between the
2932     * visible edges of this view its bounds.
2933     */
2934    private Insets mLayoutInsets;
2935
2936    /**
2937     * Briefly describes the view and is primarily used for accessibility support.
2938     */
2939    private CharSequence mContentDescription;
2940
2941    /**
2942     * Specifies the id of a view for which this view serves as a label for
2943     * accessibility purposes.
2944     */
2945    private int mLabelForId = View.NO_ID;
2946
2947    /**
2948     * Predicate for matching labeled view id with its label for
2949     * accessibility purposes.
2950     */
2951    private MatchLabelForPredicate mMatchLabelForPredicate;
2952
2953    /**
2954     * Predicate for matching a view by its id.
2955     */
2956    private MatchIdPredicate mMatchIdPredicate;
2957
2958    /**
2959     * Cache the paddingRight set by the user to append to the scrollbar's size.
2960     *
2961     * @hide
2962     */
2963    @ViewDebug.ExportedProperty(category = "padding")
2964    protected int mUserPaddingRight;
2965
2966    /**
2967     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2968     *
2969     * @hide
2970     */
2971    @ViewDebug.ExportedProperty(category = "padding")
2972    protected int mUserPaddingBottom;
2973
2974    /**
2975     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2976     *
2977     * @hide
2978     */
2979    @ViewDebug.ExportedProperty(category = "padding")
2980    protected int mUserPaddingLeft;
2981
2982    /**
2983     * Cache the paddingStart set by the user to append to the scrollbar's size.
2984     *
2985     */
2986    @ViewDebug.ExportedProperty(category = "padding")
2987    int mUserPaddingStart;
2988
2989    /**
2990     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2991     *
2992     */
2993    @ViewDebug.ExportedProperty(category = "padding")
2994    int mUserPaddingEnd;
2995
2996    /**
2997     * Cache initial left padding.
2998     *
2999     * @hide
3000     */
3001    int mUserPaddingLeftInitial;
3002
3003    /**
3004     * Cache initial right padding.
3005     *
3006     * @hide
3007     */
3008    int mUserPaddingRightInitial;
3009
3010    /**
3011     * Default undefined padding
3012     */
3013    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3014
3015    /**
3016     * @hide
3017     */
3018    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3019    /**
3020     * @hide
3021     */
3022    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3023
3024    private LongSparseLongArray mMeasureCache;
3025
3026    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3027    private Drawable mBackground;
3028
3029    private int mBackgroundResource;
3030    private boolean mBackgroundSizeChanged;
3031
3032    static class ListenerInfo {
3033        /**
3034         * Listener used to dispatch focus change events.
3035         * This field should be made private, so it is hidden from the SDK.
3036         * {@hide}
3037         */
3038        protected OnFocusChangeListener mOnFocusChangeListener;
3039
3040        /**
3041         * Listeners for layout change events.
3042         */
3043        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3044
3045        /**
3046         * Listeners for attach events.
3047         */
3048        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3049
3050        /**
3051         * Listener used to dispatch click events.
3052         * This field should be made private, so it is hidden from the SDK.
3053         * {@hide}
3054         */
3055        public OnClickListener mOnClickListener;
3056
3057        /**
3058         * Listener used to dispatch long click events.
3059         * This field should be made private, so it is hidden from the SDK.
3060         * {@hide}
3061         */
3062        protected OnLongClickListener mOnLongClickListener;
3063
3064        /**
3065         * Listener used to build the context menu.
3066         * This field should be made private, so it is hidden from the SDK.
3067         * {@hide}
3068         */
3069        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3070
3071        private OnKeyListener mOnKeyListener;
3072
3073        private OnTouchListener mOnTouchListener;
3074
3075        private OnHoverListener mOnHoverListener;
3076
3077        private OnGenericMotionListener mOnGenericMotionListener;
3078
3079        private OnDragListener mOnDragListener;
3080
3081        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3082    }
3083
3084    ListenerInfo mListenerInfo;
3085
3086    /**
3087     * The application environment this view lives in.
3088     * This field should be made private, so it is hidden from the SDK.
3089     * {@hide}
3090     */
3091    protected Context mContext;
3092
3093    private final Resources mResources;
3094
3095    private ScrollabilityCache mScrollCache;
3096
3097    private int[] mDrawableState = null;
3098
3099    /**
3100     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3101     * the user may specify which view to go to next.
3102     */
3103    private int mNextFocusLeftId = View.NO_ID;
3104
3105    /**
3106     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3107     * the user may specify which view to go to next.
3108     */
3109    private int mNextFocusRightId = View.NO_ID;
3110
3111    /**
3112     * When this view has focus and the next focus is {@link #FOCUS_UP},
3113     * the user may specify which view to go to next.
3114     */
3115    private int mNextFocusUpId = View.NO_ID;
3116
3117    /**
3118     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3119     * the user may specify which view to go to next.
3120     */
3121    private int mNextFocusDownId = View.NO_ID;
3122
3123    /**
3124     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3125     * the user may specify which view to go to next.
3126     */
3127    int mNextFocusForwardId = View.NO_ID;
3128
3129    private CheckForLongPress mPendingCheckForLongPress;
3130    private CheckForTap mPendingCheckForTap = null;
3131    private PerformClick mPerformClick;
3132    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3133
3134    private UnsetPressedState mUnsetPressedState;
3135
3136    /**
3137     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3138     * up event while a long press is invoked as soon as the long press duration is reached, so
3139     * a long press could be performed before the tap is checked, in which case the tap's action
3140     * should not be invoked.
3141     */
3142    private boolean mHasPerformedLongPress;
3143
3144    /**
3145     * The minimum height of the view. We'll try our best to have the height
3146     * of this view to at least this amount.
3147     */
3148    @ViewDebug.ExportedProperty(category = "measurement")
3149    private int mMinHeight;
3150
3151    /**
3152     * The minimum width of the view. We'll try our best to have the width
3153     * of this view to at least this amount.
3154     */
3155    @ViewDebug.ExportedProperty(category = "measurement")
3156    private int mMinWidth;
3157
3158    /**
3159     * The delegate to handle touch events that are physically in this view
3160     * but should be handled by another view.
3161     */
3162    private TouchDelegate mTouchDelegate = null;
3163
3164    /**
3165     * Solid color to use as a background when creating the drawing cache. Enables
3166     * the cache to use 16 bit bitmaps instead of 32 bit.
3167     */
3168    private int mDrawingCacheBackgroundColor = 0;
3169
3170    /**
3171     * Special tree observer used when mAttachInfo is null.
3172     */
3173    private ViewTreeObserver mFloatingTreeObserver;
3174
3175    /**
3176     * Cache the touch slop from the context that created the view.
3177     */
3178    private int mTouchSlop;
3179
3180    /**
3181     * Object that handles automatic animation of view properties.
3182     */
3183    private ViewPropertyAnimator mAnimator = null;
3184
3185    /**
3186     * Flag indicating that a drag can cross window boundaries.  When
3187     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3188     * with this flag set, all visible applications will be able to participate
3189     * in the drag operation and receive the dragged content.
3190     *
3191     * @hide
3192     */
3193    public static final int DRAG_FLAG_GLOBAL = 1;
3194
3195    /**
3196     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3197     */
3198    private float mVerticalScrollFactor;
3199
3200    /**
3201     * Position of the vertical scroll bar.
3202     */
3203    private int mVerticalScrollbarPosition;
3204
3205    /**
3206     * Position the scroll bar at the default position as determined by the system.
3207     */
3208    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3209
3210    /**
3211     * Position the scroll bar along the left edge.
3212     */
3213    public static final int SCROLLBAR_POSITION_LEFT = 1;
3214
3215    /**
3216     * Position the scroll bar along the right edge.
3217     */
3218    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3219
3220    /**
3221     * Indicates that the view does not have a layer.
3222     *
3223     * @see #getLayerType()
3224     * @see #setLayerType(int, android.graphics.Paint)
3225     * @see #LAYER_TYPE_SOFTWARE
3226     * @see #LAYER_TYPE_HARDWARE
3227     */
3228    public static final int LAYER_TYPE_NONE = 0;
3229
3230    /**
3231     * <p>Indicates that the view has a software layer. A software layer is backed
3232     * by a bitmap and causes the view to be rendered using Android's software
3233     * rendering pipeline, even if hardware acceleration is enabled.</p>
3234     *
3235     * <p>Software layers have various usages:</p>
3236     * <p>When the application is not using hardware acceleration, a software layer
3237     * is useful to apply a specific color filter and/or blending mode and/or
3238     * translucency to a view and all its children.</p>
3239     * <p>When the application is using hardware acceleration, a software layer
3240     * is useful to render drawing primitives not supported by the hardware
3241     * accelerated pipeline. It can also be used to cache a complex view tree
3242     * into a texture and reduce the complexity of drawing operations. For instance,
3243     * when animating a complex view tree with a translation, a software layer can
3244     * be used to render the view tree only once.</p>
3245     * <p>Software layers should be avoided when the affected view tree updates
3246     * often. Every update will require to re-render the software layer, which can
3247     * potentially be slow (particularly when hardware acceleration is turned on
3248     * since the layer will have to be uploaded into a hardware texture after every
3249     * update.)</p>
3250     *
3251     * @see #getLayerType()
3252     * @see #setLayerType(int, android.graphics.Paint)
3253     * @see #LAYER_TYPE_NONE
3254     * @see #LAYER_TYPE_HARDWARE
3255     */
3256    public static final int LAYER_TYPE_SOFTWARE = 1;
3257
3258    /**
3259     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3260     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3261     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3262     * rendering pipeline, but only if hardware acceleration is turned on for the
3263     * view hierarchy. When hardware acceleration is turned off, hardware layers
3264     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3265     *
3266     * <p>A hardware layer is useful to apply a specific color filter and/or
3267     * blending mode and/or translucency to a view and all its children.</p>
3268     * <p>A hardware layer can be used to cache a complex view tree into a
3269     * texture and reduce the complexity of drawing operations. For instance,
3270     * when animating a complex view tree with a translation, a hardware layer can
3271     * be used to render the view tree only once.</p>
3272     * <p>A hardware layer can also be used to increase the rendering quality when
3273     * rotation transformations are applied on a view. It can also be used to
3274     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3275     *
3276     * @see #getLayerType()
3277     * @see #setLayerType(int, android.graphics.Paint)
3278     * @see #LAYER_TYPE_NONE
3279     * @see #LAYER_TYPE_SOFTWARE
3280     */
3281    public static final int LAYER_TYPE_HARDWARE = 2;
3282
3283    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3284            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3285            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3286            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3287    })
3288    int mLayerType = LAYER_TYPE_NONE;
3289    Paint mLayerPaint;
3290    Rect mLocalDirtyRect;
3291    private HardwareLayer mHardwareLayer;
3292
3293    /**
3294     * Set to true when drawing cache is enabled and cannot be created.
3295     *
3296     * @hide
3297     */
3298    public boolean mCachingFailed;
3299    private Bitmap mDrawingCache;
3300    private Bitmap mUnscaledDrawingCache;
3301
3302    DisplayList mDisplayList;
3303
3304    /**
3305     * Set to true when the view is sending hover accessibility events because it
3306     * is the innermost hovered view.
3307     */
3308    private boolean mSendingHoverAccessibilityEvents;
3309
3310    /**
3311     * Delegate for injecting accessibility functionality.
3312     */
3313    AccessibilityDelegate mAccessibilityDelegate;
3314
3315    /**
3316     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3317     * and add/remove objects to/from the overlay directly through the Overlay methods.
3318     */
3319    ViewOverlay mOverlay;
3320
3321    /**
3322     * Consistency verifier for debugging purposes.
3323     * @hide
3324     */
3325    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3326            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3327                    new InputEventConsistencyVerifier(this, 0) : null;
3328
3329    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3330
3331    /**
3332     * Simple constructor to use when creating a view from code.
3333     *
3334     * @param context The Context the view is running in, through which it can
3335     *        access the current theme, resources, etc.
3336     */
3337    public View(Context context) {
3338        mContext = context;
3339        mResources = context != null ? context.getResources() : null;
3340        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3341        // Set some flags defaults
3342        mPrivateFlags2 =
3343                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3344                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3345                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3346                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3347                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3348                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3349        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3350        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3351        mUserPaddingStart = UNDEFINED_PADDING;
3352        mUserPaddingEnd = UNDEFINED_PADDING;
3353
3354        if (!sUseBrokenMakeMeasureSpec && context != null &&
3355                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3356            // Older apps may need this compatibility hack for measurement.
3357            sUseBrokenMakeMeasureSpec = true;
3358        }
3359    }
3360
3361    /**
3362     * Constructor that is called when inflating a view from XML. This is called
3363     * when a view is being constructed from an XML file, supplying attributes
3364     * that were specified in the XML file. This version uses a default style of
3365     * 0, so the only attribute values applied are those in the Context's Theme
3366     * and the given AttributeSet.
3367     *
3368     * <p>
3369     * The method onFinishInflate() will be called after all children have been
3370     * added.
3371     *
3372     * @param context The Context the view is running in, through which it can
3373     *        access the current theme, resources, etc.
3374     * @param attrs The attributes of the XML tag that is inflating the view.
3375     * @see #View(Context, AttributeSet, int)
3376     */
3377    public View(Context context, AttributeSet attrs) {
3378        this(context, attrs, 0);
3379    }
3380
3381    /**
3382     * Perform inflation from XML and apply a class-specific base style. This
3383     * constructor of View allows subclasses to use their own base style when
3384     * they are inflating. For example, a Button class's constructor would call
3385     * this version of the super class constructor and supply
3386     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3387     * the theme's button style to modify all of the base view attributes (in
3388     * particular its background) as well as the Button class's attributes.
3389     *
3390     * @param context The Context the view is running in, through which it can
3391     *        access the current theme, resources, etc.
3392     * @param attrs The attributes of the XML tag that is inflating the view.
3393     * @param defStyleAttr An attribute in the current theme that contains a
3394     *        reference to a style resource to apply to this view. If 0, no
3395     *        default style will be applied.
3396     * @see #View(Context, AttributeSet)
3397     */
3398    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3399        this(context);
3400
3401        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3402                defStyleAttr, 0);
3403
3404        Drawable background = null;
3405
3406        int leftPadding = -1;
3407        int topPadding = -1;
3408        int rightPadding = -1;
3409        int bottomPadding = -1;
3410        int startPadding = UNDEFINED_PADDING;
3411        int endPadding = UNDEFINED_PADDING;
3412
3413        int padding = -1;
3414
3415        int viewFlagValues = 0;
3416        int viewFlagMasks = 0;
3417
3418        boolean setScrollContainer = false;
3419
3420        int x = 0;
3421        int y = 0;
3422
3423        float tx = 0;
3424        float ty = 0;
3425        float rotation = 0;
3426        float rotationX = 0;
3427        float rotationY = 0;
3428        float sx = 1f;
3429        float sy = 1f;
3430        boolean transformSet = false;
3431
3432        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3433        int overScrollMode = mOverScrollMode;
3434        boolean initializeScrollbars = false;
3435
3436        boolean leftPaddingDefined = false;
3437        boolean rightPaddingDefined = false;
3438        boolean startPaddingDefined = false;
3439        boolean endPaddingDefined = false;
3440
3441        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3442
3443        final int N = a.getIndexCount();
3444        for (int i = 0; i < N; i++) {
3445            int attr = a.getIndex(i);
3446            switch (attr) {
3447                case com.android.internal.R.styleable.View_background:
3448                    background = a.getDrawable(attr);
3449                    break;
3450                case com.android.internal.R.styleable.View_padding:
3451                    padding = a.getDimensionPixelSize(attr, -1);
3452                    mUserPaddingLeftInitial = padding;
3453                    mUserPaddingRightInitial = padding;
3454                    leftPaddingDefined = true;
3455                    rightPaddingDefined = true;
3456                    break;
3457                 case com.android.internal.R.styleable.View_paddingLeft:
3458                    leftPadding = a.getDimensionPixelSize(attr, -1);
3459                    mUserPaddingLeftInitial = leftPadding;
3460                    leftPaddingDefined = true;
3461                    break;
3462                case com.android.internal.R.styleable.View_paddingTop:
3463                    topPadding = a.getDimensionPixelSize(attr, -1);
3464                    break;
3465                case com.android.internal.R.styleable.View_paddingRight:
3466                    rightPadding = a.getDimensionPixelSize(attr, -1);
3467                    mUserPaddingRightInitial = rightPadding;
3468                    rightPaddingDefined = true;
3469                    break;
3470                case com.android.internal.R.styleable.View_paddingBottom:
3471                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3472                    break;
3473                case com.android.internal.R.styleable.View_paddingStart:
3474                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3475                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3476                    break;
3477                case com.android.internal.R.styleable.View_paddingEnd:
3478                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3479                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3480                    break;
3481                case com.android.internal.R.styleable.View_scrollX:
3482                    x = a.getDimensionPixelOffset(attr, 0);
3483                    break;
3484                case com.android.internal.R.styleable.View_scrollY:
3485                    y = a.getDimensionPixelOffset(attr, 0);
3486                    break;
3487                case com.android.internal.R.styleable.View_alpha:
3488                    setAlpha(a.getFloat(attr, 1f));
3489                    break;
3490                case com.android.internal.R.styleable.View_transformPivotX:
3491                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3492                    break;
3493                case com.android.internal.R.styleable.View_transformPivotY:
3494                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3495                    break;
3496                case com.android.internal.R.styleable.View_translationX:
3497                    tx = a.getDimensionPixelOffset(attr, 0);
3498                    transformSet = true;
3499                    break;
3500                case com.android.internal.R.styleable.View_translationY:
3501                    ty = a.getDimensionPixelOffset(attr, 0);
3502                    transformSet = true;
3503                    break;
3504                case com.android.internal.R.styleable.View_rotation:
3505                    rotation = a.getFloat(attr, 0);
3506                    transformSet = true;
3507                    break;
3508                case com.android.internal.R.styleable.View_rotationX:
3509                    rotationX = a.getFloat(attr, 0);
3510                    transformSet = true;
3511                    break;
3512                case com.android.internal.R.styleable.View_rotationY:
3513                    rotationY = a.getFloat(attr, 0);
3514                    transformSet = true;
3515                    break;
3516                case com.android.internal.R.styleable.View_scaleX:
3517                    sx = a.getFloat(attr, 1f);
3518                    transformSet = true;
3519                    break;
3520                case com.android.internal.R.styleable.View_scaleY:
3521                    sy = a.getFloat(attr, 1f);
3522                    transformSet = true;
3523                    break;
3524                case com.android.internal.R.styleable.View_id:
3525                    mID = a.getResourceId(attr, NO_ID);
3526                    break;
3527                case com.android.internal.R.styleable.View_tag:
3528                    mTag = a.getText(attr);
3529                    break;
3530                case com.android.internal.R.styleable.View_fitsSystemWindows:
3531                    if (a.getBoolean(attr, false)) {
3532                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3533                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3534                    }
3535                    break;
3536                case com.android.internal.R.styleable.View_focusable:
3537                    if (a.getBoolean(attr, false)) {
3538                        viewFlagValues |= FOCUSABLE;
3539                        viewFlagMasks |= FOCUSABLE_MASK;
3540                    }
3541                    break;
3542                case com.android.internal.R.styleable.View_focusableInTouchMode:
3543                    if (a.getBoolean(attr, false)) {
3544                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3545                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3546                    }
3547                    break;
3548                case com.android.internal.R.styleable.View_clickable:
3549                    if (a.getBoolean(attr, false)) {
3550                        viewFlagValues |= CLICKABLE;
3551                        viewFlagMasks |= CLICKABLE;
3552                    }
3553                    break;
3554                case com.android.internal.R.styleable.View_longClickable:
3555                    if (a.getBoolean(attr, false)) {
3556                        viewFlagValues |= LONG_CLICKABLE;
3557                        viewFlagMasks |= LONG_CLICKABLE;
3558                    }
3559                    break;
3560                case com.android.internal.R.styleable.View_saveEnabled:
3561                    if (!a.getBoolean(attr, true)) {
3562                        viewFlagValues |= SAVE_DISABLED;
3563                        viewFlagMasks |= SAVE_DISABLED_MASK;
3564                    }
3565                    break;
3566                case com.android.internal.R.styleable.View_duplicateParentState:
3567                    if (a.getBoolean(attr, false)) {
3568                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3569                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3570                    }
3571                    break;
3572                case com.android.internal.R.styleable.View_visibility:
3573                    final int visibility = a.getInt(attr, 0);
3574                    if (visibility != 0) {
3575                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3576                        viewFlagMasks |= VISIBILITY_MASK;
3577                    }
3578                    break;
3579                case com.android.internal.R.styleable.View_layoutDirection:
3580                    // Clear any layout direction flags (included resolved bits) already set
3581                    mPrivateFlags2 &=
3582                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3583                    // Set the layout direction flags depending on the value of the attribute
3584                    final int layoutDirection = a.getInt(attr, -1);
3585                    final int value = (layoutDirection != -1) ?
3586                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3587                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3588                    break;
3589                case com.android.internal.R.styleable.View_drawingCacheQuality:
3590                    final int cacheQuality = a.getInt(attr, 0);
3591                    if (cacheQuality != 0) {
3592                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3593                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3594                    }
3595                    break;
3596                case com.android.internal.R.styleable.View_contentDescription:
3597                    setContentDescription(a.getString(attr));
3598                    break;
3599                case com.android.internal.R.styleable.View_labelFor:
3600                    setLabelFor(a.getResourceId(attr, NO_ID));
3601                    break;
3602                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3603                    if (!a.getBoolean(attr, true)) {
3604                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3605                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3606                    }
3607                    break;
3608                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3609                    if (!a.getBoolean(attr, true)) {
3610                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3611                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3612                    }
3613                    break;
3614                case R.styleable.View_scrollbars:
3615                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3616                    if (scrollbars != SCROLLBARS_NONE) {
3617                        viewFlagValues |= scrollbars;
3618                        viewFlagMasks |= SCROLLBARS_MASK;
3619                        initializeScrollbars = true;
3620                    }
3621                    break;
3622                //noinspection deprecation
3623                case R.styleable.View_fadingEdge:
3624                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3625                        // Ignore the attribute starting with ICS
3626                        break;
3627                    }
3628                    // With builds < ICS, fall through and apply fading edges
3629                case R.styleable.View_requiresFadingEdge:
3630                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3631                    if (fadingEdge != FADING_EDGE_NONE) {
3632                        viewFlagValues |= fadingEdge;
3633                        viewFlagMasks |= FADING_EDGE_MASK;
3634                        initializeFadingEdge(a);
3635                    }
3636                    break;
3637                case R.styleable.View_scrollbarStyle:
3638                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3639                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3640                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3641                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3642                    }
3643                    break;
3644                case R.styleable.View_isScrollContainer:
3645                    setScrollContainer = true;
3646                    if (a.getBoolean(attr, false)) {
3647                        setScrollContainer(true);
3648                    }
3649                    break;
3650                case com.android.internal.R.styleable.View_keepScreenOn:
3651                    if (a.getBoolean(attr, false)) {
3652                        viewFlagValues |= KEEP_SCREEN_ON;
3653                        viewFlagMasks |= KEEP_SCREEN_ON;
3654                    }
3655                    break;
3656                case R.styleable.View_filterTouchesWhenObscured:
3657                    if (a.getBoolean(attr, false)) {
3658                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3659                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3660                    }
3661                    break;
3662                case R.styleable.View_nextFocusLeft:
3663                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3664                    break;
3665                case R.styleable.View_nextFocusRight:
3666                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3667                    break;
3668                case R.styleable.View_nextFocusUp:
3669                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3670                    break;
3671                case R.styleable.View_nextFocusDown:
3672                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3673                    break;
3674                case R.styleable.View_nextFocusForward:
3675                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3676                    break;
3677                case R.styleable.View_minWidth:
3678                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3679                    break;
3680                case R.styleable.View_minHeight:
3681                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3682                    break;
3683                case R.styleable.View_onClick:
3684                    if (context.isRestricted()) {
3685                        throw new IllegalStateException("The android:onClick attribute cannot "
3686                                + "be used within a restricted context");
3687                    }
3688
3689                    final String handlerName = a.getString(attr);
3690                    if (handlerName != null) {
3691                        setOnClickListener(new OnClickListener() {
3692                            private Method mHandler;
3693
3694                            public void onClick(View v) {
3695                                if (mHandler == null) {
3696                                    try {
3697                                        mHandler = getContext().getClass().getMethod(handlerName,
3698                                                View.class);
3699                                    } catch (NoSuchMethodException e) {
3700                                        int id = getId();
3701                                        String idText = id == NO_ID ? "" : " with id '"
3702                                                + getContext().getResources().getResourceEntryName(
3703                                                    id) + "'";
3704                                        throw new IllegalStateException("Could not find a method " +
3705                                                handlerName + "(View) in the activity "
3706                                                + getContext().getClass() + " for onClick handler"
3707                                                + " on view " + View.this.getClass() + idText, e);
3708                                    }
3709                                }
3710
3711                                try {
3712                                    mHandler.invoke(getContext(), View.this);
3713                                } catch (IllegalAccessException e) {
3714                                    throw new IllegalStateException("Could not execute non "
3715                                            + "public method of the activity", e);
3716                                } catch (InvocationTargetException e) {
3717                                    throw new IllegalStateException("Could not execute "
3718                                            + "method of the activity", e);
3719                                }
3720                            }
3721                        });
3722                    }
3723                    break;
3724                case R.styleable.View_overScrollMode:
3725                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3726                    break;
3727                case R.styleable.View_verticalScrollbarPosition:
3728                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3729                    break;
3730                case R.styleable.View_layerType:
3731                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3732                    break;
3733                case R.styleable.View_textDirection:
3734                    // Clear any text direction flag already set
3735                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3736                    // Set the text direction flags depending on the value of the attribute
3737                    final int textDirection = a.getInt(attr, -1);
3738                    if (textDirection != -1) {
3739                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3740                    }
3741                    break;
3742                case R.styleable.View_textAlignment:
3743                    // Clear any text alignment flag already set
3744                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3745                    // Set the text alignment flag depending on the value of the attribute
3746                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3747                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3748                    break;
3749                case R.styleable.View_importantForAccessibility:
3750                    setImportantForAccessibility(a.getInt(attr,
3751                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3752                    break;
3753            }
3754        }
3755
3756        setOverScrollMode(overScrollMode);
3757
3758        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3759        // the resolved layout direction). Those cached values will be used later during padding
3760        // resolution.
3761        mUserPaddingStart = startPadding;
3762        mUserPaddingEnd = endPadding;
3763
3764        if (background != null) {
3765            setBackground(background);
3766        }
3767
3768        if (padding >= 0) {
3769            leftPadding = padding;
3770            topPadding = padding;
3771            rightPadding = padding;
3772            bottomPadding = padding;
3773            mUserPaddingLeftInitial = padding;
3774            mUserPaddingRightInitial = padding;
3775        }
3776
3777        if (isRtlCompatibilityMode()) {
3778            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3779            // left / right padding are used if defined (meaning here nothing to do). If they are not
3780            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3781            // start / end and resolve them as left / right (layout direction is not taken into account).
3782            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3783            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3784            // defined.
3785            if (!leftPaddingDefined && startPaddingDefined) {
3786                leftPadding = startPadding;
3787            }
3788            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3789            if (!rightPaddingDefined && endPaddingDefined) {
3790                rightPadding = endPadding;
3791            }
3792            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3793        } else {
3794            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3795            // values defined. Otherwise, left /right values are used.
3796            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3797            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3798            // defined.
3799            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3800
3801            if (leftPaddingDefined && !hasRelativePadding) {
3802                mUserPaddingLeftInitial = leftPadding;
3803            }
3804            if (rightPaddingDefined && !hasRelativePadding) {
3805                mUserPaddingRightInitial = rightPadding;
3806            }
3807        }
3808
3809        internalSetPadding(
3810                mUserPaddingLeftInitial,
3811                topPadding >= 0 ? topPadding : mPaddingTop,
3812                mUserPaddingRightInitial,
3813                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3814
3815        if (viewFlagMasks != 0) {
3816            setFlags(viewFlagValues, viewFlagMasks);
3817        }
3818
3819        if (initializeScrollbars) {
3820            initializeScrollbars(a);
3821        }
3822
3823        a.recycle();
3824
3825        // Needs to be called after mViewFlags is set
3826        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3827            recomputePadding();
3828        }
3829
3830        if (x != 0 || y != 0) {
3831            scrollTo(x, y);
3832        }
3833
3834        if (transformSet) {
3835            setTranslationX(tx);
3836            setTranslationY(ty);
3837            setRotation(rotation);
3838            setRotationX(rotationX);
3839            setRotationY(rotationY);
3840            setScaleX(sx);
3841            setScaleY(sy);
3842        }
3843
3844        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3845            setScrollContainer(true);
3846        }
3847
3848        computeOpaqueFlags();
3849    }
3850
3851    /**
3852     * Non-public constructor for use in testing
3853     */
3854    View() {
3855        mResources = null;
3856    }
3857
3858    public String toString() {
3859        StringBuilder out = new StringBuilder(128);
3860        out.append(getClass().getName());
3861        out.append('{');
3862        out.append(Integer.toHexString(System.identityHashCode(this)));
3863        out.append(' ');
3864        switch (mViewFlags&VISIBILITY_MASK) {
3865            case VISIBLE: out.append('V'); break;
3866            case INVISIBLE: out.append('I'); break;
3867            case GONE: out.append('G'); break;
3868            default: out.append('.'); break;
3869        }
3870        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3871        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3872        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3873        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3874        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3875        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3876        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3877        out.append(' ');
3878        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3879        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3880        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3881        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3882            out.append('p');
3883        } else {
3884            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3885        }
3886        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3887        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3888        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3889        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3890        out.append(' ');
3891        out.append(mLeft);
3892        out.append(',');
3893        out.append(mTop);
3894        out.append('-');
3895        out.append(mRight);
3896        out.append(',');
3897        out.append(mBottom);
3898        final int id = getId();
3899        if (id != NO_ID) {
3900            out.append(" #");
3901            out.append(Integer.toHexString(id));
3902            final Resources r = mResources;
3903            if (id != 0 && r != null) {
3904                try {
3905                    String pkgname;
3906                    switch (id&0xff000000) {
3907                        case 0x7f000000:
3908                            pkgname="app";
3909                            break;
3910                        case 0x01000000:
3911                            pkgname="android";
3912                            break;
3913                        default:
3914                            pkgname = r.getResourcePackageName(id);
3915                            break;
3916                    }
3917                    String typename = r.getResourceTypeName(id);
3918                    String entryname = r.getResourceEntryName(id);
3919                    out.append(" ");
3920                    out.append(pkgname);
3921                    out.append(":");
3922                    out.append(typename);
3923                    out.append("/");
3924                    out.append(entryname);
3925                } catch (Resources.NotFoundException e) {
3926                }
3927            }
3928        }
3929        out.append("}");
3930        return out.toString();
3931    }
3932
3933    /**
3934     * <p>
3935     * Initializes the fading edges from a given set of styled attributes. This
3936     * method should be called by subclasses that need fading edges and when an
3937     * instance of these subclasses is created programmatically rather than
3938     * being inflated from XML. This method is automatically called when the XML
3939     * is inflated.
3940     * </p>
3941     *
3942     * @param a the styled attributes set to initialize the fading edges from
3943     */
3944    protected void initializeFadingEdge(TypedArray a) {
3945        initScrollCache();
3946
3947        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3948                R.styleable.View_fadingEdgeLength,
3949                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3950    }
3951
3952    /**
3953     * Returns the size of the vertical faded edges used to indicate that more
3954     * content in this view is visible.
3955     *
3956     * @return The size in pixels of the vertical faded edge or 0 if vertical
3957     *         faded edges are not enabled for this view.
3958     * @attr ref android.R.styleable#View_fadingEdgeLength
3959     */
3960    public int getVerticalFadingEdgeLength() {
3961        if (isVerticalFadingEdgeEnabled()) {
3962            ScrollabilityCache cache = mScrollCache;
3963            if (cache != null) {
3964                return cache.fadingEdgeLength;
3965            }
3966        }
3967        return 0;
3968    }
3969
3970    /**
3971     * Set the size of the faded edge used to indicate that more content in this
3972     * view is available.  Will not change whether the fading edge is enabled; use
3973     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3974     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3975     * for the vertical or horizontal fading edges.
3976     *
3977     * @param length The size in pixels of the faded edge used to indicate that more
3978     *        content in this view is visible.
3979     */
3980    public void setFadingEdgeLength(int length) {
3981        initScrollCache();
3982        mScrollCache.fadingEdgeLength = length;
3983    }
3984
3985    /**
3986     * Returns the size of the horizontal faded edges used to indicate that more
3987     * content in this view is visible.
3988     *
3989     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3990     *         faded edges are not enabled for this view.
3991     * @attr ref android.R.styleable#View_fadingEdgeLength
3992     */
3993    public int getHorizontalFadingEdgeLength() {
3994        if (isHorizontalFadingEdgeEnabled()) {
3995            ScrollabilityCache cache = mScrollCache;
3996            if (cache != null) {
3997                return cache.fadingEdgeLength;
3998            }
3999        }
4000        return 0;
4001    }
4002
4003    /**
4004     * Returns the width of the vertical scrollbar.
4005     *
4006     * @return The width in pixels of the vertical scrollbar or 0 if there
4007     *         is no vertical scrollbar.
4008     */
4009    public int getVerticalScrollbarWidth() {
4010        ScrollabilityCache cache = mScrollCache;
4011        if (cache != null) {
4012            ScrollBarDrawable scrollBar = cache.scrollBar;
4013            if (scrollBar != null) {
4014                int size = scrollBar.getSize(true);
4015                if (size <= 0) {
4016                    size = cache.scrollBarSize;
4017                }
4018                return size;
4019            }
4020            return 0;
4021        }
4022        return 0;
4023    }
4024
4025    /**
4026     * Returns the height of the horizontal scrollbar.
4027     *
4028     * @return The height in pixels of the horizontal scrollbar or 0 if
4029     *         there is no horizontal scrollbar.
4030     */
4031    protected int getHorizontalScrollbarHeight() {
4032        ScrollabilityCache cache = mScrollCache;
4033        if (cache != null) {
4034            ScrollBarDrawable scrollBar = cache.scrollBar;
4035            if (scrollBar != null) {
4036                int size = scrollBar.getSize(false);
4037                if (size <= 0) {
4038                    size = cache.scrollBarSize;
4039                }
4040                return size;
4041            }
4042            return 0;
4043        }
4044        return 0;
4045    }
4046
4047    /**
4048     * <p>
4049     * Initializes the scrollbars from a given set of styled attributes. This
4050     * method should be called by subclasses that need scrollbars and when an
4051     * instance of these subclasses is created programmatically rather than
4052     * being inflated from XML. This method is automatically called when the XML
4053     * is inflated.
4054     * </p>
4055     *
4056     * @param a the styled attributes set to initialize the scrollbars from
4057     */
4058    protected void initializeScrollbars(TypedArray a) {
4059        initScrollCache();
4060
4061        final ScrollabilityCache scrollabilityCache = mScrollCache;
4062
4063        if (scrollabilityCache.scrollBar == null) {
4064            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4065        }
4066
4067        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4068
4069        if (!fadeScrollbars) {
4070            scrollabilityCache.state = ScrollabilityCache.ON;
4071        }
4072        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4073
4074
4075        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4076                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4077                        .getScrollBarFadeDuration());
4078        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4079                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4080                ViewConfiguration.getScrollDefaultDelay());
4081
4082
4083        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4084                com.android.internal.R.styleable.View_scrollbarSize,
4085                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4086
4087        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4088        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4089
4090        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4091        if (thumb != null) {
4092            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4093        }
4094
4095        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4096                false);
4097        if (alwaysDraw) {
4098            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4099        }
4100
4101        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4102        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4103
4104        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4105        if (thumb != null) {
4106            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4107        }
4108
4109        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4110                false);
4111        if (alwaysDraw) {
4112            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4113        }
4114
4115        // Apply layout direction to the new Drawables if needed
4116        final int layoutDirection = getLayoutDirection();
4117        if (track != null) {
4118            track.setLayoutDirection(layoutDirection);
4119        }
4120        if (thumb != null) {
4121            thumb.setLayoutDirection(layoutDirection);
4122        }
4123
4124        // Re-apply user/background padding so that scrollbar(s) get added
4125        resolvePadding();
4126    }
4127
4128    /**
4129     * <p>
4130     * Initalizes the scrollability cache if necessary.
4131     * </p>
4132     */
4133    private void initScrollCache() {
4134        if (mScrollCache == null) {
4135            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4136        }
4137    }
4138
4139    private ScrollabilityCache getScrollCache() {
4140        initScrollCache();
4141        return mScrollCache;
4142    }
4143
4144    /**
4145     * Set the position of the vertical scroll bar. Should be one of
4146     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4147     * {@link #SCROLLBAR_POSITION_RIGHT}.
4148     *
4149     * @param position Where the vertical scroll bar should be positioned.
4150     */
4151    public void setVerticalScrollbarPosition(int position) {
4152        if (mVerticalScrollbarPosition != position) {
4153            mVerticalScrollbarPosition = position;
4154            computeOpaqueFlags();
4155            resolvePadding();
4156        }
4157    }
4158
4159    /**
4160     * @return The position where the vertical scroll bar will show, if applicable.
4161     * @see #setVerticalScrollbarPosition(int)
4162     */
4163    public int getVerticalScrollbarPosition() {
4164        return mVerticalScrollbarPosition;
4165    }
4166
4167    ListenerInfo getListenerInfo() {
4168        if (mListenerInfo != null) {
4169            return mListenerInfo;
4170        }
4171        mListenerInfo = new ListenerInfo();
4172        return mListenerInfo;
4173    }
4174
4175    /**
4176     * Register a callback to be invoked when focus of this view changed.
4177     *
4178     * @param l The callback that will run.
4179     */
4180    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4181        getListenerInfo().mOnFocusChangeListener = l;
4182    }
4183
4184    /**
4185     * Add a listener that will be called when the bounds of the view change due to
4186     * layout processing.
4187     *
4188     * @param listener The listener that will be called when layout bounds change.
4189     */
4190    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4191        ListenerInfo li = getListenerInfo();
4192        if (li.mOnLayoutChangeListeners == null) {
4193            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4194        }
4195        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4196            li.mOnLayoutChangeListeners.add(listener);
4197        }
4198    }
4199
4200    /**
4201     * Remove a listener for layout changes.
4202     *
4203     * @param listener The listener for layout bounds change.
4204     */
4205    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4206        ListenerInfo li = mListenerInfo;
4207        if (li == null || li.mOnLayoutChangeListeners == null) {
4208            return;
4209        }
4210        li.mOnLayoutChangeListeners.remove(listener);
4211    }
4212
4213    /**
4214     * Add a listener for attach state changes.
4215     *
4216     * This listener will be called whenever this view is attached or detached
4217     * from a window. Remove the listener using
4218     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4219     *
4220     * @param listener Listener to attach
4221     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4222     */
4223    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4224        ListenerInfo li = getListenerInfo();
4225        if (li.mOnAttachStateChangeListeners == null) {
4226            li.mOnAttachStateChangeListeners
4227                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4228        }
4229        li.mOnAttachStateChangeListeners.add(listener);
4230    }
4231
4232    /**
4233     * Remove a listener for attach state changes. The listener will receive no further
4234     * notification of window attach/detach events.
4235     *
4236     * @param listener Listener to remove
4237     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4238     */
4239    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4240        ListenerInfo li = mListenerInfo;
4241        if (li == null || li.mOnAttachStateChangeListeners == null) {
4242            return;
4243        }
4244        li.mOnAttachStateChangeListeners.remove(listener);
4245    }
4246
4247    /**
4248     * Returns the focus-change callback registered for this view.
4249     *
4250     * @return The callback, or null if one is not registered.
4251     */
4252    public OnFocusChangeListener getOnFocusChangeListener() {
4253        ListenerInfo li = mListenerInfo;
4254        return li != null ? li.mOnFocusChangeListener : null;
4255    }
4256
4257    /**
4258     * Register a callback to be invoked when this view is clicked. If this view is not
4259     * clickable, it becomes clickable.
4260     *
4261     * @param l The callback that will run
4262     *
4263     * @see #setClickable(boolean)
4264     */
4265    public void setOnClickListener(OnClickListener l) {
4266        if (!isClickable()) {
4267            setClickable(true);
4268        }
4269        getListenerInfo().mOnClickListener = l;
4270    }
4271
4272    /**
4273     * Return whether this view has an attached OnClickListener.  Returns
4274     * true if there is a listener, false if there is none.
4275     */
4276    public boolean hasOnClickListeners() {
4277        ListenerInfo li = mListenerInfo;
4278        return (li != null && li.mOnClickListener != null);
4279    }
4280
4281    /**
4282     * Register a callback to be invoked when this view is clicked and held. If this view is not
4283     * long clickable, it becomes long clickable.
4284     *
4285     * @param l The callback that will run
4286     *
4287     * @see #setLongClickable(boolean)
4288     */
4289    public void setOnLongClickListener(OnLongClickListener l) {
4290        if (!isLongClickable()) {
4291            setLongClickable(true);
4292        }
4293        getListenerInfo().mOnLongClickListener = l;
4294    }
4295
4296    /**
4297     * Register a callback to be invoked when the context menu for this view is
4298     * being built. If this view is not long clickable, it becomes long clickable.
4299     *
4300     * @param l The callback that will run
4301     *
4302     */
4303    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4304        if (!isLongClickable()) {
4305            setLongClickable(true);
4306        }
4307        getListenerInfo().mOnCreateContextMenuListener = l;
4308    }
4309
4310    /**
4311     * Call this view's OnClickListener, if it is defined.  Performs all normal
4312     * actions associated with clicking: reporting accessibility event, playing
4313     * a sound, etc.
4314     *
4315     * @return True there was an assigned OnClickListener that was called, false
4316     *         otherwise is returned.
4317     */
4318    public boolean performClick() {
4319        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4320
4321        ListenerInfo li = mListenerInfo;
4322        if (li != null && li.mOnClickListener != null) {
4323            playSoundEffect(SoundEffectConstants.CLICK);
4324            li.mOnClickListener.onClick(this);
4325            return true;
4326        }
4327
4328        return false;
4329    }
4330
4331    /**
4332     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4333     * this only calls the listener, and does not do any associated clicking
4334     * actions like reporting an accessibility event.
4335     *
4336     * @return True there was an assigned OnClickListener that was called, false
4337     *         otherwise is returned.
4338     */
4339    public boolean callOnClick() {
4340        ListenerInfo li = mListenerInfo;
4341        if (li != null && li.mOnClickListener != null) {
4342            li.mOnClickListener.onClick(this);
4343            return true;
4344        }
4345        return false;
4346    }
4347
4348    /**
4349     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4350     * OnLongClickListener did not consume the event.
4351     *
4352     * @return True if one of the above receivers consumed the event, false otherwise.
4353     */
4354    public boolean performLongClick() {
4355        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4356
4357        boolean handled = false;
4358        ListenerInfo li = mListenerInfo;
4359        if (li != null && li.mOnLongClickListener != null) {
4360            handled = li.mOnLongClickListener.onLongClick(View.this);
4361        }
4362        if (!handled) {
4363            handled = showContextMenu();
4364        }
4365        if (handled) {
4366            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4367        }
4368        return handled;
4369    }
4370
4371    /**
4372     * Performs button-related actions during a touch down event.
4373     *
4374     * @param event The event.
4375     * @return True if the down was consumed.
4376     *
4377     * @hide
4378     */
4379    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4380        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4381            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4382                return true;
4383            }
4384        }
4385        return false;
4386    }
4387
4388    /**
4389     * Bring up the context menu for this view.
4390     *
4391     * @return Whether a context menu was displayed.
4392     */
4393    public boolean showContextMenu() {
4394        return getParent().showContextMenuForChild(this);
4395    }
4396
4397    /**
4398     * Bring up the context menu for this view, referring to the item under the specified point.
4399     *
4400     * @param x The referenced x coordinate.
4401     * @param y The referenced y coordinate.
4402     * @param metaState The keyboard modifiers that were pressed.
4403     * @return Whether a context menu was displayed.
4404     *
4405     * @hide
4406     */
4407    public boolean showContextMenu(float x, float y, int metaState) {
4408        return showContextMenu();
4409    }
4410
4411    /**
4412     * Start an action mode.
4413     *
4414     * @param callback Callback that will control the lifecycle of the action mode
4415     * @return The new action mode if it is started, null otherwise
4416     *
4417     * @see ActionMode
4418     */
4419    public ActionMode startActionMode(ActionMode.Callback callback) {
4420        ViewParent parent = getParent();
4421        if (parent == null) return null;
4422        return parent.startActionModeForChild(this, callback);
4423    }
4424
4425    /**
4426     * Register a callback to be invoked when a hardware key is pressed in this view.
4427     * Key presses in software input methods will generally not trigger the methods of
4428     * this listener.
4429     * @param l the key listener to attach to this view
4430     */
4431    public void setOnKeyListener(OnKeyListener l) {
4432        getListenerInfo().mOnKeyListener = l;
4433    }
4434
4435    /**
4436     * Register a callback to be invoked when a touch event is sent to this view.
4437     * @param l the touch listener to attach to this view
4438     */
4439    public void setOnTouchListener(OnTouchListener l) {
4440        getListenerInfo().mOnTouchListener = l;
4441    }
4442
4443    /**
4444     * Register a callback to be invoked when a generic motion event is sent to this view.
4445     * @param l the generic motion listener to attach to this view
4446     */
4447    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4448        getListenerInfo().mOnGenericMotionListener = l;
4449    }
4450
4451    /**
4452     * Register a callback to be invoked when a hover event is sent to this view.
4453     * @param l the hover listener to attach to this view
4454     */
4455    public void setOnHoverListener(OnHoverListener l) {
4456        getListenerInfo().mOnHoverListener = l;
4457    }
4458
4459    /**
4460     * Register a drag event listener callback object for this View. The parameter is
4461     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4462     * View, the system calls the
4463     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4464     * @param l An implementation of {@link android.view.View.OnDragListener}.
4465     */
4466    public void setOnDragListener(OnDragListener l) {
4467        getListenerInfo().mOnDragListener = l;
4468    }
4469
4470    /**
4471     * Give this view focus. This will cause
4472     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4473     *
4474     * Note: this does not check whether this {@link View} should get focus, it just
4475     * gives it focus no matter what.  It should only be called internally by framework
4476     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4477     *
4478     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4479     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4480     *        focus moved when requestFocus() is called. It may not always
4481     *        apply, in which case use the default View.FOCUS_DOWN.
4482     * @param previouslyFocusedRect The rectangle of the view that had focus
4483     *        prior in this View's coordinate system.
4484     */
4485    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4486        if (DBG) {
4487            System.out.println(this + " requestFocus()");
4488        }
4489
4490        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4491            mPrivateFlags |= PFLAG_FOCUSED;
4492
4493            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4494
4495            if (mParent != null) {
4496                mParent.requestChildFocus(this, this);
4497            }
4498
4499            if (mAttachInfo != null) {
4500                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4501            }
4502
4503            onFocusChanged(true, direction, previouslyFocusedRect);
4504            refreshDrawableState();
4505        }
4506    }
4507
4508    /**
4509     * Request that a rectangle of this view be visible on the screen,
4510     * scrolling if necessary just enough.
4511     *
4512     * <p>A View should call this if it maintains some notion of which part
4513     * of its content is interesting.  For example, a text editing view
4514     * should call this when its cursor moves.
4515     *
4516     * @param rectangle The rectangle.
4517     * @return Whether any parent scrolled.
4518     */
4519    public boolean requestRectangleOnScreen(Rect rectangle) {
4520        return requestRectangleOnScreen(rectangle, false);
4521    }
4522
4523    /**
4524     * Request that a rectangle of this view be visible on the screen,
4525     * scrolling if necessary just enough.
4526     *
4527     * <p>A View should call this if it maintains some notion of which part
4528     * of its content is interesting.  For example, a text editing view
4529     * should call this when its cursor moves.
4530     *
4531     * <p>When <code>immediate</code> is set to true, scrolling will not be
4532     * animated.
4533     *
4534     * @param rectangle The rectangle.
4535     * @param immediate True to forbid animated scrolling, false otherwise
4536     * @return Whether any parent scrolled.
4537     */
4538    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4539        if (mParent == null) {
4540            return false;
4541        }
4542
4543        View child = this;
4544
4545        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4546        position.set(rectangle);
4547
4548        ViewParent parent = mParent;
4549        boolean scrolled = false;
4550        while (parent != null) {
4551            rectangle.set((int) position.left, (int) position.top,
4552                    (int) position.right, (int) position.bottom);
4553
4554            scrolled |= parent.requestChildRectangleOnScreen(child,
4555                    rectangle, immediate);
4556
4557            if (!child.hasIdentityMatrix()) {
4558                child.getMatrix().mapRect(position);
4559            }
4560
4561            position.offset(child.mLeft, child.mTop);
4562
4563            if (!(parent instanceof View)) {
4564                break;
4565            }
4566
4567            View parentView = (View) parent;
4568
4569            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4570
4571            child = parentView;
4572            parent = child.getParent();
4573        }
4574
4575        return scrolled;
4576    }
4577
4578    /**
4579     * Called when this view wants to give up focus. If focus is cleared
4580     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4581     * <p>
4582     * <strong>Note:</strong> When a View clears focus the framework is trying
4583     * to give focus to the first focusable View from the top. Hence, if this
4584     * View is the first from the top that can take focus, then all callbacks
4585     * related to clearing focus will be invoked after wich the framework will
4586     * give focus to this view.
4587     * </p>
4588     */
4589    public void clearFocus() {
4590        if (DBG) {
4591            System.out.println(this + " clearFocus()");
4592        }
4593
4594        clearFocusInternal(true, true);
4595    }
4596
4597    /**
4598     * Clears focus from the view, optionally propagating the change up through
4599     * the parent hierarchy and requesting that the root view place new focus.
4600     *
4601     * @param propagate whether to propagate the change up through the parent
4602     *            hierarchy
4603     * @param refocus when propagate is true, specifies whether to request the
4604     *            root view place new focus
4605     */
4606    void clearFocusInternal(boolean propagate, boolean refocus) {
4607        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4608            mPrivateFlags &= ~PFLAG_FOCUSED;
4609
4610            if (propagate && mParent != null) {
4611                mParent.clearChildFocus(this);
4612            }
4613
4614            onFocusChanged(false, 0, null);
4615
4616            refreshDrawableState();
4617
4618            if (propagate && (!refocus || !rootViewRequestFocus())) {
4619                notifyGlobalFocusCleared(this);
4620            }
4621        }
4622    }
4623
4624    void notifyGlobalFocusCleared(View oldFocus) {
4625        if (oldFocus != null && mAttachInfo != null) {
4626            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4627        }
4628    }
4629
4630    boolean rootViewRequestFocus() {
4631        final View root = getRootView();
4632        return root != null && root.requestFocus();
4633    }
4634
4635    /**
4636     * Called internally by the view system when a new view is getting focus.
4637     * This is what clears the old focus.
4638     * <p>
4639     * <b>NOTE:</b> The parent view's focused child must be updated manually
4640     * after calling this method. Otherwise, the view hierarchy may be left in
4641     * an inconstent state.
4642     */
4643    void unFocus() {
4644        if (DBG) {
4645            System.out.println(this + " unFocus()");
4646        }
4647
4648        clearFocusInternal(false, false);
4649    }
4650
4651    /**
4652     * Returns true if this view has focus iteself, or is the ancestor of the
4653     * view that has focus.
4654     *
4655     * @return True if this view has or contains focus, false otherwise.
4656     */
4657    @ViewDebug.ExportedProperty(category = "focus")
4658    public boolean hasFocus() {
4659        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4660    }
4661
4662    /**
4663     * Returns true if this view is focusable or if it contains a reachable View
4664     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4665     * is a View whose parents do not block descendants focus.
4666     *
4667     * Only {@link #VISIBLE} views are considered focusable.
4668     *
4669     * @return True if the view is focusable or if the view contains a focusable
4670     *         View, false otherwise.
4671     *
4672     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4673     */
4674    public boolean hasFocusable() {
4675        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4676    }
4677
4678    /**
4679     * Called by the view system when the focus state of this view changes.
4680     * When the focus change event is caused by directional navigation, direction
4681     * and previouslyFocusedRect provide insight into where the focus is coming from.
4682     * When overriding, be sure to call up through to the super class so that
4683     * the standard focus handling will occur.
4684     *
4685     * @param gainFocus True if the View has focus; false otherwise.
4686     * @param direction The direction focus has moved when requestFocus()
4687     *                  is called to give this view focus. Values are
4688     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4689     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4690     *                  It may not always apply, in which case use the default.
4691     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4692     *        system, of the previously focused view.  If applicable, this will be
4693     *        passed in as finer grained information about where the focus is coming
4694     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4695     */
4696    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4697        if (gainFocus) {
4698            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4699        } else {
4700            notifyViewAccessibilityStateChangedIfNeeded();
4701        }
4702
4703        InputMethodManager imm = InputMethodManager.peekInstance();
4704        if (!gainFocus) {
4705            if (isPressed()) {
4706                setPressed(false);
4707            }
4708            if (imm != null && mAttachInfo != null
4709                    && mAttachInfo.mHasWindowFocus) {
4710                imm.focusOut(this);
4711            }
4712            onFocusLost();
4713        } else if (imm != null && mAttachInfo != null
4714                && mAttachInfo.mHasWindowFocus) {
4715            imm.focusIn(this);
4716        }
4717
4718        invalidate(true);
4719        ListenerInfo li = mListenerInfo;
4720        if (li != null && li.mOnFocusChangeListener != null) {
4721            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4722        }
4723
4724        if (mAttachInfo != null) {
4725            mAttachInfo.mKeyDispatchState.reset(this);
4726        }
4727    }
4728
4729    /**
4730     * Sends an accessibility event of the given type. If accessibility is
4731     * not enabled this method has no effect. The default implementation calls
4732     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4733     * to populate information about the event source (this View), then calls
4734     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4735     * populate the text content of the event source including its descendants,
4736     * and last calls
4737     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4738     * on its parent to resuest sending of the event to interested parties.
4739     * <p>
4740     * If an {@link AccessibilityDelegate} has been specified via calling
4741     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4742     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4743     * responsible for handling this call.
4744     * </p>
4745     *
4746     * @param eventType The type of the event to send, as defined by several types from
4747     * {@link android.view.accessibility.AccessibilityEvent}, such as
4748     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4749     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4750     *
4751     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4752     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4753     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4754     * @see AccessibilityDelegate
4755     */
4756    public void sendAccessibilityEvent(int eventType) {
4757        // Excluded views do not send accessibility events.
4758        if (!includeForAccessibility()) {
4759            return;
4760        }
4761        if (mAccessibilityDelegate != null) {
4762            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4763        } else {
4764            sendAccessibilityEventInternal(eventType);
4765        }
4766    }
4767
4768    /**
4769     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4770     * {@link AccessibilityEvent} to make an announcement which is related to some
4771     * sort of a context change for which none of the events representing UI transitions
4772     * is a good fit. For example, announcing a new page in a book. If accessibility
4773     * is not enabled this method does nothing.
4774     *
4775     * @param text The announcement text.
4776     */
4777    public void announceForAccessibility(CharSequence text) {
4778        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4779            AccessibilityEvent event = AccessibilityEvent.obtain(
4780                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4781            onInitializeAccessibilityEvent(event);
4782            event.getText().add(text);
4783            event.setContentDescription(null);
4784            mParent.requestSendAccessibilityEvent(this, event);
4785        }
4786    }
4787
4788    /**
4789     * @see #sendAccessibilityEvent(int)
4790     *
4791     * Note: Called from the default {@link AccessibilityDelegate}.
4792     */
4793    void sendAccessibilityEventInternal(int eventType) {
4794        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4795            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4796        }
4797    }
4798
4799    /**
4800     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4801     * takes as an argument an empty {@link AccessibilityEvent} and does not
4802     * perform a check whether accessibility is enabled.
4803     * <p>
4804     * If an {@link AccessibilityDelegate} has been specified via calling
4805     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4806     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4807     * is responsible for handling this call.
4808     * </p>
4809     *
4810     * @param event The event to send.
4811     *
4812     * @see #sendAccessibilityEvent(int)
4813     */
4814    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4815        if (mAccessibilityDelegate != null) {
4816            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4817        } else {
4818            sendAccessibilityEventUncheckedInternal(event);
4819        }
4820    }
4821
4822    /**
4823     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4824     *
4825     * Note: Called from the default {@link AccessibilityDelegate}.
4826     */
4827    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4828        if (!isShown()) {
4829            return;
4830        }
4831        onInitializeAccessibilityEvent(event);
4832        // Only a subset of accessibility events populates text content.
4833        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4834            dispatchPopulateAccessibilityEvent(event);
4835        }
4836        // In the beginning we called #isShown(), so we know that getParent() is not null.
4837        getParent().requestSendAccessibilityEvent(this, event);
4838    }
4839
4840    /**
4841     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4842     * to its children for adding their text content to the event. Note that the
4843     * event text is populated in a separate dispatch path since we add to the
4844     * event not only the text of the source but also the text of all its descendants.
4845     * A typical implementation will call
4846     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4847     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4848     * on each child. Override this method if custom population of the event text
4849     * content is required.
4850     * <p>
4851     * If an {@link AccessibilityDelegate} has been specified via calling
4852     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4853     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4854     * is responsible for handling this call.
4855     * </p>
4856     * <p>
4857     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4858     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4859     * </p>
4860     *
4861     * @param event The event.
4862     *
4863     * @return True if the event population was completed.
4864     */
4865    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4866        if (mAccessibilityDelegate != null) {
4867            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4868        } else {
4869            return dispatchPopulateAccessibilityEventInternal(event);
4870        }
4871    }
4872
4873    /**
4874     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4875     *
4876     * Note: Called from the default {@link AccessibilityDelegate}.
4877     */
4878    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4879        onPopulateAccessibilityEvent(event);
4880        return false;
4881    }
4882
4883    /**
4884     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4885     * giving a chance to this View to populate the accessibility event with its
4886     * text content. While this method is free to modify event
4887     * attributes other than text content, doing so should normally be performed in
4888     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4889     * <p>
4890     * Example: Adding formatted date string to an accessibility event in addition
4891     *          to the text added by the super implementation:
4892     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4893     *     super.onPopulateAccessibilityEvent(event);
4894     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4895     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4896     *         mCurrentDate.getTimeInMillis(), flags);
4897     *     event.getText().add(selectedDateUtterance);
4898     * }</pre>
4899     * <p>
4900     * If an {@link AccessibilityDelegate} has been specified via calling
4901     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4902     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4903     * is responsible for handling this call.
4904     * </p>
4905     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4906     * information to the event, in case the default implementation has basic information to add.
4907     * </p>
4908     *
4909     * @param event The accessibility event which to populate.
4910     *
4911     * @see #sendAccessibilityEvent(int)
4912     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4913     */
4914    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4915        if (mAccessibilityDelegate != null) {
4916            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4917        } else {
4918            onPopulateAccessibilityEventInternal(event);
4919        }
4920    }
4921
4922    /**
4923     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4924     *
4925     * Note: Called from the default {@link AccessibilityDelegate}.
4926     */
4927    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4928    }
4929
4930    /**
4931     * Initializes an {@link AccessibilityEvent} with information about
4932     * this View which is the event source. In other words, the source of
4933     * an accessibility event is the view whose state change triggered firing
4934     * the event.
4935     * <p>
4936     * Example: Setting the password property of an event in addition
4937     *          to properties set by the super implementation:
4938     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4939     *     super.onInitializeAccessibilityEvent(event);
4940     *     event.setPassword(true);
4941     * }</pre>
4942     * <p>
4943     * If an {@link AccessibilityDelegate} has been specified via calling
4944     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4945     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4946     * is responsible for handling this call.
4947     * </p>
4948     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4949     * information to the event, in case the default implementation has basic information to add.
4950     * </p>
4951     * @param event The event to initialize.
4952     *
4953     * @see #sendAccessibilityEvent(int)
4954     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4955     */
4956    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4957        if (mAccessibilityDelegate != null) {
4958            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4959        } else {
4960            onInitializeAccessibilityEventInternal(event);
4961        }
4962    }
4963
4964    /**
4965     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4966     *
4967     * Note: Called from the default {@link AccessibilityDelegate}.
4968     */
4969    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4970        event.setSource(this);
4971        event.setClassName(View.class.getName());
4972        event.setPackageName(getContext().getPackageName());
4973        event.setEnabled(isEnabled());
4974        event.setContentDescription(mContentDescription);
4975
4976        switch (event.getEventType()) {
4977            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4978                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4979                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4980                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4981                event.setItemCount(focusablesTempList.size());
4982                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4983                if (mAttachInfo != null) {
4984                    focusablesTempList.clear();
4985                }
4986            } break;
4987            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4988                CharSequence text = getIterableTextForAccessibility();
4989                if (text != null && text.length() > 0) {
4990                    event.setFromIndex(getAccessibilitySelectionStart());
4991                    event.setToIndex(getAccessibilitySelectionEnd());
4992                    event.setItemCount(text.length());
4993                }
4994            } break;
4995        }
4996    }
4997
4998    /**
4999     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5000     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5001     * This method is responsible for obtaining an accessibility node info from a
5002     * pool of reusable instances and calling
5003     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5004     * initialize the former.
5005     * <p>
5006     * Note: The client is responsible for recycling the obtained instance by calling
5007     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5008     * </p>
5009     *
5010     * @return A populated {@link AccessibilityNodeInfo}.
5011     *
5012     * @see AccessibilityNodeInfo
5013     */
5014    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5015        if (mAccessibilityDelegate != null) {
5016            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5017        } else {
5018            return createAccessibilityNodeInfoInternal();
5019        }
5020    }
5021
5022    /**
5023     * @see #createAccessibilityNodeInfo()
5024     */
5025    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5026        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5027        if (provider != null) {
5028            return provider.createAccessibilityNodeInfo(View.NO_ID);
5029        } else {
5030            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5031            onInitializeAccessibilityNodeInfo(info);
5032            return info;
5033        }
5034    }
5035
5036    /**
5037     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5038     * The base implementation sets:
5039     * <ul>
5040     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5041     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5042     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5043     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5044     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5045     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5046     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5047     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5048     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5049     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5050     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5051     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5052     * </ul>
5053     * <p>
5054     * Subclasses should override this method, call the super implementation,
5055     * and set additional attributes.
5056     * </p>
5057     * <p>
5058     * If an {@link AccessibilityDelegate} has been specified via calling
5059     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5060     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5061     * is responsible for handling this call.
5062     * </p>
5063     *
5064     * @param info The instance to initialize.
5065     */
5066    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5067        if (mAccessibilityDelegate != null) {
5068            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5069        } else {
5070            onInitializeAccessibilityNodeInfoInternal(info);
5071        }
5072    }
5073
5074    /**
5075     * Gets the location of this view in screen coordintates.
5076     *
5077     * @param outRect The output location
5078     */
5079    void getBoundsOnScreen(Rect outRect) {
5080        if (mAttachInfo == null) {
5081            return;
5082        }
5083
5084        RectF position = mAttachInfo.mTmpTransformRect;
5085        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5086
5087        if (!hasIdentityMatrix()) {
5088            getMatrix().mapRect(position);
5089        }
5090
5091        position.offset(mLeft, mTop);
5092
5093        ViewParent parent = mParent;
5094        while (parent instanceof View) {
5095            View parentView = (View) parent;
5096
5097            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5098
5099            if (!parentView.hasIdentityMatrix()) {
5100                parentView.getMatrix().mapRect(position);
5101            }
5102
5103            position.offset(parentView.mLeft, parentView.mTop);
5104
5105            parent = parentView.mParent;
5106        }
5107
5108        if (parent instanceof ViewRootImpl) {
5109            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5110            position.offset(0, -viewRootImpl.mCurScrollY);
5111        }
5112
5113        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5114
5115        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5116                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5117    }
5118
5119    /**
5120     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5121     *
5122     * Note: Called from the default {@link AccessibilityDelegate}.
5123     */
5124    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5125        Rect bounds = mAttachInfo.mTmpInvalRect;
5126
5127        getDrawingRect(bounds);
5128        info.setBoundsInParent(bounds);
5129
5130        getBoundsOnScreen(bounds);
5131        info.setBoundsInScreen(bounds);
5132
5133        ViewParent parent = getParentForAccessibility();
5134        if (parent instanceof View) {
5135            info.setParent((View) parent);
5136        }
5137
5138        if (mID != View.NO_ID) {
5139            View rootView = getRootView();
5140            if (rootView == null) {
5141                rootView = this;
5142            }
5143            View label = rootView.findLabelForView(this, mID);
5144            if (label != null) {
5145                info.setLabeledBy(label);
5146            }
5147
5148            if ((mAttachInfo.mAccessibilityFetchFlags
5149                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5150                    && Resources.resourceHasPackage(mID)) {
5151                try {
5152                    String viewId = getResources().getResourceName(mID);
5153                    info.setViewIdResourceName(viewId);
5154                } catch (Resources.NotFoundException nfe) {
5155                    /* ignore */
5156                }
5157            }
5158        }
5159
5160        if (mLabelForId != View.NO_ID) {
5161            View rootView = getRootView();
5162            if (rootView == null) {
5163                rootView = this;
5164            }
5165            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5166            if (labeled != null) {
5167                info.setLabelFor(labeled);
5168            }
5169        }
5170
5171        info.setVisibleToUser(isVisibleToUser());
5172
5173        info.setPackageName(mContext.getPackageName());
5174        info.setClassName(View.class.getName());
5175        info.setContentDescription(getContentDescription());
5176
5177        info.setEnabled(isEnabled());
5178        info.setClickable(isClickable());
5179        info.setFocusable(isFocusable());
5180        info.setFocused(isFocused());
5181        info.setAccessibilityFocused(isAccessibilityFocused());
5182        info.setSelected(isSelected());
5183        info.setLongClickable(isLongClickable());
5184
5185        // TODO: These make sense only if we are in an AdapterView but all
5186        // views can be selected. Maybe from accessibility perspective
5187        // we should report as selectable view in an AdapterView.
5188        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5189        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5190
5191        if (isFocusable()) {
5192            if (isFocused()) {
5193                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5194            } else {
5195                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5196            }
5197        }
5198
5199        if (!isAccessibilityFocused()) {
5200            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5201        } else {
5202            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5203        }
5204
5205        if (isClickable() && isEnabled()) {
5206            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5207        }
5208
5209        if (isLongClickable() && isEnabled()) {
5210            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5211        }
5212
5213        CharSequence text = getIterableTextForAccessibility();
5214        if (text != null && text.length() > 0) {
5215            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5216
5217            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5218            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5219            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5220            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5221                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5222                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5223        }
5224    }
5225
5226    private View findLabelForView(View view, int labeledId) {
5227        if (mMatchLabelForPredicate == null) {
5228            mMatchLabelForPredicate = new MatchLabelForPredicate();
5229        }
5230        mMatchLabelForPredicate.mLabeledId = labeledId;
5231        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5232    }
5233
5234    /**
5235     * Computes whether this view is visible to the user. Such a view is
5236     * attached, visible, all its predecessors are visible, it is not clipped
5237     * entirely by its predecessors, and has an alpha greater than zero.
5238     *
5239     * @return Whether the view is visible on the screen.
5240     *
5241     * @hide
5242     */
5243    protected boolean isVisibleToUser() {
5244        return isVisibleToUser(null);
5245    }
5246
5247    /**
5248     * Computes whether the given portion of this view is visible to the user.
5249     * Such a view is attached, visible, all its predecessors are visible,
5250     * has an alpha greater than zero, and the specified portion is not
5251     * clipped entirely by its predecessors.
5252     *
5253     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5254     *                    <code>null</code>, and the entire view will be tested in this case.
5255     *                    When <code>true</code> is returned by the function, the actual visible
5256     *                    region will be stored in this parameter; that is, if boundInView is fully
5257     *                    contained within the view, no modification will be made, otherwise regions
5258     *                    outside of the visible area of the view will be clipped.
5259     *
5260     * @return Whether the specified portion of the view is visible on the screen.
5261     *
5262     * @hide
5263     */
5264    protected boolean isVisibleToUser(Rect boundInView) {
5265        if (mAttachInfo != null) {
5266            // Attached to invisible window means this view is not visible.
5267            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5268                return false;
5269            }
5270            // An invisible predecessor or one with alpha zero means
5271            // that this view is not visible to the user.
5272            Object current = this;
5273            while (current instanceof View) {
5274                View view = (View) current;
5275                // We have attach info so this view is attached and there is no
5276                // need to check whether we reach to ViewRootImpl on the way up.
5277                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5278                    return false;
5279                }
5280                current = view.mParent;
5281            }
5282            // Check if the view is entirely covered by its predecessors.
5283            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5284            Point offset = mAttachInfo.mPoint;
5285            if (!getGlobalVisibleRect(visibleRect, offset)) {
5286                return false;
5287            }
5288            // Check if the visible portion intersects the rectangle of interest.
5289            if (boundInView != null) {
5290                visibleRect.offset(-offset.x, -offset.y);
5291                return boundInView.intersect(visibleRect);
5292            }
5293            return true;
5294        }
5295        return false;
5296    }
5297
5298    /**
5299     * Returns the delegate for implementing accessibility support via
5300     * composition. For more details see {@link AccessibilityDelegate}.
5301     *
5302     * @return The delegate, or null if none set.
5303     *
5304     * @hide
5305     */
5306    public AccessibilityDelegate getAccessibilityDelegate() {
5307        return mAccessibilityDelegate;
5308    }
5309
5310    /**
5311     * Sets a delegate for implementing accessibility support via composition as
5312     * opposed to inheritance. The delegate's primary use is for implementing
5313     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5314     *
5315     * @param delegate The delegate instance.
5316     *
5317     * @see AccessibilityDelegate
5318     */
5319    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5320        mAccessibilityDelegate = delegate;
5321    }
5322
5323    /**
5324     * Gets the provider for managing a virtual view hierarchy rooted at this View
5325     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5326     * that explore the window content.
5327     * <p>
5328     * If this method returns an instance, this instance is responsible for managing
5329     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5330     * View including the one representing the View itself. Similarly the returned
5331     * instance is responsible for performing accessibility actions on any virtual
5332     * view or the root view itself.
5333     * </p>
5334     * <p>
5335     * If an {@link AccessibilityDelegate} has been specified via calling
5336     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5337     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5338     * is responsible for handling this call.
5339     * </p>
5340     *
5341     * @return The provider.
5342     *
5343     * @see AccessibilityNodeProvider
5344     */
5345    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5346        if (mAccessibilityDelegate != null) {
5347            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5348        } else {
5349            return null;
5350        }
5351    }
5352
5353    /**
5354     * Gets the unique identifier of this view on the screen for accessibility purposes.
5355     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5356     *
5357     * @return The view accessibility id.
5358     *
5359     * @hide
5360     */
5361    public int getAccessibilityViewId() {
5362        if (mAccessibilityViewId == NO_ID) {
5363            mAccessibilityViewId = sNextAccessibilityViewId++;
5364        }
5365        return mAccessibilityViewId;
5366    }
5367
5368    /**
5369     * Gets the unique identifier of the window in which this View reseides.
5370     *
5371     * @return The window accessibility id.
5372     *
5373     * @hide
5374     */
5375    public int getAccessibilityWindowId() {
5376        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5377    }
5378
5379    /**
5380     * Gets the {@link View} description. It briefly describes the view and is
5381     * primarily used for accessibility support. Set this property to enable
5382     * better accessibility support for your application. This is especially
5383     * true for views that do not have textual representation (For example,
5384     * ImageButton).
5385     *
5386     * @return The content description.
5387     *
5388     * @attr ref android.R.styleable#View_contentDescription
5389     */
5390    @ViewDebug.ExportedProperty(category = "accessibility")
5391    public CharSequence getContentDescription() {
5392        return mContentDescription;
5393    }
5394
5395    /**
5396     * Sets the {@link View} description. It briefly describes the view and is
5397     * primarily used for accessibility support. Set this property to enable
5398     * better accessibility support for your application. This is especially
5399     * true for views that do not have textual representation (For example,
5400     * ImageButton).
5401     *
5402     * @param contentDescription The content description.
5403     *
5404     * @attr ref android.R.styleable#View_contentDescription
5405     */
5406    @RemotableViewMethod
5407    public void setContentDescription(CharSequence contentDescription) {
5408        if (mContentDescription == null) {
5409            if (contentDescription == null) {
5410                return;
5411            }
5412        } else if (mContentDescription.equals(contentDescription)) {
5413            return;
5414        }
5415        mContentDescription = contentDescription;
5416        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5417        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5418            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5419            notifySubtreeAccessibilityStateChangedIfNeeded();
5420        } else {
5421            notifyViewAccessibilityStateChangedIfNeeded();
5422        }
5423    }
5424
5425    /**
5426     * Gets the id of a view for which this view serves as a label for
5427     * accessibility purposes.
5428     *
5429     * @return The labeled view id.
5430     */
5431    @ViewDebug.ExportedProperty(category = "accessibility")
5432    public int getLabelFor() {
5433        return mLabelForId;
5434    }
5435
5436    /**
5437     * Sets the id of a view for which this view serves as a label for
5438     * accessibility purposes.
5439     *
5440     * @param id The labeled view id.
5441     */
5442    @RemotableViewMethod
5443    public void setLabelFor(int id) {
5444        mLabelForId = id;
5445        if (mLabelForId != View.NO_ID
5446                && mID == View.NO_ID) {
5447            mID = generateViewId();
5448        }
5449    }
5450
5451    /**
5452     * Invoked whenever this view loses focus, either by losing window focus or by losing
5453     * focus within its window. This method can be used to clear any state tied to the
5454     * focus. For instance, if a button is held pressed with the trackball and the window
5455     * loses focus, this method can be used to cancel the press.
5456     *
5457     * Subclasses of View overriding this method should always call super.onFocusLost().
5458     *
5459     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5460     * @see #onWindowFocusChanged(boolean)
5461     *
5462     * @hide pending API council approval
5463     */
5464    protected void onFocusLost() {
5465        resetPressedState();
5466    }
5467
5468    private void resetPressedState() {
5469        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5470            return;
5471        }
5472
5473        if (isPressed()) {
5474            setPressed(false);
5475
5476            if (!mHasPerformedLongPress) {
5477                removeLongPressCallback();
5478            }
5479        }
5480    }
5481
5482    /**
5483     * Returns true if this view has focus
5484     *
5485     * @return True if this view has focus, false otherwise.
5486     */
5487    @ViewDebug.ExportedProperty(category = "focus")
5488    public boolean isFocused() {
5489        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5490    }
5491
5492    /**
5493     * Find the view in the hierarchy rooted at this view that currently has
5494     * focus.
5495     *
5496     * @return The view that currently has focus, or null if no focused view can
5497     *         be found.
5498     */
5499    public View findFocus() {
5500        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5501    }
5502
5503    /**
5504     * Indicates whether this view is one of the set of scrollable containers in
5505     * its window.
5506     *
5507     * @return whether this view is one of the set of scrollable containers in
5508     * its window
5509     *
5510     * @attr ref android.R.styleable#View_isScrollContainer
5511     */
5512    public boolean isScrollContainer() {
5513        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5514    }
5515
5516    /**
5517     * Change whether this view is one of the set of scrollable containers in
5518     * its window.  This will be used to determine whether the window can
5519     * resize or must pan when a soft input area is open -- scrollable
5520     * containers allow the window to use resize mode since the container
5521     * will appropriately shrink.
5522     *
5523     * @attr ref android.R.styleable#View_isScrollContainer
5524     */
5525    public void setScrollContainer(boolean isScrollContainer) {
5526        if (isScrollContainer) {
5527            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5528                mAttachInfo.mScrollContainers.add(this);
5529                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5530            }
5531            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5532        } else {
5533            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5534                mAttachInfo.mScrollContainers.remove(this);
5535            }
5536            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5537        }
5538    }
5539
5540    /**
5541     * Returns the quality of the drawing cache.
5542     *
5543     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5544     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5545     *
5546     * @see #setDrawingCacheQuality(int)
5547     * @see #setDrawingCacheEnabled(boolean)
5548     * @see #isDrawingCacheEnabled()
5549     *
5550     * @attr ref android.R.styleable#View_drawingCacheQuality
5551     */
5552    public int getDrawingCacheQuality() {
5553        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5554    }
5555
5556    /**
5557     * Set the drawing cache quality of this view. This value is used only when the
5558     * drawing cache is enabled
5559     *
5560     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5561     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5562     *
5563     * @see #getDrawingCacheQuality()
5564     * @see #setDrawingCacheEnabled(boolean)
5565     * @see #isDrawingCacheEnabled()
5566     *
5567     * @attr ref android.R.styleable#View_drawingCacheQuality
5568     */
5569    public void setDrawingCacheQuality(int quality) {
5570        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5571    }
5572
5573    /**
5574     * Returns whether the screen should remain on, corresponding to the current
5575     * value of {@link #KEEP_SCREEN_ON}.
5576     *
5577     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5578     *
5579     * @see #setKeepScreenOn(boolean)
5580     *
5581     * @attr ref android.R.styleable#View_keepScreenOn
5582     */
5583    public boolean getKeepScreenOn() {
5584        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5585    }
5586
5587    /**
5588     * Controls whether the screen should remain on, modifying the
5589     * value of {@link #KEEP_SCREEN_ON}.
5590     *
5591     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5592     *
5593     * @see #getKeepScreenOn()
5594     *
5595     * @attr ref android.R.styleable#View_keepScreenOn
5596     */
5597    public void setKeepScreenOn(boolean keepScreenOn) {
5598        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5599    }
5600
5601    /**
5602     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5603     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5604     *
5605     * @attr ref android.R.styleable#View_nextFocusLeft
5606     */
5607    public int getNextFocusLeftId() {
5608        return mNextFocusLeftId;
5609    }
5610
5611    /**
5612     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5613     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5614     * decide automatically.
5615     *
5616     * @attr ref android.R.styleable#View_nextFocusLeft
5617     */
5618    public void setNextFocusLeftId(int nextFocusLeftId) {
5619        mNextFocusLeftId = nextFocusLeftId;
5620    }
5621
5622    /**
5623     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5624     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5625     *
5626     * @attr ref android.R.styleable#View_nextFocusRight
5627     */
5628    public int getNextFocusRightId() {
5629        return mNextFocusRightId;
5630    }
5631
5632    /**
5633     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5634     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5635     * decide automatically.
5636     *
5637     * @attr ref android.R.styleable#View_nextFocusRight
5638     */
5639    public void setNextFocusRightId(int nextFocusRightId) {
5640        mNextFocusRightId = nextFocusRightId;
5641    }
5642
5643    /**
5644     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5645     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5646     *
5647     * @attr ref android.R.styleable#View_nextFocusUp
5648     */
5649    public int getNextFocusUpId() {
5650        return mNextFocusUpId;
5651    }
5652
5653    /**
5654     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5655     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5656     * decide automatically.
5657     *
5658     * @attr ref android.R.styleable#View_nextFocusUp
5659     */
5660    public void setNextFocusUpId(int nextFocusUpId) {
5661        mNextFocusUpId = nextFocusUpId;
5662    }
5663
5664    /**
5665     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5666     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5667     *
5668     * @attr ref android.R.styleable#View_nextFocusDown
5669     */
5670    public int getNextFocusDownId() {
5671        return mNextFocusDownId;
5672    }
5673
5674    /**
5675     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5676     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5677     * decide automatically.
5678     *
5679     * @attr ref android.R.styleable#View_nextFocusDown
5680     */
5681    public void setNextFocusDownId(int nextFocusDownId) {
5682        mNextFocusDownId = nextFocusDownId;
5683    }
5684
5685    /**
5686     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5687     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5688     *
5689     * @attr ref android.R.styleable#View_nextFocusForward
5690     */
5691    public int getNextFocusForwardId() {
5692        return mNextFocusForwardId;
5693    }
5694
5695    /**
5696     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5697     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5698     * decide automatically.
5699     *
5700     * @attr ref android.R.styleable#View_nextFocusForward
5701     */
5702    public void setNextFocusForwardId(int nextFocusForwardId) {
5703        mNextFocusForwardId = nextFocusForwardId;
5704    }
5705
5706    /**
5707     * Returns the visibility of this view and all of its ancestors
5708     *
5709     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5710     */
5711    public boolean isShown() {
5712        View current = this;
5713        //noinspection ConstantConditions
5714        do {
5715            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5716                return false;
5717            }
5718            ViewParent parent = current.mParent;
5719            if (parent == null) {
5720                return false; // We are not attached to the view root
5721            }
5722            if (!(parent instanceof View)) {
5723                return true;
5724            }
5725            current = (View) parent;
5726        } while (current != null);
5727
5728        return false;
5729    }
5730
5731    /**
5732     * Called by the view hierarchy when the content insets for a window have
5733     * changed, to allow it to adjust its content to fit within those windows.
5734     * The content insets tell you the space that the status bar, input method,
5735     * and other system windows infringe on the application's window.
5736     *
5737     * <p>You do not normally need to deal with this function, since the default
5738     * window decoration given to applications takes care of applying it to the
5739     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5740     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5741     * and your content can be placed under those system elements.  You can then
5742     * use this method within your view hierarchy if you have parts of your UI
5743     * which you would like to ensure are not being covered.
5744     *
5745     * <p>The default implementation of this method simply applies the content
5746     * insets to the view's padding, consuming that content (modifying the
5747     * insets to be 0), and returning true.  This behavior is off by default, but can
5748     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5749     *
5750     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5751     * insets object is propagated down the hierarchy, so any changes made to it will
5752     * be seen by all following views (including potentially ones above in
5753     * the hierarchy since this is a depth-first traversal).  The first view
5754     * that returns true will abort the entire traversal.
5755     *
5756     * <p>The default implementation works well for a situation where it is
5757     * used with a container that covers the entire window, allowing it to
5758     * apply the appropriate insets to its content on all edges.  If you need
5759     * a more complicated layout (such as two different views fitting system
5760     * windows, one on the top of the window, and one on the bottom),
5761     * you can override the method and handle the insets however you would like.
5762     * Note that the insets provided by the framework are always relative to the
5763     * far edges of the window, not accounting for the location of the called view
5764     * within that window.  (In fact when this method is called you do not yet know
5765     * where the layout will place the view, as it is done before layout happens.)
5766     *
5767     * <p>Note: unlike many View methods, there is no dispatch phase to this
5768     * call.  If you are overriding it in a ViewGroup and want to allow the
5769     * call to continue to your children, you must be sure to call the super
5770     * implementation.
5771     *
5772     * <p>Here is a sample layout that makes use of fitting system windows
5773     * to have controls for a video view placed inside of the window decorations
5774     * that it hides and shows.  This can be used with code like the second
5775     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5776     *
5777     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5778     *
5779     * @param insets Current content insets of the window.  Prior to
5780     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5781     * the insets or else you and Android will be unhappy.
5782     *
5783     * @return {@code true} if this view applied the insets and it should not
5784     * continue propagating further down the hierarchy, {@code false} otherwise.
5785     * @see #getFitsSystemWindows()
5786     * @see #setFitsSystemWindows(boolean)
5787     * @see #setSystemUiVisibility(int)
5788     */
5789    protected boolean fitSystemWindows(Rect insets) {
5790        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5791            mUserPaddingStart = UNDEFINED_PADDING;
5792            mUserPaddingEnd = UNDEFINED_PADDING;
5793            Rect localInsets = sThreadLocal.get();
5794            if (localInsets == null) {
5795                localInsets = new Rect();
5796                sThreadLocal.set(localInsets);
5797            }
5798            boolean res = computeFitSystemWindows(insets, localInsets);
5799            internalSetPadding(localInsets.left, localInsets.top,
5800                    localInsets.right, localInsets.bottom);
5801            return res;
5802        }
5803        return false;
5804    }
5805
5806    /**
5807     * @hide Compute the insets that should be consumed by this view and the ones
5808     * that should propagate to those under it.
5809     */
5810    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5811        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5812                || mAttachInfo == null
5813                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5814                        && !mAttachInfo.mOverscanRequested)) {
5815            outLocalInsets.set(inoutInsets);
5816            inoutInsets.set(0, 0, 0, 0);
5817            return true;
5818        } else {
5819            // The application wants to take care of fitting system window for
5820            // the content...  however we still need to take care of any overscan here.
5821            final Rect overscan = mAttachInfo.mOverscanInsets;
5822            outLocalInsets.set(overscan);
5823            inoutInsets.left -= overscan.left;
5824            inoutInsets.top -= overscan.top;
5825            inoutInsets.right -= overscan.right;
5826            inoutInsets.bottom -= overscan.bottom;
5827            return false;
5828        }
5829    }
5830
5831    /**
5832     * Sets whether or not this view should account for system screen decorations
5833     * such as the status bar and inset its content; that is, controlling whether
5834     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5835     * executed.  See that method for more details.
5836     *
5837     * <p>Note that if you are providing your own implementation of
5838     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5839     * flag to true -- your implementation will be overriding the default
5840     * implementation that checks this flag.
5841     *
5842     * @param fitSystemWindows If true, then the default implementation of
5843     * {@link #fitSystemWindows(Rect)} will be executed.
5844     *
5845     * @attr ref android.R.styleable#View_fitsSystemWindows
5846     * @see #getFitsSystemWindows()
5847     * @see #fitSystemWindows(Rect)
5848     * @see #setSystemUiVisibility(int)
5849     */
5850    public void setFitsSystemWindows(boolean fitSystemWindows) {
5851        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5852    }
5853
5854    /**
5855     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5856     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5857     * will be executed.
5858     *
5859     * @return {@code true} if the default implementation of
5860     * {@link #fitSystemWindows(Rect)} will be executed.
5861     *
5862     * @attr ref android.R.styleable#View_fitsSystemWindows
5863     * @see #setFitsSystemWindows(boolean)
5864     * @see #fitSystemWindows(Rect)
5865     * @see #setSystemUiVisibility(int)
5866     */
5867    public boolean getFitsSystemWindows() {
5868        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5869    }
5870
5871    /** @hide */
5872    public boolean fitsSystemWindows() {
5873        return getFitsSystemWindows();
5874    }
5875
5876    /**
5877     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5878     */
5879    public void requestFitSystemWindows() {
5880        if (mParent != null) {
5881            mParent.requestFitSystemWindows();
5882        }
5883    }
5884
5885    /**
5886     * For use by PhoneWindow to make its own system window fitting optional.
5887     * @hide
5888     */
5889    public void makeOptionalFitsSystemWindows() {
5890        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5891    }
5892
5893    /**
5894     * Returns the visibility status for this view.
5895     *
5896     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5897     * @attr ref android.R.styleable#View_visibility
5898     */
5899    @ViewDebug.ExportedProperty(mapping = {
5900        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5901        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5902        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5903    })
5904    public int getVisibility() {
5905        return mViewFlags & VISIBILITY_MASK;
5906    }
5907
5908    /**
5909     * Set the enabled state of this view.
5910     *
5911     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5912     * @attr ref android.R.styleable#View_visibility
5913     */
5914    @RemotableViewMethod
5915    public void setVisibility(int visibility) {
5916        setFlags(visibility, VISIBILITY_MASK);
5917        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5918    }
5919
5920    /**
5921     * Returns the enabled status for this view. The interpretation of the
5922     * enabled state varies by subclass.
5923     *
5924     * @return True if this view is enabled, false otherwise.
5925     */
5926    @ViewDebug.ExportedProperty
5927    public boolean isEnabled() {
5928        return (mViewFlags & ENABLED_MASK) == ENABLED;
5929    }
5930
5931    /**
5932     * Set the enabled state of this view. The interpretation of the enabled
5933     * state varies by subclass.
5934     *
5935     * @param enabled True if this view is enabled, false otherwise.
5936     */
5937    @RemotableViewMethod
5938    public void setEnabled(boolean enabled) {
5939        if (enabled == isEnabled()) return;
5940
5941        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5942
5943        /*
5944         * The View most likely has to change its appearance, so refresh
5945         * the drawable state.
5946         */
5947        refreshDrawableState();
5948
5949        // Invalidate too, since the default behavior for views is to be
5950        // be drawn at 50% alpha rather than to change the drawable.
5951        invalidate(true);
5952    }
5953
5954    /**
5955     * Set whether this view can receive the focus.
5956     *
5957     * Setting this to false will also ensure that this view is not focusable
5958     * in touch mode.
5959     *
5960     * @param focusable If true, this view can receive the focus.
5961     *
5962     * @see #setFocusableInTouchMode(boolean)
5963     * @attr ref android.R.styleable#View_focusable
5964     */
5965    public void setFocusable(boolean focusable) {
5966        if (!focusable) {
5967            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5968        }
5969        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5970    }
5971
5972    /**
5973     * Set whether this view can receive focus while in touch mode.
5974     *
5975     * Setting this to true will also ensure that this view is focusable.
5976     *
5977     * @param focusableInTouchMode If true, this view can receive the focus while
5978     *   in touch mode.
5979     *
5980     * @see #setFocusable(boolean)
5981     * @attr ref android.R.styleable#View_focusableInTouchMode
5982     */
5983    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5984        // Focusable in touch mode should always be set before the focusable flag
5985        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5986        // which, in touch mode, will not successfully request focus on this view
5987        // because the focusable in touch mode flag is not set
5988        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5989        if (focusableInTouchMode) {
5990            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5991        }
5992    }
5993
5994    /**
5995     * Set whether this view should have sound effects enabled for events such as
5996     * clicking and touching.
5997     *
5998     * <p>You may wish to disable sound effects for a view if you already play sounds,
5999     * for instance, a dial key that plays dtmf tones.
6000     *
6001     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6002     * @see #isSoundEffectsEnabled()
6003     * @see #playSoundEffect(int)
6004     * @attr ref android.R.styleable#View_soundEffectsEnabled
6005     */
6006    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6007        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6008    }
6009
6010    /**
6011     * @return whether this view should have sound effects enabled for events such as
6012     *     clicking and touching.
6013     *
6014     * @see #setSoundEffectsEnabled(boolean)
6015     * @see #playSoundEffect(int)
6016     * @attr ref android.R.styleable#View_soundEffectsEnabled
6017     */
6018    @ViewDebug.ExportedProperty
6019    public boolean isSoundEffectsEnabled() {
6020        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6021    }
6022
6023    /**
6024     * Set whether this view should have haptic feedback for events such as
6025     * long presses.
6026     *
6027     * <p>You may wish to disable haptic feedback if your view already controls
6028     * its own haptic feedback.
6029     *
6030     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6031     * @see #isHapticFeedbackEnabled()
6032     * @see #performHapticFeedback(int)
6033     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6034     */
6035    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6036        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6037    }
6038
6039    /**
6040     * @return whether this view should have haptic feedback enabled for events
6041     * long presses.
6042     *
6043     * @see #setHapticFeedbackEnabled(boolean)
6044     * @see #performHapticFeedback(int)
6045     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6046     */
6047    @ViewDebug.ExportedProperty
6048    public boolean isHapticFeedbackEnabled() {
6049        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6050    }
6051
6052    /**
6053     * Returns the layout direction for this view.
6054     *
6055     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6056     *   {@link #LAYOUT_DIRECTION_RTL},
6057     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6058     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6059     *
6060     * @attr ref android.R.styleable#View_layoutDirection
6061     *
6062     * @hide
6063     */
6064    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6065        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6066        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6067        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6068        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6069    })
6070    public int getRawLayoutDirection() {
6071        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6072    }
6073
6074    /**
6075     * Set the layout direction for this view. This will propagate a reset of layout direction
6076     * resolution to the view's children and resolve layout direction for this view.
6077     *
6078     * @param layoutDirection the layout direction to set. Should be one of:
6079     *
6080     * {@link #LAYOUT_DIRECTION_LTR},
6081     * {@link #LAYOUT_DIRECTION_RTL},
6082     * {@link #LAYOUT_DIRECTION_INHERIT},
6083     * {@link #LAYOUT_DIRECTION_LOCALE}.
6084     *
6085     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6086     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6087     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6088     *
6089     * @attr ref android.R.styleable#View_layoutDirection
6090     */
6091    @RemotableViewMethod
6092    public void setLayoutDirection(int layoutDirection) {
6093        if (getRawLayoutDirection() != layoutDirection) {
6094            // Reset the current layout direction and the resolved one
6095            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6096            resetRtlProperties();
6097            // Set the new layout direction (filtered)
6098            mPrivateFlags2 |=
6099                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6100            // We need to resolve all RTL properties as they all depend on layout direction
6101            resolveRtlPropertiesIfNeeded();
6102            requestLayout();
6103            invalidate(true);
6104        }
6105    }
6106
6107    /**
6108     * Returns the resolved layout direction for this view.
6109     *
6110     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6111     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6112     *
6113     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6114     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6115     *
6116     * @attr ref android.R.styleable#View_layoutDirection
6117     */
6118    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6119        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6120        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6121    })
6122    public int getLayoutDirection() {
6123        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6124        if (targetSdkVersion < JELLY_BEAN_MR1) {
6125            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6126            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6127        }
6128        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6129                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6130    }
6131
6132    /**
6133     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6134     * layout attribute and/or the inherited value from the parent
6135     *
6136     * @return true if the layout is right-to-left.
6137     *
6138     * @hide
6139     */
6140    @ViewDebug.ExportedProperty(category = "layout")
6141    public boolean isLayoutRtl() {
6142        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6143    }
6144
6145    /**
6146     * Indicates whether the view is currently tracking transient state that the
6147     * app should not need to concern itself with saving and restoring, but that
6148     * the framework should take special note to preserve when possible.
6149     *
6150     * <p>A view with transient state cannot be trivially rebound from an external
6151     * data source, such as an adapter binding item views in a list. This may be
6152     * because the view is performing an animation, tracking user selection
6153     * of content, or similar.</p>
6154     *
6155     * @return true if the view has transient state
6156     */
6157    @ViewDebug.ExportedProperty(category = "layout")
6158    public boolean hasTransientState() {
6159        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6160    }
6161
6162    /**
6163     * Set whether this view is currently tracking transient state that the
6164     * framework should attempt to preserve when possible. This flag is reference counted,
6165     * so every call to setHasTransientState(true) should be paired with a later call
6166     * to setHasTransientState(false).
6167     *
6168     * <p>A view with transient state cannot be trivially rebound from an external
6169     * data source, such as an adapter binding item views in a list. This may be
6170     * because the view is performing an animation, tracking user selection
6171     * of content, or similar.</p>
6172     *
6173     * @param hasTransientState true if this view has transient state
6174     */
6175    public void setHasTransientState(boolean hasTransientState) {
6176        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6177                mTransientStateCount - 1;
6178        if (mTransientStateCount < 0) {
6179            mTransientStateCount = 0;
6180            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6181                    "unmatched pair of setHasTransientState calls");
6182        } else if ((hasTransientState && mTransientStateCount == 1) ||
6183                (!hasTransientState && mTransientStateCount == 0)) {
6184            // update flag if we've just incremented up from 0 or decremented down to 0
6185            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6186                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6187            if (mParent != null) {
6188                try {
6189                    mParent.childHasTransientStateChanged(this, hasTransientState);
6190                } catch (AbstractMethodError e) {
6191                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6192                            " does not fully implement ViewParent", e);
6193                }
6194            }
6195        }
6196    }
6197
6198    /**
6199     * Returns true if this view is currently attached to a window.
6200     */
6201    public boolean isAttachedToWindow() {
6202        return mAttachInfo != null;
6203    }
6204
6205    /**
6206     * Returns true if this view has been through at least one layout since it
6207     * was last attached to or detached from a window.
6208     */
6209    public boolean isLaidOut() {
6210        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6211    }
6212
6213    /**
6214     * If this view doesn't do any drawing on its own, set this flag to
6215     * allow further optimizations. By default, this flag is not set on
6216     * View, but could be set on some View subclasses such as ViewGroup.
6217     *
6218     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6219     * you should clear this flag.
6220     *
6221     * @param willNotDraw whether or not this View draw on its own
6222     */
6223    public void setWillNotDraw(boolean willNotDraw) {
6224        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6225    }
6226
6227    /**
6228     * Returns whether or not this View draws on its own.
6229     *
6230     * @return true if this view has nothing to draw, false otherwise
6231     */
6232    @ViewDebug.ExportedProperty(category = "drawing")
6233    public boolean willNotDraw() {
6234        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6235    }
6236
6237    /**
6238     * When a View's drawing cache is enabled, drawing is redirected to an
6239     * offscreen bitmap. Some views, like an ImageView, must be able to
6240     * bypass this mechanism if they already draw a single bitmap, to avoid
6241     * unnecessary usage of the memory.
6242     *
6243     * @param willNotCacheDrawing true if this view does not cache its
6244     *        drawing, false otherwise
6245     */
6246    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6247        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6248    }
6249
6250    /**
6251     * Returns whether or not this View can cache its drawing or not.
6252     *
6253     * @return true if this view does not cache its drawing, false otherwise
6254     */
6255    @ViewDebug.ExportedProperty(category = "drawing")
6256    public boolean willNotCacheDrawing() {
6257        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6258    }
6259
6260    /**
6261     * Indicates whether this view reacts to click events or not.
6262     *
6263     * @return true if the view is clickable, false otherwise
6264     *
6265     * @see #setClickable(boolean)
6266     * @attr ref android.R.styleable#View_clickable
6267     */
6268    @ViewDebug.ExportedProperty
6269    public boolean isClickable() {
6270        return (mViewFlags & CLICKABLE) == CLICKABLE;
6271    }
6272
6273    /**
6274     * Enables or disables click events for this view. When a view
6275     * is clickable it will change its state to "pressed" on every click.
6276     * Subclasses should set the view clickable to visually react to
6277     * user's clicks.
6278     *
6279     * @param clickable true to make the view clickable, false otherwise
6280     *
6281     * @see #isClickable()
6282     * @attr ref android.R.styleable#View_clickable
6283     */
6284    public void setClickable(boolean clickable) {
6285        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6286    }
6287
6288    /**
6289     * Indicates whether this view reacts to long click events or not.
6290     *
6291     * @return true if the view is long clickable, false otherwise
6292     *
6293     * @see #setLongClickable(boolean)
6294     * @attr ref android.R.styleable#View_longClickable
6295     */
6296    public boolean isLongClickable() {
6297        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6298    }
6299
6300    /**
6301     * Enables or disables long click events for this view. When a view is long
6302     * clickable it reacts to the user holding down the button for a longer
6303     * duration than a tap. This event can either launch the listener or a
6304     * context menu.
6305     *
6306     * @param longClickable true to make the view long clickable, false otherwise
6307     * @see #isLongClickable()
6308     * @attr ref android.R.styleable#View_longClickable
6309     */
6310    public void setLongClickable(boolean longClickable) {
6311        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6312    }
6313
6314    /**
6315     * Sets the pressed state for this view.
6316     *
6317     * @see #isClickable()
6318     * @see #setClickable(boolean)
6319     *
6320     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6321     *        the View's internal state from a previously set "pressed" state.
6322     */
6323    public void setPressed(boolean pressed) {
6324        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6325
6326        if (pressed) {
6327            mPrivateFlags |= PFLAG_PRESSED;
6328        } else {
6329            mPrivateFlags &= ~PFLAG_PRESSED;
6330        }
6331
6332        if (needsRefresh) {
6333            refreshDrawableState();
6334        }
6335        dispatchSetPressed(pressed);
6336    }
6337
6338    /**
6339     * Dispatch setPressed to all of this View's children.
6340     *
6341     * @see #setPressed(boolean)
6342     *
6343     * @param pressed The new pressed state
6344     */
6345    protected void dispatchSetPressed(boolean pressed) {
6346    }
6347
6348    /**
6349     * Indicates whether the view is currently in pressed state. Unless
6350     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6351     * the pressed state.
6352     *
6353     * @see #setPressed(boolean)
6354     * @see #isClickable()
6355     * @see #setClickable(boolean)
6356     *
6357     * @return true if the view is currently pressed, false otherwise
6358     */
6359    public boolean isPressed() {
6360        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6361    }
6362
6363    /**
6364     * Indicates whether this view will save its state (that is,
6365     * whether its {@link #onSaveInstanceState} method will be called).
6366     *
6367     * @return Returns true if the view state saving is enabled, else false.
6368     *
6369     * @see #setSaveEnabled(boolean)
6370     * @attr ref android.R.styleable#View_saveEnabled
6371     */
6372    public boolean isSaveEnabled() {
6373        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6374    }
6375
6376    /**
6377     * Controls whether the saving of this view's state is
6378     * enabled (that is, whether its {@link #onSaveInstanceState} method
6379     * will be called).  Note that even if freezing is enabled, the
6380     * view still must have an id assigned to it (via {@link #setId(int)})
6381     * for its state to be saved.  This flag can only disable the
6382     * saving of this view; any child views may still have their state saved.
6383     *
6384     * @param enabled Set to false to <em>disable</em> state saving, or true
6385     * (the default) to allow it.
6386     *
6387     * @see #isSaveEnabled()
6388     * @see #setId(int)
6389     * @see #onSaveInstanceState()
6390     * @attr ref android.R.styleable#View_saveEnabled
6391     */
6392    public void setSaveEnabled(boolean enabled) {
6393        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6394    }
6395
6396    /**
6397     * Gets whether the framework should discard touches when the view's
6398     * window is obscured by another visible window.
6399     * Refer to the {@link View} security documentation for more details.
6400     *
6401     * @return True if touch filtering is enabled.
6402     *
6403     * @see #setFilterTouchesWhenObscured(boolean)
6404     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6405     */
6406    @ViewDebug.ExportedProperty
6407    public boolean getFilterTouchesWhenObscured() {
6408        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6409    }
6410
6411    /**
6412     * Sets whether the framework should discard touches when the view's
6413     * window is obscured by another visible window.
6414     * Refer to the {@link View} security documentation for more details.
6415     *
6416     * @param enabled True if touch filtering should be enabled.
6417     *
6418     * @see #getFilterTouchesWhenObscured
6419     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6420     */
6421    public void setFilterTouchesWhenObscured(boolean enabled) {
6422        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6423                FILTER_TOUCHES_WHEN_OBSCURED);
6424    }
6425
6426    /**
6427     * Indicates whether the entire hierarchy under this view will save its
6428     * state when a state saving traversal occurs from its parent.  The default
6429     * is true; if false, these views will not be saved unless
6430     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6431     *
6432     * @return Returns true if the view state saving from parent is enabled, else false.
6433     *
6434     * @see #setSaveFromParentEnabled(boolean)
6435     */
6436    public boolean isSaveFromParentEnabled() {
6437        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6438    }
6439
6440    /**
6441     * Controls whether the entire hierarchy under this view will save its
6442     * state when a state saving traversal occurs from its parent.  The default
6443     * is true; if false, these views will not be saved unless
6444     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6445     *
6446     * @param enabled Set to false to <em>disable</em> state saving, or true
6447     * (the default) to allow it.
6448     *
6449     * @see #isSaveFromParentEnabled()
6450     * @see #setId(int)
6451     * @see #onSaveInstanceState()
6452     */
6453    public void setSaveFromParentEnabled(boolean enabled) {
6454        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6455    }
6456
6457
6458    /**
6459     * Returns whether this View is able to take focus.
6460     *
6461     * @return True if this view can take focus, or false otherwise.
6462     * @attr ref android.R.styleable#View_focusable
6463     */
6464    @ViewDebug.ExportedProperty(category = "focus")
6465    public final boolean isFocusable() {
6466        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6467    }
6468
6469    /**
6470     * When a view is focusable, it may not want to take focus when in touch mode.
6471     * For example, a button would like focus when the user is navigating via a D-pad
6472     * so that the user can click on it, but once the user starts touching the screen,
6473     * the button shouldn't take focus
6474     * @return Whether the view is focusable in touch mode.
6475     * @attr ref android.R.styleable#View_focusableInTouchMode
6476     */
6477    @ViewDebug.ExportedProperty
6478    public final boolean isFocusableInTouchMode() {
6479        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6480    }
6481
6482    /**
6483     * Find the nearest view in the specified direction that can take focus.
6484     * This does not actually give focus to that view.
6485     *
6486     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6487     *
6488     * @return The nearest focusable in the specified direction, or null if none
6489     *         can be found.
6490     */
6491    public View focusSearch(int direction) {
6492        if (mParent != null) {
6493            return mParent.focusSearch(this, direction);
6494        } else {
6495            return null;
6496        }
6497    }
6498
6499    /**
6500     * This method is the last chance for the focused view and its ancestors to
6501     * respond to an arrow key. This is called when the focused view did not
6502     * consume the key internally, nor could the view system find a new view in
6503     * the requested direction to give focus to.
6504     *
6505     * @param focused The currently focused view.
6506     * @param direction The direction focus wants to move. One of FOCUS_UP,
6507     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6508     * @return True if the this view consumed this unhandled move.
6509     */
6510    public boolean dispatchUnhandledMove(View focused, int direction) {
6511        return false;
6512    }
6513
6514    /**
6515     * If a user manually specified the next view id for a particular direction,
6516     * use the root to look up the view.
6517     * @param root The root view of the hierarchy containing this view.
6518     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6519     * or FOCUS_BACKWARD.
6520     * @return The user specified next view, or null if there is none.
6521     */
6522    View findUserSetNextFocus(View root, int direction) {
6523        switch (direction) {
6524            case FOCUS_LEFT:
6525                if (mNextFocusLeftId == View.NO_ID) return null;
6526                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6527            case FOCUS_RIGHT:
6528                if (mNextFocusRightId == View.NO_ID) return null;
6529                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6530            case FOCUS_UP:
6531                if (mNextFocusUpId == View.NO_ID) return null;
6532                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6533            case FOCUS_DOWN:
6534                if (mNextFocusDownId == View.NO_ID) return null;
6535                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6536            case FOCUS_FORWARD:
6537                if (mNextFocusForwardId == View.NO_ID) return null;
6538                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6539            case FOCUS_BACKWARD: {
6540                if (mID == View.NO_ID) return null;
6541                final int id = mID;
6542                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6543                    @Override
6544                    public boolean apply(View t) {
6545                        return t.mNextFocusForwardId == id;
6546                    }
6547                });
6548            }
6549        }
6550        return null;
6551    }
6552
6553    private View findViewInsideOutShouldExist(View root, int id) {
6554        if (mMatchIdPredicate == null) {
6555            mMatchIdPredicate = new MatchIdPredicate();
6556        }
6557        mMatchIdPredicate.mId = id;
6558        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6559        if (result == null) {
6560            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6561        }
6562        return result;
6563    }
6564
6565    /**
6566     * Find and return all focusable views that are descendants of this view,
6567     * possibly including this view if it is focusable itself.
6568     *
6569     * @param direction The direction of the focus
6570     * @return A list of focusable views
6571     */
6572    public ArrayList<View> getFocusables(int direction) {
6573        ArrayList<View> result = new ArrayList<View>(24);
6574        addFocusables(result, direction);
6575        return result;
6576    }
6577
6578    /**
6579     * Add any focusable views that are descendants of this view (possibly
6580     * including this view if it is focusable itself) to views.  If we are in touch mode,
6581     * only add views that are also focusable in touch mode.
6582     *
6583     * @param views Focusable views found so far
6584     * @param direction The direction of the focus
6585     */
6586    public void addFocusables(ArrayList<View> views, int direction) {
6587        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6588    }
6589
6590    /**
6591     * Adds any focusable views that are descendants of this view (possibly
6592     * including this view if it is focusable itself) to views. This method
6593     * adds all focusable views regardless if we are in touch mode or
6594     * only views focusable in touch mode if we are in touch mode or
6595     * only views that can take accessibility focus if accessibility is enabeld
6596     * depending on the focusable mode paramater.
6597     *
6598     * @param views Focusable views found so far or null if all we are interested is
6599     *        the number of focusables.
6600     * @param direction The direction of the focus.
6601     * @param focusableMode The type of focusables to be added.
6602     *
6603     * @see #FOCUSABLES_ALL
6604     * @see #FOCUSABLES_TOUCH_MODE
6605     */
6606    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6607        if (views == null) {
6608            return;
6609        }
6610        if (!isFocusable()) {
6611            return;
6612        }
6613        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6614                && isInTouchMode() && !isFocusableInTouchMode()) {
6615            return;
6616        }
6617        views.add(this);
6618    }
6619
6620    /**
6621     * Finds the Views that contain given text. The containment is case insensitive.
6622     * The search is performed by either the text that the View renders or the content
6623     * description that describes the view for accessibility purposes and the view does
6624     * not render or both. Clients can specify how the search is to be performed via
6625     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6626     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6627     *
6628     * @param outViews The output list of matching Views.
6629     * @param searched The text to match against.
6630     *
6631     * @see #FIND_VIEWS_WITH_TEXT
6632     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6633     * @see #setContentDescription(CharSequence)
6634     */
6635    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6636        if (getAccessibilityNodeProvider() != null) {
6637            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6638                outViews.add(this);
6639            }
6640        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6641                && (searched != null && searched.length() > 0)
6642                && (mContentDescription != null && mContentDescription.length() > 0)) {
6643            String searchedLowerCase = searched.toString().toLowerCase();
6644            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6645            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6646                outViews.add(this);
6647            }
6648        }
6649    }
6650
6651    /**
6652     * Find and return all touchable views that are descendants of this view,
6653     * possibly including this view if it is touchable itself.
6654     *
6655     * @return A list of touchable views
6656     */
6657    public ArrayList<View> getTouchables() {
6658        ArrayList<View> result = new ArrayList<View>();
6659        addTouchables(result);
6660        return result;
6661    }
6662
6663    /**
6664     * Add any touchable views that are descendants of this view (possibly
6665     * including this view if it is touchable itself) to views.
6666     *
6667     * @param views Touchable views found so far
6668     */
6669    public void addTouchables(ArrayList<View> views) {
6670        final int viewFlags = mViewFlags;
6671
6672        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6673                && (viewFlags & ENABLED_MASK) == ENABLED) {
6674            views.add(this);
6675        }
6676    }
6677
6678    /**
6679     * Returns whether this View is accessibility focused.
6680     *
6681     * @return True if this View is accessibility focused.
6682     */
6683    boolean isAccessibilityFocused() {
6684        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6685    }
6686
6687    /**
6688     * Call this to try to give accessibility focus to this view.
6689     *
6690     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6691     * returns false or the view is no visible or the view already has accessibility
6692     * focus.
6693     *
6694     * See also {@link #focusSearch(int)}, which is what you call to say that you
6695     * have focus, and you want your parent to look for the next one.
6696     *
6697     * @return Whether this view actually took accessibility focus.
6698     *
6699     * @hide
6700     */
6701    public boolean requestAccessibilityFocus() {
6702        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6703        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6704            return false;
6705        }
6706        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6707            return false;
6708        }
6709        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6710            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6711            ViewRootImpl viewRootImpl = getViewRootImpl();
6712            if (viewRootImpl != null) {
6713                viewRootImpl.setAccessibilityFocus(this, null);
6714            }
6715            invalidate();
6716            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6717            return true;
6718        }
6719        return false;
6720    }
6721
6722    /**
6723     * Call this to try to clear accessibility focus of this view.
6724     *
6725     * See also {@link #focusSearch(int)}, which is what you call to say that you
6726     * have focus, and you want your parent to look for the next one.
6727     *
6728     * @hide
6729     */
6730    public void clearAccessibilityFocus() {
6731        clearAccessibilityFocusNoCallbacks();
6732        // Clear the global reference of accessibility focus if this
6733        // view or any of its descendants had accessibility focus.
6734        ViewRootImpl viewRootImpl = getViewRootImpl();
6735        if (viewRootImpl != null) {
6736            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6737            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6738                viewRootImpl.setAccessibilityFocus(null, null);
6739            }
6740        }
6741    }
6742
6743    private void sendAccessibilityHoverEvent(int eventType) {
6744        // Since we are not delivering to a client accessibility events from not
6745        // important views (unless the clinet request that) we need to fire the
6746        // event from the deepest view exposed to the client. As a consequence if
6747        // the user crosses a not exposed view the client will see enter and exit
6748        // of the exposed predecessor followed by and enter and exit of that same
6749        // predecessor when entering and exiting the not exposed descendant. This
6750        // is fine since the client has a clear idea which view is hovered at the
6751        // price of a couple more events being sent. This is a simple and
6752        // working solution.
6753        View source = this;
6754        while (true) {
6755            if (source.includeForAccessibility()) {
6756                source.sendAccessibilityEvent(eventType);
6757                return;
6758            }
6759            ViewParent parent = source.getParent();
6760            if (parent instanceof View) {
6761                source = (View) parent;
6762            } else {
6763                return;
6764            }
6765        }
6766    }
6767
6768    /**
6769     * Clears accessibility focus without calling any callback methods
6770     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6771     * is used for clearing accessibility focus when giving this focus to
6772     * another view.
6773     */
6774    void clearAccessibilityFocusNoCallbacks() {
6775        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6776            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6777            invalidate();
6778            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6779        }
6780    }
6781
6782    /**
6783     * Call this to try to give focus to a specific view or to one of its
6784     * descendants.
6785     *
6786     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6787     * false), or if it is focusable and it is not focusable in touch mode
6788     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6789     *
6790     * See also {@link #focusSearch(int)}, which is what you call to say that you
6791     * have focus, and you want your parent to look for the next one.
6792     *
6793     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6794     * {@link #FOCUS_DOWN} and <code>null</code>.
6795     *
6796     * @return Whether this view or one of its descendants actually took focus.
6797     */
6798    public final boolean requestFocus() {
6799        return requestFocus(View.FOCUS_DOWN);
6800    }
6801
6802    /**
6803     * Call this to try to give focus to a specific view or to one of its
6804     * descendants and give it a hint about what direction focus is heading.
6805     *
6806     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6807     * false), or if it is focusable and it is not focusable in touch mode
6808     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6809     *
6810     * See also {@link #focusSearch(int)}, which is what you call to say that you
6811     * have focus, and you want your parent to look for the next one.
6812     *
6813     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6814     * <code>null</code> set for the previously focused rectangle.
6815     *
6816     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6817     * @return Whether this view or one of its descendants actually took focus.
6818     */
6819    public final boolean requestFocus(int direction) {
6820        return requestFocus(direction, null);
6821    }
6822
6823    /**
6824     * Call this to try to give focus to a specific view or to one of its descendants
6825     * and give it hints about the direction and a specific rectangle that the focus
6826     * is coming from.  The rectangle can help give larger views a finer grained hint
6827     * about where focus is coming from, and therefore, where to show selection, or
6828     * forward focus change internally.
6829     *
6830     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6831     * false), or if it is focusable and it is not focusable in touch mode
6832     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6833     *
6834     * A View will not take focus if it is not visible.
6835     *
6836     * A View will not take focus if one of its parents has
6837     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6838     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6839     *
6840     * See also {@link #focusSearch(int)}, which is what you call to say that you
6841     * have focus, and you want your parent to look for the next one.
6842     *
6843     * You may wish to override this method if your custom {@link View} has an internal
6844     * {@link View} that it wishes to forward the request to.
6845     *
6846     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6847     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6848     *        to give a finer grained hint about where focus is coming from.  May be null
6849     *        if there is no hint.
6850     * @return Whether this view or one of its descendants actually took focus.
6851     */
6852    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6853        return requestFocusNoSearch(direction, previouslyFocusedRect);
6854    }
6855
6856    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6857        // need to be focusable
6858        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6859                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6860            return false;
6861        }
6862
6863        // need to be focusable in touch mode if in touch mode
6864        if (isInTouchMode() &&
6865            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6866               return false;
6867        }
6868
6869        // need to not have any parents blocking us
6870        if (hasAncestorThatBlocksDescendantFocus()) {
6871            return false;
6872        }
6873
6874        handleFocusGainInternal(direction, previouslyFocusedRect);
6875        return true;
6876    }
6877
6878    /**
6879     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6880     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6881     * touch mode to request focus when they are touched.
6882     *
6883     * @return Whether this view or one of its descendants actually took focus.
6884     *
6885     * @see #isInTouchMode()
6886     *
6887     */
6888    public final boolean requestFocusFromTouch() {
6889        // Leave touch mode if we need to
6890        if (isInTouchMode()) {
6891            ViewRootImpl viewRoot = getViewRootImpl();
6892            if (viewRoot != null) {
6893                viewRoot.ensureTouchMode(false);
6894            }
6895        }
6896        return requestFocus(View.FOCUS_DOWN);
6897    }
6898
6899    /**
6900     * @return Whether any ancestor of this view blocks descendant focus.
6901     */
6902    private boolean hasAncestorThatBlocksDescendantFocus() {
6903        ViewParent ancestor = mParent;
6904        while (ancestor instanceof ViewGroup) {
6905            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6906            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6907                return true;
6908            } else {
6909                ancestor = vgAncestor.getParent();
6910            }
6911        }
6912        return false;
6913    }
6914
6915    /**
6916     * Gets the mode for determining whether this View is important for accessibility
6917     * which is if it fires accessibility events and if it is reported to
6918     * accessibility services that query the screen.
6919     *
6920     * @return The mode for determining whether a View is important for accessibility.
6921     *
6922     * @attr ref android.R.styleable#View_importantForAccessibility
6923     *
6924     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6925     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6926     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6927     */
6928    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6929            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6930            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6931            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6932        })
6933    public int getImportantForAccessibility() {
6934        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6935                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6936    }
6937
6938    /**
6939     * Sets how to determine whether this view is important for accessibility
6940     * which is if it fires accessibility events and if it is reported to
6941     * accessibility services that query the screen.
6942     *
6943     * @param mode How to determine whether this view is important for accessibility.
6944     *
6945     * @attr ref android.R.styleable#View_importantForAccessibility
6946     *
6947     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6948     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6949     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6950     */
6951    public void setImportantForAccessibility(int mode) {
6952        final boolean oldIncludeForAccessibility = includeForAccessibility();
6953        if (mode != getImportantForAccessibility()) {
6954            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6955            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6956                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6957            if (oldIncludeForAccessibility != includeForAccessibility()) {
6958                notifySubtreeAccessibilityStateChangedIfNeeded();
6959            } else {
6960                notifyViewAccessibilityStateChangedIfNeeded();
6961            }
6962        }
6963    }
6964
6965    /**
6966     * Gets whether this view should be exposed for accessibility.
6967     *
6968     * @return Whether the view is exposed for accessibility.
6969     *
6970     * @hide
6971     */
6972    public boolean isImportantForAccessibility() {
6973        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6974                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6975        switch (mode) {
6976            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6977                return true;
6978            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6979                return false;
6980            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6981                return isActionableForAccessibility() || hasListenersForAccessibility()
6982                        || getAccessibilityNodeProvider() != null;
6983            default:
6984                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6985                        + mode);
6986        }
6987    }
6988
6989    /**
6990     * Gets the parent for accessibility purposes. Note that the parent for
6991     * accessibility is not necessary the immediate parent. It is the first
6992     * predecessor that is important for accessibility.
6993     *
6994     * @return The parent for accessibility purposes.
6995     */
6996    public ViewParent getParentForAccessibility() {
6997        if (mParent instanceof View) {
6998            View parentView = (View) mParent;
6999            if (parentView.includeForAccessibility()) {
7000                return mParent;
7001            } else {
7002                return mParent.getParentForAccessibility();
7003            }
7004        }
7005        return null;
7006    }
7007
7008    /**
7009     * Adds the children of a given View for accessibility. Since some Views are
7010     * not important for accessibility the children for accessibility are not
7011     * necessarily direct children of the view, rather they are the first level of
7012     * descendants important for accessibility.
7013     *
7014     * @param children The list of children for accessibility.
7015     */
7016    public void addChildrenForAccessibility(ArrayList<View> children) {
7017        if (includeForAccessibility()) {
7018            children.add(this);
7019        }
7020    }
7021
7022    /**
7023     * Whether to regard this view for accessibility. A view is regarded for
7024     * accessibility if it is important for accessibility or the querying
7025     * accessibility service has explicitly requested that view not
7026     * important for accessibility are regarded.
7027     *
7028     * @return Whether to regard the view for accessibility.
7029     *
7030     * @hide
7031     */
7032    public boolean includeForAccessibility() {
7033        //noinspection SimplifiableIfStatement
7034        if (mAttachInfo != null) {
7035            return (mAttachInfo.mAccessibilityFetchFlags
7036                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7037                    || isImportantForAccessibility();
7038        }
7039        return false;
7040    }
7041
7042    /**
7043     * Returns whether the View is considered actionable from
7044     * accessibility perspective. Such view are important for
7045     * accessibility.
7046     *
7047     * @return True if the view is actionable for accessibility.
7048     *
7049     * @hide
7050     */
7051    public boolean isActionableForAccessibility() {
7052        return (isClickable() || isLongClickable() || isFocusable());
7053    }
7054
7055    /**
7056     * Returns whether the View has registered callbacks wich makes it
7057     * important for accessibility.
7058     *
7059     * @return True if the view is actionable for accessibility.
7060     */
7061    private boolean hasListenersForAccessibility() {
7062        ListenerInfo info = getListenerInfo();
7063        return mTouchDelegate != null || info.mOnKeyListener != null
7064                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7065                || info.mOnHoverListener != null || info.mOnDragListener != null;
7066    }
7067
7068    /**
7069     * Notifies that the accessibility state of this view changed. The change
7070     * is local to this view and does not represent structural changes such
7071     * as children and parent. For example, the view became focusable. The
7072     * notification is at at most once every
7073     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7074     * to avoid unnecessary load to the system. Also once a view has a pending
7075     * notifucation this method is a NOP until the notification has been sent.
7076     *
7077     * @hide
7078     */
7079    public void notifyViewAccessibilityStateChangedIfNeeded() {
7080        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7081            return;
7082        }
7083        if (mSendViewStateChangedAccessibilityEvent == null) {
7084            mSendViewStateChangedAccessibilityEvent =
7085                    new SendViewStateChangedAccessibilityEvent();
7086        }
7087        mSendViewStateChangedAccessibilityEvent.runOrPost();
7088    }
7089
7090    /**
7091     * Notifies that the accessibility state of this view changed. The change
7092     * is *not* local to this view and does represent structural changes such
7093     * as children and parent. For example, the view size changed. The
7094     * notification is at at most once every
7095     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7096     * to avoid unnecessary load to the system. Also once a view has a pending
7097     * notifucation this method is a NOP until the notification has been sent.
7098     *
7099     * @hide
7100     */
7101    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7102        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7103            return;
7104        }
7105        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7106            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7107            if (mParent != null) {
7108                try {
7109                    mParent.childAccessibilityStateChanged(this);
7110                } catch (AbstractMethodError e) {
7111                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7112                            " does not fully implement ViewParent", e);
7113                }
7114            }
7115        }
7116    }
7117
7118    /**
7119     * Reset the flag indicating the accessibility state of the subtree rooted
7120     * at this view changed.
7121     */
7122    void resetSubtreeAccessibilityStateChanged() {
7123        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7124    }
7125
7126    /**
7127     * Performs the specified accessibility action on the view. For
7128     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7129     * <p>
7130     * If an {@link AccessibilityDelegate} has been specified via calling
7131     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7132     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7133     * is responsible for handling this call.
7134     * </p>
7135     *
7136     * @param action The action to perform.
7137     * @param arguments Optional action arguments.
7138     * @return Whether the action was performed.
7139     */
7140    public boolean performAccessibilityAction(int action, Bundle arguments) {
7141      if (mAccessibilityDelegate != null) {
7142          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7143      } else {
7144          return performAccessibilityActionInternal(action, arguments);
7145      }
7146    }
7147
7148   /**
7149    * @see #performAccessibilityAction(int, Bundle)
7150    *
7151    * Note: Called from the default {@link AccessibilityDelegate}.
7152    */
7153    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7154        switch (action) {
7155            case AccessibilityNodeInfo.ACTION_CLICK: {
7156                if (isClickable()) {
7157                    performClick();
7158                    return true;
7159                }
7160            } break;
7161            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7162                if (isLongClickable()) {
7163                    performLongClick();
7164                    return true;
7165                }
7166            } break;
7167            case AccessibilityNodeInfo.ACTION_FOCUS: {
7168                if (!hasFocus()) {
7169                    // Get out of touch mode since accessibility
7170                    // wants to move focus around.
7171                    getViewRootImpl().ensureTouchMode(false);
7172                    return requestFocus();
7173                }
7174            } break;
7175            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7176                if (hasFocus()) {
7177                    clearFocus();
7178                    return !isFocused();
7179                }
7180            } break;
7181            case AccessibilityNodeInfo.ACTION_SELECT: {
7182                if (!isSelected()) {
7183                    setSelected(true);
7184                    return isSelected();
7185                }
7186            } break;
7187            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7188                if (isSelected()) {
7189                    setSelected(false);
7190                    return !isSelected();
7191                }
7192            } break;
7193            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7194                if (!isAccessibilityFocused()) {
7195                    return requestAccessibilityFocus();
7196                }
7197            } break;
7198            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7199                if (isAccessibilityFocused()) {
7200                    clearAccessibilityFocus();
7201                    return true;
7202                }
7203            } break;
7204            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7205                if (arguments != null) {
7206                    final int granularity = arguments.getInt(
7207                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7208                    final boolean extendSelection = arguments.getBoolean(
7209                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7210                    return traverseAtGranularity(granularity, true, extendSelection);
7211                }
7212            } break;
7213            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7214                if (arguments != null) {
7215                    final int granularity = arguments.getInt(
7216                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7217                    final boolean extendSelection = arguments.getBoolean(
7218                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7219                    return traverseAtGranularity(granularity, false, extendSelection);
7220                }
7221            } break;
7222            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7223                CharSequence text = getIterableTextForAccessibility();
7224                if (text == null) {
7225                    return false;
7226                }
7227                final int start = (arguments != null) ? arguments.getInt(
7228                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7229                final int end = (arguments != null) ? arguments.getInt(
7230                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7231                // Only cursor position can be specified (selection length == 0)
7232                if ((getAccessibilitySelectionStart() != start
7233                        || getAccessibilitySelectionEnd() != end)
7234                        && (start == end)) {
7235                    setAccessibilitySelection(start, end);
7236                    notifyViewAccessibilityStateChangedIfNeeded();
7237                    return true;
7238                }
7239            } break;
7240        }
7241        return false;
7242    }
7243
7244    private boolean traverseAtGranularity(int granularity, boolean forward,
7245            boolean extendSelection) {
7246        CharSequence text = getIterableTextForAccessibility();
7247        if (text == null || text.length() == 0) {
7248            return false;
7249        }
7250        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7251        if (iterator == null) {
7252            return false;
7253        }
7254        int current = getAccessibilitySelectionEnd();
7255        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7256            current = forward ? 0 : text.length();
7257        }
7258        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7259        if (range == null) {
7260            return false;
7261        }
7262        final int segmentStart = range[0];
7263        final int segmentEnd = range[1];
7264        int selectionStart;
7265        int selectionEnd;
7266        if (extendSelection && isAccessibilitySelectionExtendable()) {
7267            selectionStart = getAccessibilitySelectionStart();
7268            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7269                selectionStart = forward ? segmentStart : segmentEnd;
7270            }
7271            selectionEnd = forward ? segmentEnd : segmentStart;
7272        } else {
7273            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7274        }
7275        setAccessibilitySelection(selectionStart, selectionEnd);
7276        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7277                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7278        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7279        return true;
7280    }
7281
7282    /**
7283     * Gets the text reported for accessibility purposes.
7284     *
7285     * @return The accessibility text.
7286     *
7287     * @hide
7288     */
7289    public CharSequence getIterableTextForAccessibility() {
7290        return getContentDescription();
7291    }
7292
7293    /**
7294     * Gets whether accessibility selection can be extended.
7295     *
7296     * @return If selection is extensible.
7297     *
7298     * @hide
7299     */
7300    public boolean isAccessibilitySelectionExtendable() {
7301        return false;
7302    }
7303
7304    /**
7305     * @hide
7306     */
7307    public int getAccessibilitySelectionStart() {
7308        return mAccessibilityCursorPosition;
7309    }
7310
7311    /**
7312     * @hide
7313     */
7314    public int getAccessibilitySelectionEnd() {
7315        return getAccessibilitySelectionStart();
7316    }
7317
7318    /**
7319     * @hide
7320     */
7321    public void setAccessibilitySelection(int start, int end) {
7322        if (start ==  end && end == mAccessibilityCursorPosition) {
7323            return;
7324        }
7325        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7326            mAccessibilityCursorPosition = start;
7327        } else {
7328            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7329        }
7330        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7331    }
7332
7333    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7334            int fromIndex, int toIndex) {
7335        if (mParent == null) {
7336            return;
7337        }
7338        AccessibilityEvent event = AccessibilityEvent.obtain(
7339                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7340        onInitializeAccessibilityEvent(event);
7341        onPopulateAccessibilityEvent(event);
7342        event.setFromIndex(fromIndex);
7343        event.setToIndex(toIndex);
7344        event.setAction(action);
7345        event.setMovementGranularity(granularity);
7346        mParent.requestSendAccessibilityEvent(this, event);
7347    }
7348
7349    /**
7350     * @hide
7351     */
7352    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7353        switch (granularity) {
7354            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7355                CharSequence text = getIterableTextForAccessibility();
7356                if (text != null && text.length() > 0) {
7357                    CharacterTextSegmentIterator iterator =
7358                        CharacterTextSegmentIterator.getInstance(
7359                                mContext.getResources().getConfiguration().locale);
7360                    iterator.initialize(text.toString());
7361                    return iterator;
7362                }
7363            } break;
7364            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7365                CharSequence text = getIterableTextForAccessibility();
7366                if (text != null && text.length() > 0) {
7367                    WordTextSegmentIterator iterator =
7368                        WordTextSegmentIterator.getInstance(
7369                                mContext.getResources().getConfiguration().locale);
7370                    iterator.initialize(text.toString());
7371                    return iterator;
7372                }
7373            } break;
7374            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7375                CharSequence text = getIterableTextForAccessibility();
7376                if (text != null && text.length() > 0) {
7377                    ParagraphTextSegmentIterator iterator =
7378                        ParagraphTextSegmentIterator.getInstance();
7379                    iterator.initialize(text.toString());
7380                    return iterator;
7381                }
7382            } break;
7383        }
7384        return null;
7385    }
7386
7387    /**
7388     * @hide
7389     */
7390    public void dispatchStartTemporaryDetach() {
7391        clearAccessibilityFocus();
7392        clearDisplayList();
7393
7394        onStartTemporaryDetach();
7395    }
7396
7397    /**
7398     * This is called when a container is going to temporarily detach a child, with
7399     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7400     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7401     * {@link #onDetachedFromWindow()} when the container is done.
7402     */
7403    public void onStartTemporaryDetach() {
7404        removeUnsetPressCallback();
7405        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7406    }
7407
7408    /**
7409     * @hide
7410     */
7411    public void dispatchFinishTemporaryDetach() {
7412        onFinishTemporaryDetach();
7413    }
7414
7415    /**
7416     * Called after {@link #onStartTemporaryDetach} when the container is done
7417     * changing the view.
7418     */
7419    public void onFinishTemporaryDetach() {
7420    }
7421
7422    /**
7423     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7424     * for this view's window.  Returns null if the view is not currently attached
7425     * to the window.  Normally you will not need to use this directly, but
7426     * just use the standard high-level event callbacks like
7427     * {@link #onKeyDown(int, KeyEvent)}.
7428     */
7429    public KeyEvent.DispatcherState getKeyDispatcherState() {
7430        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7431    }
7432
7433    /**
7434     * Dispatch a key event before it is processed by any input method
7435     * associated with the view hierarchy.  This can be used to intercept
7436     * key events in special situations before the IME consumes them; a
7437     * typical example would be handling the BACK key to update the application's
7438     * UI instead of allowing the IME to see it and close itself.
7439     *
7440     * @param event The key event to be dispatched.
7441     * @return True if the event was handled, false otherwise.
7442     */
7443    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7444        return onKeyPreIme(event.getKeyCode(), event);
7445    }
7446
7447    /**
7448     * Dispatch a key event to the next view on the focus path. This path runs
7449     * from the top of the view tree down to the currently focused view. If this
7450     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7451     * the next node down the focus path. This method also fires any key
7452     * listeners.
7453     *
7454     * @param event The key event to be dispatched.
7455     * @return True if the event was handled, false otherwise.
7456     */
7457    public boolean dispatchKeyEvent(KeyEvent event) {
7458        if (mInputEventConsistencyVerifier != null) {
7459            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7460        }
7461
7462        // Give any attached key listener a first crack at the event.
7463        //noinspection SimplifiableIfStatement
7464        ListenerInfo li = mListenerInfo;
7465        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7466                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7467            return true;
7468        }
7469
7470        if (event.dispatch(this, mAttachInfo != null
7471                ? mAttachInfo.mKeyDispatchState : null, this)) {
7472            return true;
7473        }
7474
7475        if (mInputEventConsistencyVerifier != null) {
7476            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7477        }
7478        return false;
7479    }
7480
7481    /**
7482     * Dispatches a key shortcut event.
7483     *
7484     * @param event The key event to be dispatched.
7485     * @return True if the event was handled by the view, false otherwise.
7486     */
7487    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7488        return onKeyShortcut(event.getKeyCode(), event);
7489    }
7490
7491    /**
7492     * Pass the touch screen motion event down to the target view, or this
7493     * view if it is the target.
7494     *
7495     * @param event The motion event to be dispatched.
7496     * @return True if the event was handled by the view, false otherwise.
7497     */
7498    public boolean dispatchTouchEvent(MotionEvent event) {
7499        if (mInputEventConsistencyVerifier != null) {
7500            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7501        }
7502
7503        if (onFilterTouchEventForSecurity(event)) {
7504            //noinspection SimplifiableIfStatement
7505            ListenerInfo li = mListenerInfo;
7506            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7507                    && li.mOnTouchListener.onTouch(this, event)) {
7508                return true;
7509            }
7510
7511            if (onTouchEvent(event)) {
7512                return true;
7513            }
7514        }
7515
7516        if (mInputEventConsistencyVerifier != null) {
7517            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7518        }
7519        return false;
7520    }
7521
7522    /**
7523     * Filter the touch event to apply security policies.
7524     *
7525     * @param event The motion event to be filtered.
7526     * @return True if the event should be dispatched, false if the event should be dropped.
7527     *
7528     * @see #getFilterTouchesWhenObscured
7529     */
7530    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7531        //noinspection RedundantIfStatement
7532        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7533                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7534            // Window is obscured, drop this touch.
7535            return false;
7536        }
7537        return true;
7538    }
7539
7540    /**
7541     * Pass a trackball motion event down to the focused view.
7542     *
7543     * @param event The motion event to be dispatched.
7544     * @return True if the event was handled by the view, false otherwise.
7545     */
7546    public boolean dispatchTrackballEvent(MotionEvent event) {
7547        if (mInputEventConsistencyVerifier != null) {
7548            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7549        }
7550
7551        return onTrackballEvent(event);
7552    }
7553
7554    /**
7555     * Dispatch a generic motion event.
7556     * <p>
7557     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7558     * are delivered to the view under the pointer.  All other generic motion events are
7559     * delivered to the focused view.  Hover events are handled specially and are delivered
7560     * to {@link #onHoverEvent(MotionEvent)}.
7561     * </p>
7562     *
7563     * @param event The motion event to be dispatched.
7564     * @return True if the event was handled by the view, false otherwise.
7565     */
7566    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7567        if (mInputEventConsistencyVerifier != null) {
7568            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7569        }
7570
7571        final int source = event.getSource();
7572        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7573            final int action = event.getAction();
7574            if (action == MotionEvent.ACTION_HOVER_ENTER
7575                    || action == MotionEvent.ACTION_HOVER_MOVE
7576                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7577                if (dispatchHoverEvent(event)) {
7578                    return true;
7579                }
7580            } else if (dispatchGenericPointerEvent(event)) {
7581                return true;
7582            }
7583        } else if (dispatchGenericFocusedEvent(event)) {
7584            return true;
7585        }
7586
7587        if (dispatchGenericMotionEventInternal(event)) {
7588            return true;
7589        }
7590
7591        if (mInputEventConsistencyVerifier != null) {
7592            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7593        }
7594        return false;
7595    }
7596
7597    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7598        //noinspection SimplifiableIfStatement
7599        ListenerInfo li = mListenerInfo;
7600        if (li != null && li.mOnGenericMotionListener != null
7601                && (mViewFlags & ENABLED_MASK) == ENABLED
7602                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7603            return true;
7604        }
7605
7606        if (onGenericMotionEvent(event)) {
7607            return true;
7608        }
7609
7610        if (mInputEventConsistencyVerifier != null) {
7611            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7612        }
7613        return false;
7614    }
7615
7616    /**
7617     * Dispatch a hover event.
7618     * <p>
7619     * Do not call this method directly.
7620     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7621     * </p>
7622     *
7623     * @param event The motion event to be dispatched.
7624     * @return True if the event was handled by the view, false otherwise.
7625     */
7626    protected boolean dispatchHoverEvent(MotionEvent event) {
7627        ListenerInfo li = mListenerInfo;
7628        //noinspection SimplifiableIfStatement
7629        if (li != null && li.mOnHoverListener != null
7630                && (mViewFlags & ENABLED_MASK) == ENABLED
7631                && li.mOnHoverListener.onHover(this, event)) {
7632            return true;
7633        }
7634
7635        return onHoverEvent(event);
7636    }
7637
7638    /**
7639     * Returns true if the view has a child to which it has recently sent
7640     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7641     * it does not have a hovered child, then it must be the innermost hovered view.
7642     * @hide
7643     */
7644    protected boolean hasHoveredChild() {
7645        return false;
7646    }
7647
7648    /**
7649     * Dispatch a generic motion event to the view under the first pointer.
7650     * <p>
7651     * Do not call this method directly.
7652     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7653     * </p>
7654     *
7655     * @param event The motion event to be dispatched.
7656     * @return True if the event was handled by the view, false otherwise.
7657     */
7658    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7659        return false;
7660    }
7661
7662    /**
7663     * Dispatch a generic motion event to the currently focused view.
7664     * <p>
7665     * Do not call this method directly.
7666     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7667     * </p>
7668     *
7669     * @param event The motion event to be dispatched.
7670     * @return True if the event was handled by the view, false otherwise.
7671     */
7672    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7673        return false;
7674    }
7675
7676    /**
7677     * Dispatch a pointer event.
7678     * <p>
7679     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7680     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7681     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7682     * and should not be expected to handle other pointing device features.
7683     * </p>
7684     *
7685     * @param event The motion event to be dispatched.
7686     * @return True if the event was handled by the view, false otherwise.
7687     * @hide
7688     */
7689    public final boolean dispatchPointerEvent(MotionEvent event) {
7690        if (event.isTouchEvent()) {
7691            return dispatchTouchEvent(event);
7692        } else {
7693            return dispatchGenericMotionEvent(event);
7694        }
7695    }
7696
7697    /**
7698     * Called when the window containing this view gains or loses window focus.
7699     * ViewGroups should override to route to their children.
7700     *
7701     * @param hasFocus True if the window containing this view now has focus,
7702     *        false otherwise.
7703     */
7704    public void dispatchWindowFocusChanged(boolean hasFocus) {
7705        onWindowFocusChanged(hasFocus);
7706    }
7707
7708    /**
7709     * Called when the window containing this view gains or loses focus.  Note
7710     * that this is separate from view focus: to receive key events, both
7711     * your view and its window must have focus.  If a window is displayed
7712     * on top of yours that takes input focus, then your own window will lose
7713     * focus but the view focus will remain unchanged.
7714     *
7715     * @param hasWindowFocus True if the window containing this view now has
7716     *        focus, false otherwise.
7717     */
7718    public void onWindowFocusChanged(boolean hasWindowFocus) {
7719        InputMethodManager imm = InputMethodManager.peekInstance();
7720        if (!hasWindowFocus) {
7721            if (isPressed()) {
7722                setPressed(false);
7723            }
7724            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7725                imm.focusOut(this);
7726            }
7727            removeLongPressCallback();
7728            removeTapCallback();
7729            onFocusLost();
7730        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7731            imm.focusIn(this);
7732        }
7733        refreshDrawableState();
7734    }
7735
7736    /**
7737     * Returns true if this view is in a window that currently has window focus.
7738     * Note that this is not the same as the view itself having focus.
7739     *
7740     * @return True if this view is in a window that currently has window focus.
7741     */
7742    public boolean hasWindowFocus() {
7743        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7744    }
7745
7746    /**
7747     * Dispatch a view visibility change down the view hierarchy.
7748     * ViewGroups should override to route to their children.
7749     * @param changedView The view whose visibility changed. Could be 'this' or
7750     * an ancestor view.
7751     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7752     * {@link #INVISIBLE} or {@link #GONE}.
7753     */
7754    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7755        onVisibilityChanged(changedView, visibility);
7756    }
7757
7758    /**
7759     * Called when the visibility of the view or an ancestor of the view is changed.
7760     * @param changedView The view whose visibility changed. Could be 'this' or
7761     * an ancestor view.
7762     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7763     * {@link #INVISIBLE} or {@link #GONE}.
7764     */
7765    protected void onVisibilityChanged(View changedView, int visibility) {
7766        if (visibility == VISIBLE) {
7767            if (mAttachInfo != null) {
7768                initialAwakenScrollBars();
7769            } else {
7770                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7771            }
7772        }
7773    }
7774
7775    /**
7776     * Dispatch a hint about whether this view is displayed. For instance, when
7777     * a View moves out of the screen, it might receives a display hint indicating
7778     * the view is not displayed. Applications should not <em>rely</em> on this hint
7779     * as there is no guarantee that they will receive one.
7780     *
7781     * @param hint A hint about whether or not this view is displayed:
7782     * {@link #VISIBLE} or {@link #INVISIBLE}.
7783     */
7784    public void dispatchDisplayHint(int hint) {
7785        onDisplayHint(hint);
7786    }
7787
7788    /**
7789     * Gives this view a hint about whether is displayed or not. For instance, when
7790     * a View moves out of the screen, it might receives a display hint indicating
7791     * the view is not displayed. Applications should not <em>rely</em> on this hint
7792     * as there is no guarantee that they will receive one.
7793     *
7794     * @param hint A hint about whether or not this view is displayed:
7795     * {@link #VISIBLE} or {@link #INVISIBLE}.
7796     */
7797    protected void onDisplayHint(int hint) {
7798    }
7799
7800    /**
7801     * Dispatch a window visibility change down the view hierarchy.
7802     * ViewGroups should override to route to their children.
7803     *
7804     * @param visibility The new visibility of the window.
7805     *
7806     * @see #onWindowVisibilityChanged(int)
7807     */
7808    public void dispatchWindowVisibilityChanged(int visibility) {
7809        onWindowVisibilityChanged(visibility);
7810    }
7811
7812    /**
7813     * Called when the window containing has change its visibility
7814     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7815     * that this tells you whether or not your window is being made visible
7816     * to the window manager; this does <em>not</em> tell you whether or not
7817     * your window is obscured by other windows on the screen, even if it
7818     * is itself visible.
7819     *
7820     * @param visibility The new visibility of the window.
7821     */
7822    protected void onWindowVisibilityChanged(int visibility) {
7823        if (visibility == VISIBLE) {
7824            initialAwakenScrollBars();
7825        }
7826    }
7827
7828    /**
7829     * Returns the current visibility of the window this view is attached to
7830     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7831     *
7832     * @return Returns the current visibility of the view's window.
7833     */
7834    public int getWindowVisibility() {
7835        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7836    }
7837
7838    /**
7839     * Retrieve the overall visible display size in which the window this view is
7840     * attached to has been positioned in.  This takes into account screen
7841     * decorations above the window, for both cases where the window itself
7842     * is being position inside of them or the window is being placed under
7843     * then and covered insets are used for the window to position its content
7844     * inside.  In effect, this tells you the available area where content can
7845     * be placed and remain visible to users.
7846     *
7847     * <p>This function requires an IPC back to the window manager to retrieve
7848     * the requested information, so should not be used in performance critical
7849     * code like drawing.
7850     *
7851     * @param outRect Filled in with the visible display frame.  If the view
7852     * is not attached to a window, this is simply the raw display size.
7853     */
7854    public void getWindowVisibleDisplayFrame(Rect outRect) {
7855        if (mAttachInfo != null) {
7856            try {
7857                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7858            } catch (RemoteException e) {
7859                return;
7860            }
7861            // XXX This is really broken, and probably all needs to be done
7862            // in the window manager, and we need to know more about whether
7863            // we want the area behind or in front of the IME.
7864            final Rect insets = mAttachInfo.mVisibleInsets;
7865            outRect.left += insets.left;
7866            outRect.top += insets.top;
7867            outRect.right -= insets.right;
7868            outRect.bottom -= insets.bottom;
7869            return;
7870        }
7871        // The view is not attached to a display so we don't have a context.
7872        // Make a best guess about the display size.
7873        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7874        d.getRectSize(outRect);
7875    }
7876
7877    /**
7878     * Dispatch a notification about a resource configuration change down
7879     * the view hierarchy.
7880     * ViewGroups should override to route to their children.
7881     *
7882     * @param newConfig The new resource configuration.
7883     *
7884     * @see #onConfigurationChanged(android.content.res.Configuration)
7885     */
7886    public void dispatchConfigurationChanged(Configuration newConfig) {
7887        onConfigurationChanged(newConfig);
7888    }
7889
7890    /**
7891     * Called when the current configuration of the resources being used
7892     * by the application have changed.  You can use this to decide when
7893     * to reload resources that can changed based on orientation and other
7894     * configuration characterstics.  You only need to use this if you are
7895     * not relying on the normal {@link android.app.Activity} mechanism of
7896     * recreating the activity instance upon a configuration change.
7897     *
7898     * @param newConfig The new resource configuration.
7899     */
7900    protected void onConfigurationChanged(Configuration newConfig) {
7901    }
7902
7903    /**
7904     * Private function to aggregate all per-view attributes in to the view
7905     * root.
7906     */
7907    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7908        performCollectViewAttributes(attachInfo, visibility);
7909    }
7910
7911    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7912        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7913            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7914                attachInfo.mKeepScreenOn = true;
7915            }
7916            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7917            ListenerInfo li = mListenerInfo;
7918            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7919                attachInfo.mHasSystemUiListeners = true;
7920            }
7921        }
7922    }
7923
7924    void needGlobalAttributesUpdate(boolean force) {
7925        final AttachInfo ai = mAttachInfo;
7926        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7927            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7928                    || ai.mHasSystemUiListeners) {
7929                ai.mRecomputeGlobalAttributes = true;
7930            }
7931        }
7932    }
7933
7934    /**
7935     * Returns whether the device is currently in touch mode.  Touch mode is entered
7936     * once the user begins interacting with the device by touch, and affects various
7937     * things like whether focus is always visible to the user.
7938     *
7939     * @return Whether the device is in touch mode.
7940     */
7941    @ViewDebug.ExportedProperty
7942    public boolean isInTouchMode() {
7943        if (mAttachInfo != null) {
7944            return mAttachInfo.mInTouchMode;
7945        } else {
7946            return ViewRootImpl.isInTouchMode();
7947        }
7948    }
7949
7950    /**
7951     * Returns the context the view is running in, through which it can
7952     * access the current theme, resources, etc.
7953     *
7954     * @return The view's Context.
7955     */
7956    @ViewDebug.CapturedViewProperty
7957    public final Context getContext() {
7958        return mContext;
7959    }
7960
7961    /**
7962     * Handle a key event before it is processed by any input method
7963     * associated with the view hierarchy.  This can be used to intercept
7964     * key events in special situations before the IME consumes them; a
7965     * typical example would be handling the BACK key to update the application's
7966     * UI instead of allowing the IME to see it and close itself.
7967     *
7968     * @param keyCode The value in event.getKeyCode().
7969     * @param event Description of the key event.
7970     * @return If you handled the event, return true. If you want to allow the
7971     *         event to be handled by the next receiver, return false.
7972     */
7973    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7974        return false;
7975    }
7976
7977    /**
7978     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7979     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7980     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7981     * is released, if the view is enabled and clickable.
7982     *
7983     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7984     * although some may elect to do so in some situations. Do not rely on this to
7985     * catch software key presses.
7986     *
7987     * @param keyCode A key code that represents the button pressed, from
7988     *                {@link android.view.KeyEvent}.
7989     * @param event   The KeyEvent object that defines the button action.
7990     */
7991    public boolean onKeyDown(int keyCode, KeyEvent event) {
7992        boolean result = false;
7993
7994        if (KeyEvent.isConfirmKey(event.getKeyCode())) {
7995            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7996                return true;
7997            }
7998            // Long clickable items don't necessarily have to be clickable
7999            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8000                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8001                    (event.getRepeatCount() == 0)) {
8002                setPressed(true);
8003                checkForLongClick(0);
8004                return true;
8005            }
8006        }
8007        return result;
8008    }
8009
8010    /**
8011     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8012     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8013     * the event).
8014     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8015     * although some may elect to do so in some situations. Do not rely on this to
8016     * catch software key presses.
8017     */
8018    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8019        return false;
8020    }
8021
8022    /**
8023     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8024     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8025     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8026     * {@link KeyEvent#KEYCODE_ENTER} is released.
8027     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8028     * although some may elect to do so in some situations. Do not rely on this to
8029     * catch software key presses.
8030     *
8031     * @param keyCode A key code that represents the button pressed, from
8032     *                {@link android.view.KeyEvent}.
8033     * @param event   The KeyEvent object that defines the button action.
8034     */
8035    public boolean onKeyUp(int keyCode, KeyEvent event) {
8036        boolean result = false;
8037
8038        switch (keyCode) {
8039            case KeyEvent.KEYCODE_DPAD_CENTER:
8040            case KeyEvent.KEYCODE_ENTER: {
8041                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8042                    return true;
8043                }
8044                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8045                    setPressed(false);
8046
8047                    if (!mHasPerformedLongPress) {
8048                        // This is a tap, so remove the longpress check
8049                        removeLongPressCallback();
8050
8051                        result = performClick();
8052                    }
8053                }
8054                break;
8055            }
8056        }
8057        return result;
8058    }
8059
8060    /**
8061     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8062     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8063     * the event).
8064     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8065     * although some may elect to do so in some situations. Do not rely on this to
8066     * catch software key presses.
8067     *
8068     * @param keyCode     A key code that represents the button pressed, from
8069     *                    {@link android.view.KeyEvent}.
8070     * @param repeatCount The number of times the action was made.
8071     * @param event       The KeyEvent object that defines the button action.
8072     */
8073    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8074        return false;
8075    }
8076
8077    /**
8078     * Called on the focused view when a key shortcut event is not handled.
8079     * Override this method to implement local key shortcuts for the View.
8080     * Key shortcuts can also be implemented by setting the
8081     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8082     *
8083     * @param keyCode The value in event.getKeyCode().
8084     * @param event Description of the key event.
8085     * @return If you handled the event, return true. If you want to allow the
8086     *         event to be handled by the next receiver, return false.
8087     */
8088    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8089        return false;
8090    }
8091
8092    /**
8093     * Check whether the called view is a text editor, in which case it
8094     * would make sense to automatically display a soft input window for
8095     * it.  Subclasses should override this if they implement
8096     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8097     * a call on that method would return a non-null InputConnection, and
8098     * they are really a first-class editor that the user would normally
8099     * start typing on when the go into a window containing your view.
8100     *
8101     * <p>The default implementation always returns false.  This does
8102     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8103     * will not be called or the user can not otherwise perform edits on your
8104     * view; it is just a hint to the system that this is not the primary
8105     * purpose of this view.
8106     *
8107     * @return Returns true if this view is a text editor, else false.
8108     */
8109    public boolean onCheckIsTextEditor() {
8110        return false;
8111    }
8112
8113    /**
8114     * Create a new InputConnection for an InputMethod to interact
8115     * with the view.  The default implementation returns null, since it doesn't
8116     * support input methods.  You can override this to implement such support.
8117     * This is only needed for views that take focus and text input.
8118     *
8119     * <p>When implementing this, you probably also want to implement
8120     * {@link #onCheckIsTextEditor()} to indicate you will return a
8121     * non-null InputConnection.
8122     *
8123     * @param outAttrs Fill in with attribute information about the connection.
8124     */
8125    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8126        return null;
8127    }
8128
8129    /**
8130     * Called by the {@link android.view.inputmethod.InputMethodManager}
8131     * when a view who is not the current
8132     * input connection target is trying to make a call on the manager.  The
8133     * default implementation returns false; you can override this to return
8134     * true for certain views if you are performing InputConnection proxying
8135     * to them.
8136     * @param view The View that is making the InputMethodManager call.
8137     * @return Return true to allow the call, false to reject.
8138     */
8139    public boolean checkInputConnectionProxy(View view) {
8140        return false;
8141    }
8142
8143    /**
8144     * Show the context menu for this view. It is not safe to hold on to the
8145     * menu after returning from this method.
8146     *
8147     * You should normally not overload this method. Overload
8148     * {@link #onCreateContextMenu(ContextMenu)} or define an
8149     * {@link OnCreateContextMenuListener} to add items to the context menu.
8150     *
8151     * @param menu The context menu to populate
8152     */
8153    public void createContextMenu(ContextMenu menu) {
8154        ContextMenuInfo menuInfo = getContextMenuInfo();
8155
8156        // Sets the current menu info so all items added to menu will have
8157        // my extra info set.
8158        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8159
8160        onCreateContextMenu(menu);
8161        ListenerInfo li = mListenerInfo;
8162        if (li != null && li.mOnCreateContextMenuListener != null) {
8163            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8164        }
8165
8166        // Clear the extra information so subsequent items that aren't mine don't
8167        // have my extra info.
8168        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8169
8170        if (mParent != null) {
8171            mParent.createContextMenu(menu);
8172        }
8173    }
8174
8175    /**
8176     * Views should implement this if they have extra information to associate
8177     * with the context menu. The return result is supplied as a parameter to
8178     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8179     * callback.
8180     *
8181     * @return Extra information about the item for which the context menu
8182     *         should be shown. This information will vary across different
8183     *         subclasses of View.
8184     */
8185    protected ContextMenuInfo getContextMenuInfo() {
8186        return null;
8187    }
8188
8189    /**
8190     * Views should implement this if the view itself is going to add items to
8191     * the context menu.
8192     *
8193     * @param menu the context menu to populate
8194     */
8195    protected void onCreateContextMenu(ContextMenu menu) {
8196    }
8197
8198    /**
8199     * Implement this method to handle trackball motion events.  The
8200     * <em>relative</em> movement of the trackball since the last event
8201     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8202     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8203     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8204     * they will often be fractional values, representing the more fine-grained
8205     * movement information available from a trackball).
8206     *
8207     * @param event The motion event.
8208     * @return True if the event was handled, false otherwise.
8209     */
8210    public boolean onTrackballEvent(MotionEvent event) {
8211        return false;
8212    }
8213
8214    /**
8215     * Implement this method to handle generic motion events.
8216     * <p>
8217     * Generic motion events describe joystick movements, mouse hovers, track pad
8218     * touches, scroll wheel movements and other input events.  The
8219     * {@link MotionEvent#getSource() source} of the motion event specifies
8220     * the class of input that was received.  Implementations of this method
8221     * must examine the bits in the source before processing the event.
8222     * The following code example shows how this is done.
8223     * </p><p>
8224     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8225     * are delivered to the view under the pointer.  All other generic motion events are
8226     * delivered to the focused view.
8227     * </p>
8228     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8229     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8230     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8231     *             // process the joystick movement...
8232     *             return true;
8233     *         }
8234     *     }
8235     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8236     *         switch (event.getAction()) {
8237     *             case MotionEvent.ACTION_HOVER_MOVE:
8238     *                 // process the mouse hover movement...
8239     *                 return true;
8240     *             case MotionEvent.ACTION_SCROLL:
8241     *                 // process the scroll wheel movement...
8242     *                 return true;
8243     *         }
8244     *     }
8245     *     return super.onGenericMotionEvent(event);
8246     * }</pre>
8247     *
8248     * @param event The generic motion event being processed.
8249     * @return True if the event was handled, false otherwise.
8250     */
8251    public boolean onGenericMotionEvent(MotionEvent event) {
8252        return false;
8253    }
8254
8255    /**
8256     * Implement this method to handle hover events.
8257     * <p>
8258     * This method is called whenever a pointer is hovering into, over, or out of the
8259     * bounds of a view and the view is not currently being touched.
8260     * Hover events are represented as pointer events with action
8261     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8262     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8263     * </p>
8264     * <ul>
8265     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8266     * when the pointer enters the bounds of the view.</li>
8267     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8268     * when the pointer has already entered the bounds of the view and has moved.</li>
8269     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8270     * when the pointer has exited the bounds of the view or when the pointer is
8271     * about to go down due to a button click, tap, or similar user action that
8272     * causes the view to be touched.</li>
8273     * </ul>
8274     * <p>
8275     * The view should implement this method to return true to indicate that it is
8276     * handling the hover event, such as by changing its drawable state.
8277     * </p><p>
8278     * The default implementation calls {@link #setHovered} to update the hovered state
8279     * of the view when a hover enter or hover exit event is received, if the view
8280     * is enabled and is clickable.  The default implementation also sends hover
8281     * accessibility events.
8282     * </p>
8283     *
8284     * @param event The motion event that describes the hover.
8285     * @return True if the view handled the hover event.
8286     *
8287     * @see #isHovered
8288     * @see #setHovered
8289     * @see #onHoverChanged
8290     */
8291    public boolean onHoverEvent(MotionEvent event) {
8292        // The root view may receive hover (or touch) events that are outside the bounds of
8293        // the window.  This code ensures that we only send accessibility events for
8294        // hovers that are actually within the bounds of the root view.
8295        final int action = event.getActionMasked();
8296        if (!mSendingHoverAccessibilityEvents) {
8297            if ((action == MotionEvent.ACTION_HOVER_ENTER
8298                    || action == MotionEvent.ACTION_HOVER_MOVE)
8299                    && !hasHoveredChild()
8300                    && pointInView(event.getX(), event.getY())) {
8301                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8302                mSendingHoverAccessibilityEvents = true;
8303            }
8304        } else {
8305            if (action == MotionEvent.ACTION_HOVER_EXIT
8306                    || (action == MotionEvent.ACTION_MOVE
8307                            && !pointInView(event.getX(), event.getY()))) {
8308                mSendingHoverAccessibilityEvents = false;
8309                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8310                // If the window does not have input focus we take away accessibility
8311                // focus as soon as the user stop hovering over the view.
8312                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8313                    getViewRootImpl().setAccessibilityFocus(null, null);
8314                }
8315            }
8316        }
8317
8318        if (isHoverable()) {
8319            switch (action) {
8320                case MotionEvent.ACTION_HOVER_ENTER:
8321                    setHovered(true);
8322                    break;
8323                case MotionEvent.ACTION_HOVER_EXIT:
8324                    setHovered(false);
8325                    break;
8326            }
8327
8328            // Dispatch the event to onGenericMotionEvent before returning true.
8329            // This is to provide compatibility with existing applications that
8330            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8331            // break because of the new default handling for hoverable views
8332            // in onHoverEvent.
8333            // Note that onGenericMotionEvent will be called by default when
8334            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8335            dispatchGenericMotionEventInternal(event);
8336            // The event was already handled by calling setHovered(), so always
8337            // return true.
8338            return true;
8339        }
8340
8341        return false;
8342    }
8343
8344    /**
8345     * Returns true if the view should handle {@link #onHoverEvent}
8346     * by calling {@link #setHovered} to change its hovered state.
8347     *
8348     * @return True if the view is hoverable.
8349     */
8350    private boolean isHoverable() {
8351        final int viewFlags = mViewFlags;
8352        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8353            return false;
8354        }
8355
8356        return (viewFlags & CLICKABLE) == CLICKABLE
8357                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8358    }
8359
8360    /**
8361     * Returns true if the view is currently hovered.
8362     *
8363     * @return True if the view is currently hovered.
8364     *
8365     * @see #setHovered
8366     * @see #onHoverChanged
8367     */
8368    @ViewDebug.ExportedProperty
8369    public boolean isHovered() {
8370        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8371    }
8372
8373    /**
8374     * Sets whether the view is currently hovered.
8375     * <p>
8376     * Calling this method also changes the drawable state of the view.  This
8377     * enables the view to react to hover by using different drawable resources
8378     * to change its appearance.
8379     * </p><p>
8380     * The {@link #onHoverChanged} method is called when the hovered state changes.
8381     * </p>
8382     *
8383     * @param hovered True if the view is hovered.
8384     *
8385     * @see #isHovered
8386     * @see #onHoverChanged
8387     */
8388    public void setHovered(boolean hovered) {
8389        if (hovered) {
8390            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8391                mPrivateFlags |= PFLAG_HOVERED;
8392                refreshDrawableState();
8393                onHoverChanged(true);
8394            }
8395        } else {
8396            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8397                mPrivateFlags &= ~PFLAG_HOVERED;
8398                refreshDrawableState();
8399                onHoverChanged(false);
8400            }
8401        }
8402    }
8403
8404    /**
8405     * Implement this method to handle hover state changes.
8406     * <p>
8407     * This method is called whenever the hover state changes as a result of a
8408     * call to {@link #setHovered}.
8409     * </p>
8410     *
8411     * @param hovered The current hover state, as returned by {@link #isHovered}.
8412     *
8413     * @see #isHovered
8414     * @see #setHovered
8415     */
8416    public void onHoverChanged(boolean hovered) {
8417    }
8418
8419    /**
8420     * Implement this method to handle touch screen motion events.
8421     *
8422     * @param event The motion event.
8423     * @return True if the event was handled, false otherwise.
8424     */
8425    public boolean onTouchEvent(MotionEvent event) {
8426        final int viewFlags = mViewFlags;
8427
8428        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8429            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8430                setPressed(false);
8431            }
8432            // A disabled view that is clickable still consumes the touch
8433            // events, it just doesn't respond to them.
8434            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8435                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8436        }
8437
8438        if (mTouchDelegate != null) {
8439            if (mTouchDelegate.onTouchEvent(event)) {
8440                return true;
8441            }
8442        }
8443
8444        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8445                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8446            switch (event.getAction()) {
8447                case MotionEvent.ACTION_UP:
8448                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8449                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8450                        // take focus if we don't have it already and we should in
8451                        // touch mode.
8452                        boolean focusTaken = false;
8453                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8454                            focusTaken = requestFocus();
8455                        }
8456
8457                        if (prepressed) {
8458                            // The button is being released before we actually
8459                            // showed it as pressed.  Make it show the pressed
8460                            // state now (before scheduling the click) to ensure
8461                            // the user sees it.
8462                            setPressed(true);
8463                       }
8464
8465                        if (!mHasPerformedLongPress) {
8466                            // This is a tap, so remove the longpress check
8467                            removeLongPressCallback();
8468
8469                            // Only perform take click actions if we were in the pressed state
8470                            if (!focusTaken) {
8471                                // Use a Runnable and post this rather than calling
8472                                // performClick directly. This lets other visual state
8473                                // of the view update before click actions start.
8474                                if (mPerformClick == null) {
8475                                    mPerformClick = new PerformClick();
8476                                }
8477                                if (!post(mPerformClick)) {
8478                                    performClick();
8479                                }
8480                            }
8481                        }
8482
8483                        if (mUnsetPressedState == null) {
8484                            mUnsetPressedState = new UnsetPressedState();
8485                        }
8486
8487                        if (prepressed) {
8488                            postDelayed(mUnsetPressedState,
8489                                    ViewConfiguration.getPressedStateDuration());
8490                        } else if (!post(mUnsetPressedState)) {
8491                            // If the post failed, unpress right now
8492                            mUnsetPressedState.run();
8493                        }
8494                        removeTapCallback();
8495                    }
8496                    break;
8497
8498                case MotionEvent.ACTION_DOWN:
8499                    mHasPerformedLongPress = false;
8500
8501                    if (performButtonActionOnTouchDown(event)) {
8502                        break;
8503                    }
8504
8505                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8506                    boolean isInScrollingContainer = isInScrollingContainer();
8507
8508                    // For views inside a scrolling container, delay the pressed feedback for
8509                    // a short period in case this is a scroll.
8510                    if (isInScrollingContainer) {
8511                        mPrivateFlags |= PFLAG_PREPRESSED;
8512                        if (mPendingCheckForTap == null) {
8513                            mPendingCheckForTap = new CheckForTap();
8514                        }
8515                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8516                    } else {
8517                        // Not inside a scrolling container, so show the feedback right away
8518                        setPressed(true);
8519                        checkForLongClick(0);
8520                    }
8521                    break;
8522
8523                case MotionEvent.ACTION_CANCEL:
8524                    setPressed(false);
8525                    removeTapCallback();
8526                    removeLongPressCallback();
8527                    break;
8528
8529                case MotionEvent.ACTION_MOVE:
8530                    final int x = (int) event.getX();
8531                    final int y = (int) event.getY();
8532
8533                    // Be lenient about moving outside of buttons
8534                    if (!pointInView(x, y, mTouchSlop)) {
8535                        // Outside button
8536                        removeTapCallback();
8537                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8538                            // Remove any future long press/tap checks
8539                            removeLongPressCallback();
8540
8541                            setPressed(false);
8542                        }
8543                    }
8544                    break;
8545            }
8546            return true;
8547        }
8548
8549        return false;
8550    }
8551
8552    /**
8553     * @hide
8554     */
8555    public boolean isInScrollingContainer() {
8556        ViewParent p = getParent();
8557        while (p != null && p instanceof ViewGroup) {
8558            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8559                return true;
8560            }
8561            p = p.getParent();
8562        }
8563        return false;
8564    }
8565
8566    /**
8567     * Remove the longpress detection timer.
8568     */
8569    private void removeLongPressCallback() {
8570        if (mPendingCheckForLongPress != null) {
8571          removeCallbacks(mPendingCheckForLongPress);
8572        }
8573    }
8574
8575    /**
8576     * Remove the pending click action
8577     */
8578    private void removePerformClickCallback() {
8579        if (mPerformClick != null) {
8580            removeCallbacks(mPerformClick);
8581        }
8582    }
8583
8584    /**
8585     * Remove the prepress detection timer.
8586     */
8587    private void removeUnsetPressCallback() {
8588        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8589            setPressed(false);
8590            removeCallbacks(mUnsetPressedState);
8591        }
8592    }
8593
8594    /**
8595     * Remove the tap detection timer.
8596     */
8597    private void removeTapCallback() {
8598        if (mPendingCheckForTap != null) {
8599            mPrivateFlags &= ~PFLAG_PREPRESSED;
8600            removeCallbacks(mPendingCheckForTap);
8601        }
8602    }
8603
8604    /**
8605     * Cancels a pending long press.  Your subclass can use this if you
8606     * want the context menu to come up if the user presses and holds
8607     * at the same place, but you don't want it to come up if they press
8608     * and then move around enough to cause scrolling.
8609     */
8610    public void cancelLongPress() {
8611        removeLongPressCallback();
8612
8613        /*
8614         * The prepressed state handled by the tap callback is a display
8615         * construct, but the tap callback will post a long press callback
8616         * less its own timeout. Remove it here.
8617         */
8618        removeTapCallback();
8619    }
8620
8621    /**
8622     * Remove the pending callback for sending a
8623     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8624     */
8625    private void removeSendViewScrolledAccessibilityEventCallback() {
8626        if (mSendViewScrolledAccessibilityEvent != null) {
8627            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8628            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8629        }
8630    }
8631
8632    /**
8633     * Sets the TouchDelegate for this View.
8634     */
8635    public void setTouchDelegate(TouchDelegate delegate) {
8636        mTouchDelegate = delegate;
8637    }
8638
8639    /**
8640     * Gets the TouchDelegate for this View.
8641     */
8642    public TouchDelegate getTouchDelegate() {
8643        return mTouchDelegate;
8644    }
8645
8646    /**
8647     * Set flags controlling behavior of this view.
8648     *
8649     * @param flags Constant indicating the value which should be set
8650     * @param mask Constant indicating the bit range that should be changed
8651     */
8652    void setFlags(int flags, int mask) {
8653        final boolean accessibilityEnabled =
8654                AccessibilityManager.getInstance(mContext).isEnabled();
8655        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8656
8657        int old = mViewFlags;
8658        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8659
8660        int changed = mViewFlags ^ old;
8661        if (changed == 0) {
8662            return;
8663        }
8664        int privateFlags = mPrivateFlags;
8665
8666        /* Check if the FOCUSABLE bit has changed */
8667        if (((changed & FOCUSABLE_MASK) != 0) &&
8668                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8669            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8670                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8671                /* Give up focus if we are no longer focusable */
8672                clearFocus();
8673            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8674                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8675                /*
8676                 * Tell the view system that we are now available to take focus
8677                 * if no one else already has it.
8678                 */
8679                if (mParent != null) mParent.focusableViewAvailable(this);
8680            }
8681        }
8682
8683        final int newVisibility = flags & VISIBILITY_MASK;
8684        if (newVisibility == VISIBLE) {
8685            if ((changed & VISIBILITY_MASK) != 0) {
8686                /*
8687                 * If this view is becoming visible, invalidate it in case it changed while
8688                 * it was not visible. Marking it drawn ensures that the invalidation will
8689                 * go through.
8690                 */
8691                mPrivateFlags |= PFLAG_DRAWN;
8692                invalidate(true);
8693
8694                needGlobalAttributesUpdate(true);
8695
8696                // a view becoming visible is worth notifying the parent
8697                // about in case nothing has focus.  even if this specific view
8698                // isn't focusable, it may contain something that is, so let
8699                // the root view try to give this focus if nothing else does.
8700                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8701                    mParent.focusableViewAvailable(this);
8702                }
8703            }
8704        }
8705
8706        /* Check if the GONE bit has changed */
8707        if ((changed & GONE) != 0) {
8708            needGlobalAttributesUpdate(false);
8709            requestLayout();
8710
8711            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8712                if (hasFocus()) clearFocus();
8713                clearAccessibilityFocus();
8714                destroyDrawingCache();
8715                if (mParent instanceof View) {
8716                    // GONE views noop invalidation, so invalidate the parent
8717                    ((View) mParent).invalidate(true);
8718                }
8719                // Mark the view drawn to ensure that it gets invalidated properly the next
8720                // time it is visible and gets invalidated
8721                mPrivateFlags |= PFLAG_DRAWN;
8722            }
8723            if (mAttachInfo != null) {
8724                mAttachInfo.mViewVisibilityChanged = true;
8725            }
8726        }
8727
8728        /* Check if the VISIBLE bit has changed */
8729        if ((changed & INVISIBLE) != 0) {
8730            needGlobalAttributesUpdate(false);
8731            /*
8732             * If this view is becoming invisible, set the DRAWN flag so that
8733             * the next invalidate() will not be skipped.
8734             */
8735            mPrivateFlags |= PFLAG_DRAWN;
8736
8737            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8738                // root view becoming invisible shouldn't clear focus and accessibility focus
8739                if (getRootView() != this) {
8740                    clearFocus();
8741                    clearAccessibilityFocus();
8742                }
8743            }
8744            if (mAttachInfo != null) {
8745                mAttachInfo.mViewVisibilityChanged = true;
8746            }
8747        }
8748
8749        if ((changed & VISIBILITY_MASK) != 0) {
8750            // If the view is invisible, cleanup its display list to free up resources
8751            if (newVisibility != VISIBLE) {
8752                cleanupDraw();
8753            }
8754
8755            if (mParent instanceof ViewGroup) {
8756                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8757                        (changed & VISIBILITY_MASK), newVisibility);
8758                ((View) mParent).invalidate(true);
8759            } else if (mParent != null) {
8760                mParent.invalidateChild(this, null);
8761            }
8762            dispatchVisibilityChanged(this, newVisibility);
8763        }
8764
8765        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8766            destroyDrawingCache();
8767        }
8768
8769        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8770            destroyDrawingCache();
8771            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8772            invalidateParentCaches();
8773        }
8774
8775        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8776            destroyDrawingCache();
8777            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8778        }
8779
8780        if ((changed & DRAW_MASK) != 0) {
8781            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8782                if (mBackground != null) {
8783                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8784                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8785                } else {
8786                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8787                }
8788            } else {
8789                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8790            }
8791            requestLayout();
8792            invalidate(true);
8793        }
8794
8795        if ((changed & KEEP_SCREEN_ON) != 0) {
8796            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8797                mParent.recomputeViewAttributes(this);
8798            }
8799        }
8800
8801        if (accessibilityEnabled) {
8802            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8803                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8804                if (oldIncludeForAccessibility != includeForAccessibility()) {
8805                    notifySubtreeAccessibilityStateChangedIfNeeded();
8806                } else {
8807                    notifyViewAccessibilityStateChangedIfNeeded();
8808                }
8809            }
8810            if ((changed & ENABLED_MASK) != 0) {
8811                notifyViewAccessibilityStateChangedIfNeeded();
8812            }
8813        }
8814    }
8815
8816    /**
8817     * Change the view's z order in the tree, so it's on top of other sibling
8818     * views. This ordering change may affect layout, if the parent container
8819     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8820     * method should be followed by calls to {@link #requestLayout()} and
8821     * {@link View#invalidate()} on the parent.
8822     *
8823     * @see ViewGroup#bringChildToFront(View)
8824     */
8825    public void bringToFront() {
8826        if (mParent != null) {
8827            mParent.bringChildToFront(this);
8828        }
8829    }
8830
8831    /**
8832     * This is called in response to an internal scroll in this view (i.e., the
8833     * view scrolled its own contents). This is typically as a result of
8834     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8835     * called.
8836     *
8837     * @param l Current horizontal scroll origin.
8838     * @param t Current vertical scroll origin.
8839     * @param oldl Previous horizontal scroll origin.
8840     * @param oldt Previous vertical scroll origin.
8841     */
8842    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8843        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8844            postSendViewScrolledAccessibilityEventCallback();
8845        }
8846
8847        mBackgroundSizeChanged = true;
8848
8849        final AttachInfo ai = mAttachInfo;
8850        if (ai != null) {
8851            ai.mViewScrollChanged = true;
8852        }
8853    }
8854
8855    /**
8856     * Interface definition for a callback to be invoked when the layout bounds of a view
8857     * changes due to layout processing.
8858     */
8859    public interface OnLayoutChangeListener {
8860        /**
8861         * Called when the focus state of a view has changed.
8862         *
8863         * @param v The view whose state has changed.
8864         * @param left The new value of the view's left property.
8865         * @param top The new value of the view's top property.
8866         * @param right The new value of the view's right property.
8867         * @param bottom The new value of the view's bottom property.
8868         * @param oldLeft The previous value of the view's left property.
8869         * @param oldTop The previous value of the view's top property.
8870         * @param oldRight The previous value of the view's right property.
8871         * @param oldBottom The previous value of the view's bottom property.
8872         */
8873        void onLayoutChange(View v, int left, int top, int right, int bottom,
8874            int oldLeft, int oldTop, int oldRight, int oldBottom);
8875    }
8876
8877    /**
8878     * This is called during layout when the size of this view has changed. If
8879     * you were just added to the view hierarchy, you're called with the old
8880     * values of 0.
8881     *
8882     * @param w Current width of this view.
8883     * @param h Current height of this view.
8884     * @param oldw Old width of this view.
8885     * @param oldh Old height of this view.
8886     */
8887    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8888    }
8889
8890    /**
8891     * Called by draw to draw the child views. This may be overridden
8892     * by derived classes to gain control just before its children are drawn
8893     * (but after its own view has been drawn).
8894     * @param canvas the canvas on which to draw the view
8895     */
8896    protected void dispatchDraw(Canvas canvas) {
8897
8898    }
8899
8900    /**
8901     * Gets the parent of this view. Note that the parent is a
8902     * ViewParent and not necessarily a View.
8903     *
8904     * @return Parent of this view.
8905     */
8906    public final ViewParent getParent() {
8907        return mParent;
8908    }
8909
8910    /**
8911     * Set the horizontal scrolled position of your view. This will cause a call to
8912     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8913     * invalidated.
8914     * @param value the x position to scroll to
8915     */
8916    public void setScrollX(int value) {
8917        scrollTo(value, mScrollY);
8918    }
8919
8920    /**
8921     * Set the vertical scrolled position of your view. This will cause a call to
8922     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8923     * invalidated.
8924     * @param value the y position to scroll to
8925     */
8926    public void setScrollY(int value) {
8927        scrollTo(mScrollX, value);
8928    }
8929
8930    /**
8931     * Return the scrolled left position of this view. This is the left edge of
8932     * the displayed part of your view. You do not need to draw any pixels
8933     * farther left, since those are outside of the frame of your view on
8934     * screen.
8935     *
8936     * @return The left edge of the displayed part of your view, in pixels.
8937     */
8938    public final int getScrollX() {
8939        return mScrollX;
8940    }
8941
8942    /**
8943     * Return the scrolled top position of this view. This is the top edge of
8944     * the displayed part of your view. You do not need to draw any pixels above
8945     * it, since those are outside of the frame of your view on screen.
8946     *
8947     * @return The top edge of the displayed part of your view, in pixels.
8948     */
8949    public final int getScrollY() {
8950        return mScrollY;
8951    }
8952
8953    /**
8954     * Return the width of the your view.
8955     *
8956     * @return The width of your view, in pixels.
8957     */
8958    @ViewDebug.ExportedProperty(category = "layout")
8959    public final int getWidth() {
8960        return mRight - mLeft;
8961    }
8962
8963    /**
8964     * Return the height of your view.
8965     *
8966     * @return The height of your view, in pixels.
8967     */
8968    @ViewDebug.ExportedProperty(category = "layout")
8969    public final int getHeight() {
8970        return mBottom - mTop;
8971    }
8972
8973    /**
8974     * Return the visible drawing bounds of your view. Fills in the output
8975     * rectangle with the values from getScrollX(), getScrollY(),
8976     * getWidth(), and getHeight(). These bounds do not account for any
8977     * transformation properties currently set on the view, such as
8978     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8979     *
8980     * @param outRect The (scrolled) drawing bounds of the view.
8981     */
8982    public void getDrawingRect(Rect outRect) {
8983        outRect.left = mScrollX;
8984        outRect.top = mScrollY;
8985        outRect.right = mScrollX + (mRight - mLeft);
8986        outRect.bottom = mScrollY + (mBottom - mTop);
8987    }
8988
8989    /**
8990     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8991     * raw width component (that is the result is masked by
8992     * {@link #MEASURED_SIZE_MASK}).
8993     *
8994     * @return The raw measured width of this view.
8995     */
8996    public final int getMeasuredWidth() {
8997        return mMeasuredWidth & MEASURED_SIZE_MASK;
8998    }
8999
9000    /**
9001     * Return the full width measurement information for this view as computed
9002     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9003     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9004     * This should be used during measurement and layout calculations only. Use
9005     * {@link #getWidth()} to see how wide a view is after layout.
9006     *
9007     * @return The measured width of this view as a bit mask.
9008     */
9009    public final int getMeasuredWidthAndState() {
9010        return mMeasuredWidth;
9011    }
9012
9013    /**
9014     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9015     * raw width component (that is the result is masked by
9016     * {@link #MEASURED_SIZE_MASK}).
9017     *
9018     * @return The raw measured height of this view.
9019     */
9020    public final int getMeasuredHeight() {
9021        return mMeasuredHeight & MEASURED_SIZE_MASK;
9022    }
9023
9024    /**
9025     * Return the full height measurement information for this view as computed
9026     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9027     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9028     * This should be used during measurement and layout calculations only. Use
9029     * {@link #getHeight()} to see how wide a view is after layout.
9030     *
9031     * @return The measured width of this view as a bit mask.
9032     */
9033    public final int getMeasuredHeightAndState() {
9034        return mMeasuredHeight;
9035    }
9036
9037    /**
9038     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9039     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9040     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9041     * and the height component is at the shifted bits
9042     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9043     */
9044    public final int getMeasuredState() {
9045        return (mMeasuredWidth&MEASURED_STATE_MASK)
9046                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9047                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9048    }
9049
9050    /**
9051     * The transform matrix of this view, which is calculated based on the current
9052     * roation, scale, and pivot properties.
9053     *
9054     * @see #getRotation()
9055     * @see #getScaleX()
9056     * @see #getScaleY()
9057     * @see #getPivotX()
9058     * @see #getPivotY()
9059     * @return The current transform matrix for the view
9060     */
9061    public Matrix getMatrix() {
9062        if (mTransformationInfo != null) {
9063            updateMatrix();
9064            return mTransformationInfo.mMatrix;
9065        }
9066        return Matrix.IDENTITY_MATRIX;
9067    }
9068
9069    /**
9070     * Utility function to determine if the value is far enough away from zero to be
9071     * considered non-zero.
9072     * @param value A floating point value to check for zero-ness
9073     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9074     */
9075    private static boolean nonzero(float value) {
9076        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9077    }
9078
9079    /**
9080     * Returns true if the transform matrix is the identity matrix.
9081     * Recomputes the matrix if necessary.
9082     *
9083     * @return True if the transform matrix is the identity matrix, false otherwise.
9084     */
9085    final boolean hasIdentityMatrix() {
9086        if (mTransformationInfo != null) {
9087            updateMatrix();
9088            return mTransformationInfo.mMatrixIsIdentity;
9089        }
9090        return true;
9091    }
9092
9093    void ensureTransformationInfo() {
9094        if (mTransformationInfo == null) {
9095            mTransformationInfo = new TransformationInfo();
9096        }
9097    }
9098
9099    /**
9100     * Recomputes the transform matrix if necessary.
9101     */
9102    private void updateMatrix() {
9103        final TransformationInfo info = mTransformationInfo;
9104        if (info == null) {
9105            return;
9106        }
9107        if (info.mMatrixDirty) {
9108            // transform-related properties have changed since the last time someone
9109            // asked for the matrix; recalculate it with the current values
9110
9111            // Figure out if we need to update the pivot point
9112            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9113                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9114                    info.mPrevWidth = mRight - mLeft;
9115                    info.mPrevHeight = mBottom - mTop;
9116                    info.mPivotX = info.mPrevWidth / 2f;
9117                    info.mPivotY = info.mPrevHeight / 2f;
9118                }
9119            }
9120            info.mMatrix.reset();
9121            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9122                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9123                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9124                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9125            } else {
9126                if (info.mCamera == null) {
9127                    info.mCamera = new Camera();
9128                    info.matrix3D = new Matrix();
9129                }
9130                info.mCamera.save();
9131                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9132                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9133                info.mCamera.getMatrix(info.matrix3D);
9134                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9135                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9136                        info.mPivotY + info.mTranslationY);
9137                info.mMatrix.postConcat(info.matrix3D);
9138                info.mCamera.restore();
9139            }
9140            info.mMatrixDirty = false;
9141            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9142            info.mInverseMatrixDirty = true;
9143        }
9144    }
9145
9146   /**
9147     * Utility method to retrieve the inverse of the current mMatrix property.
9148     * We cache the matrix to avoid recalculating it when transform properties
9149     * have not changed.
9150     *
9151     * @return The inverse of the current matrix of this view.
9152     */
9153    final Matrix getInverseMatrix() {
9154        final TransformationInfo info = mTransformationInfo;
9155        if (info != null) {
9156            updateMatrix();
9157            if (info.mInverseMatrixDirty) {
9158                if (info.mInverseMatrix == null) {
9159                    info.mInverseMatrix = new Matrix();
9160                }
9161                info.mMatrix.invert(info.mInverseMatrix);
9162                info.mInverseMatrixDirty = false;
9163            }
9164            return info.mInverseMatrix;
9165        }
9166        return Matrix.IDENTITY_MATRIX;
9167    }
9168
9169    /**
9170     * Gets the distance along the Z axis from the camera to this view.
9171     *
9172     * @see #setCameraDistance(float)
9173     *
9174     * @return The distance along the Z axis.
9175     */
9176    public float getCameraDistance() {
9177        ensureTransformationInfo();
9178        final float dpi = mResources.getDisplayMetrics().densityDpi;
9179        final TransformationInfo info = mTransformationInfo;
9180        if (info.mCamera == null) {
9181            info.mCamera = new Camera();
9182            info.matrix3D = new Matrix();
9183        }
9184        return -(info.mCamera.getLocationZ() * dpi);
9185    }
9186
9187    /**
9188     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9189     * views are drawn) from the camera to this view. The camera's distance
9190     * affects 3D transformations, for instance rotations around the X and Y
9191     * axis. If the rotationX or rotationY properties are changed and this view is
9192     * large (more than half the size of the screen), it is recommended to always
9193     * use a camera distance that's greater than the height (X axis rotation) or
9194     * the width (Y axis rotation) of this view.</p>
9195     *
9196     * <p>The distance of the camera from the view plane can have an affect on the
9197     * perspective distortion of the view when it is rotated around the x or y axis.
9198     * For example, a large distance will result in a large viewing angle, and there
9199     * will not be much perspective distortion of the view as it rotates. A short
9200     * distance may cause much more perspective distortion upon rotation, and can
9201     * also result in some drawing artifacts if the rotated view ends up partially
9202     * behind the camera (which is why the recommendation is to use a distance at
9203     * least as far as the size of the view, if the view is to be rotated.)</p>
9204     *
9205     * <p>The distance is expressed in "depth pixels." The default distance depends
9206     * on the screen density. For instance, on a medium density display, the
9207     * default distance is 1280. On a high density display, the default distance
9208     * is 1920.</p>
9209     *
9210     * <p>If you want to specify a distance that leads to visually consistent
9211     * results across various densities, use the following formula:</p>
9212     * <pre>
9213     * float scale = context.getResources().getDisplayMetrics().density;
9214     * view.setCameraDistance(distance * scale);
9215     * </pre>
9216     *
9217     * <p>The density scale factor of a high density display is 1.5,
9218     * and 1920 = 1280 * 1.5.</p>
9219     *
9220     * @param distance The distance in "depth pixels", if negative the opposite
9221     *        value is used
9222     *
9223     * @see #setRotationX(float)
9224     * @see #setRotationY(float)
9225     */
9226    public void setCameraDistance(float distance) {
9227        invalidateViewProperty(true, false);
9228
9229        ensureTransformationInfo();
9230        final float dpi = mResources.getDisplayMetrics().densityDpi;
9231        final TransformationInfo info = mTransformationInfo;
9232        if (info.mCamera == null) {
9233            info.mCamera = new Camera();
9234            info.matrix3D = new Matrix();
9235        }
9236
9237        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9238        info.mMatrixDirty = true;
9239
9240        invalidateViewProperty(false, false);
9241        if (mDisplayList != null) {
9242            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9243        }
9244        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9245            // View was rejected last time it was drawn by its parent; this may have changed
9246            invalidateParentIfNeeded();
9247        }
9248    }
9249
9250    /**
9251     * The degrees that the view is rotated around the pivot point.
9252     *
9253     * @see #setRotation(float)
9254     * @see #getPivotX()
9255     * @see #getPivotY()
9256     *
9257     * @return The degrees of rotation.
9258     */
9259    @ViewDebug.ExportedProperty(category = "drawing")
9260    public float getRotation() {
9261        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9262    }
9263
9264    /**
9265     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9266     * result in clockwise rotation.
9267     *
9268     * @param rotation The degrees of rotation.
9269     *
9270     * @see #getRotation()
9271     * @see #getPivotX()
9272     * @see #getPivotY()
9273     * @see #setRotationX(float)
9274     * @see #setRotationY(float)
9275     *
9276     * @attr ref android.R.styleable#View_rotation
9277     */
9278    public void setRotation(float rotation) {
9279        ensureTransformationInfo();
9280        final TransformationInfo info = mTransformationInfo;
9281        if (info.mRotation != rotation) {
9282            // Double-invalidation is necessary to capture view's old and new areas
9283            invalidateViewProperty(true, false);
9284            info.mRotation = rotation;
9285            info.mMatrixDirty = true;
9286            invalidateViewProperty(false, true);
9287            if (mDisplayList != null) {
9288                mDisplayList.setRotation(rotation);
9289            }
9290            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9291                // View was rejected last time it was drawn by its parent; this may have changed
9292                invalidateParentIfNeeded();
9293            }
9294        }
9295    }
9296
9297    /**
9298     * The degrees that the view is rotated around the vertical axis through the pivot point.
9299     *
9300     * @see #getPivotX()
9301     * @see #getPivotY()
9302     * @see #setRotationY(float)
9303     *
9304     * @return The degrees of Y rotation.
9305     */
9306    @ViewDebug.ExportedProperty(category = "drawing")
9307    public float getRotationY() {
9308        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9309    }
9310
9311    /**
9312     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9313     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9314     * down the y axis.
9315     *
9316     * When rotating large views, it is recommended to adjust the camera distance
9317     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9318     *
9319     * @param rotationY The degrees of Y rotation.
9320     *
9321     * @see #getRotationY()
9322     * @see #getPivotX()
9323     * @see #getPivotY()
9324     * @see #setRotation(float)
9325     * @see #setRotationX(float)
9326     * @see #setCameraDistance(float)
9327     *
9328     * @attr ref android.R.styleable#View_rotationY
9329     */
9330    public void setRotationY(float rotationY) {
9331        ensureTransformationInfo();
9332        final TransformationInfo info = mTransformationInfo;
9333        if (info.mRotationY != rotationY) {
9334            invalidateViewProperty(true, false);
9335            info.mRotationY = rotationY;
9336            info.mMatrixDirty = true;
9337            invalidateViewProperty(false, true);
9338            if (mDisplayList != null) {
9339                mDisplayList.setRotationY(rotationY);
9340            }
9341            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9342                // View was rejected last time it was drawn by its parent; this may have changed
9343                invalidateParentIfNeeded();
9344            }
9345        }
9346    }
9347
9348    /**
9349     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9350     *
9351     * @see #getPivotX()
9352     * @see #getPivotY()
9353     * @see #setRotationX(float)
9354     *
9355     * @return The degrees of X rotation.
9356     */
9357    @ViewDebug.ExportedProperty(category = "drawing")
9358    public float getRotationX() {
9359        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9360    }
9361
9362    /**
9363     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9364     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9365     * x axis.
9366     *
9367     * When rotating large views, it is recommended to adjust the camera distance
9368     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9369     *
9370     * @param rotationX The degrees of X rotation.
9371     *
9372     * @see #getRotationX()
9373     * @see #getPivotX()
9374     * @see #getPivotY()
9375     * @see #setRotation(float)
9376     * @see #setRotationY(float)
9377     * @see #setCameraDistance(float)
9378     *
9379     * @attr ref android.R.styleable#View_rotationX
9380     */
9381    public void setRotationX(float rotationX) {
9382        ensureTransformationInfo();
9383        final TransformationInfo info = mTransformationInfo;
9384        if (info.mRotationX != rotationX) {
9385            invalidateViewProperty(true, false);
9386            info.mRotationX = rotationX;
9387            info.mMatrixDirty = true;
9388            invalidateViewProperty(false, true);
9389            if (mDisplayList != null) {
9390                mDisplayList.setRotationX(rotationX);
9391            }
9392            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9393                // View was rejected last time it was drawn by its parent; this may have changed
9394                invalidateParentIfNeeded();
9395            }
9396        }
9397    }
9398
9399    /**
9400     * The amount that the view is scaled in x around the pivot point, as a proportion of
9401     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9402     *
9403     * <p>By default, this is 1.0f.
9404     *
9405     * @see #getPivotX()
9406     * @see #getPivotY()
9407     * @return The scaling factor.
9408     */
9409    @ViewDebug.ExportedProperty(category = "drawing")
9410    public float getScaleX() {
9411        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9412    }
9413
9414    /**
9415     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9416     * the view's unscaled width. A value of 1 means that no scaling is applied.
9417     *
9418     * @param scaleX The scaling factor.
9419     * @see #getPivotX()
9420     * @see #getPivotY()
9421     *
9422     * @attr ref android.R.styleable#View_scaleX
9423     */
9424    public void setScaleX(float scaleX) {
9425        ensureTransformationInfo();
9426        final TransformationInfo info = mTransformationInfo;
9427        if (info.mScaleX != scaleX) {
9428            invalidateViewProperty(true, false);
9429            info.mScaleX = scaleX;
9430            info.mMatrixDirty = true;
9431            invalidateViewProperty(false, true);
9432            if (mDisplayList != null) {
9433                mDisplayList.setScaleX(scaleX);
9434            }
9435            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9436                // View was rejected last time it was drawn by its parent; this may have changed
9437                invalidateParentIfNeeded();
9438            }
9439        }
9440    }
9441
9442    /**
9443     * The amount that the view is scaled in y around the pivot point, as a proportion of
9444     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9445     *
9446     * <p>By default, this is 1.0f.
9447     *
9448     * @see #getPivotX()
9449     * @see #getPivotY()
9450     * @return The scaling factor.
9451     */
9452    @ViewDebug.ExportedProperty(category = "drawing")
9453    public float getScaleY() {
9454        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9455    }
9456
9457    /**
9458     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9459     * the view's unscaled width. A value of 1 means that no scaling is applied.
9460     *
9461     * @param scaleY The scaling factor.
9462     * @see #getPivotX()
9463     * @see #getPivotY()
9464     *
9465     * @attr ref android.R.styleable#View_scaleY
9466     */
9467    public void setScaleY(float scaleY) {
9468        ensureTransformationInfo();
9469        final TransformationInfo info = mTransformationInfo;
9470        if (info.mScaleY != scaleY) {
9471            invalidateViewProperty(true, false);
9472            info.mScaleY = scaleY;
9473            info.mMatrixDirty = true;
9474            invalidateViewProperty(false, true);
9475            if (mDisplayList != null) {
9476                mDisplayList.setScaleY(scaleY);
9477            }
9478            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9479                // View was rejected last time it was drawn by its parent; this may have changed
9480                invalidateParentIfNeeded();
9481            }
9482        }
9483    }
9484
9485    /**
9486     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9487     * and {@link #setScaleX(float) scaled}.
9488     *
9489     * @see #getRotation()
9490     * @see #getScaleX()
9491     * @see #getScaleY()
9492     * @see #getPivotY()
9493     * @return The x location of the pivot point.
9494     *
9495     * @attr ref android.R.styleable#View_transformPivotX
9496     */
9497    @ViewDebug.ExportedProperty(category = "drawing")
9498    public float getPivotX() {
9499        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9500    }
9501
9502    /**
9503     * Sets the x location of the point around which the view is
9504     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9505     * By default, the pivot point is centered on the object.
9506     * Setting this property disables this behavior and causes the view to use only the
9507     * explicitly set pivotX and pivotY values.
9508     *
9509     * @param pivotX The x location of the pivot point.
9510     * @see #getRotation()
9511     * @see #getScaleX()
9512     * @see #getScaleY()
9513     * @see #getPivotY()
9514     *
9515     * @attr ref android.R.styleable#View_transformPivotX
9516     */
9517    public void setPivotX(float pivotX) {
9518        ensureTransformationInfo();
9519        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9520        final TransformationInfo info = mTransformationInfo;
9521        if (info.mPivotX != pivotX) {
9522            invalidateViewProperty(true, false);
9523            info.mPivotX = pivotX;
9524            info.mMatrixDirty = true;
9525            invalidateViewProperty(false, true);
9526            if (mDisplayList != null) {
9527                mDisplayList.setPivotX(pivotX);
9528            }
9529            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9530                // View was rejected last time it was drawn by its parent; this may have changed
9531                invalidateParentIfNeeded();
9532            }
9533        }
9534    }
9535
9536    /**
9537     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9538     * and {@link #setScaleY(float) scaled}.
9539     *
9540     * @see #getRotation()
9541     * @see #getScaleX()
9542     * @see #getScaleY()
9543     * @see #getPivotY()
9544     * @return The y location of the pivot point.
9545     *
9546     * @attr ref android.R.styleable#View_transformPivotY
9547     */
9548    @ViewDebug.ExportedProperty(category = "drawing")
9549    public float getPivotY() {
9550        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9551    }
9552
9553    /**
9554     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9555     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9556     * Setting this property disables this behavior and causes the view to use only the
9557     * explicitly set pivotX and pivotY values.
9558     *
9559     * @param pivotY The y location of the pivot point.
9560     * @see #getRotation()
9561     * @see #getScaleX()
9562     * @see #getScaleY()
9563     * @see #getPivotY()
9564     *
9565     * @attr ref android.R.styleable#View_transformPivotY
9566     */
9567    public void setPivotY(float pivotY) {
9568        ensureTransformationInfo();
9569        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9570        final TransformationInfo info = mTransformationInfo;
9571        if (info.mPivotY != pivotY) {
9572            invalidateViewProperty(true, false);
9573            info.mPivotY = pivotY;
9574            info.mMatrixDirty = true;
9575            invalidateViewProperty(false, true);
9576            if (mDisplayList != null) {
9577                mDisplayList.setPivotY(pivotY);
9578            }
9579            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9580                // View was rejected last time it was drawn by its parent; this may have changed
9581                invalidateParentIfNeeded();
9582            }
9583        }
9584    }
9585
9586    /**
9587     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9588     * completely transparent and 1 means the view is completely opaque.
9589     *
9590     * <p>By default this is 1.0f.
9591     * @return The opacity of the view.
9592     */
9593    @ViewDebug.ExportedProperty(category = "drawing")
9594    public float getAlpha() {
9595        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9596    }
9597
9598    /**
9599     * Returns whether this View has content which overlaps. This function, intended to be
9600     * overridden by specific View types, is an optimization when alpha is set on a view. If
9601     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9602     * and then composited it into place, which can be expensive. If the view has no overlapping
9603     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9604     * An example of overlapping rendering is a TextView with a background image, such as a
9605     * Button. An example of non-overlapping rendering is a TextView with no background, or
9606     * an ImageView with only the foreground image. The default implementation returns true;
9607     * subclasses should override if they have cases which can be optimized.
9608     *
9609     * @return true if the content in this view might overlap, false otherwise.
9610     */
9611    public boolean hasOverlappingRendering() {
9612        return true;
9613    }
9614
9615    /**
9616     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9617     * completely transparent and 1 means the view is completely opaque.</p>
9618     *
9619     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9620     * performance implications, especially for large views. It is best to use the alpha property
9621     * sparingly and transiently, as in the case of fading animations.</p>
9622     *
9623     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9624     * strongly recommended for performance reasons to either override
9625     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9626     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9627     *
9628     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9629     * responsible for applying the opacity itself.</p>
9630     *
9631     * <p>Note that if the view is backed by a
9632     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9633     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9634     * 1.0 will supercede the alpha of the layer paint.</p>
9635     *
9636     * @param alpha The opacity of the view.
9637     *
9638     * @see #hasOverlappingRendering()
9639     * @see #setLayerType(int, android.graphics.Paint)
9640     *
9641     * @attr ref android.R.styleable#View_alpha
9642     */
9643    public void setAlpha(float alpha) {
9644        ensureTransformationInfo();
9645        if (mTransformationInfo.mAlpha != alpha) {
9646            mTransformationInfo.mAlpha = alpha;
9647            if (onSetAlpha((int) (alpha * 255))) {
9648                mPrivateFlags |= PFLAG_ALPHA_SET;
9649                // subclass is handling alpha - don't optimize rendering cache invalidation
9650                invalidateParentCaches();
9651                invalidate(true);
9652            } else {
9653                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9654                invalidateViewProperty(true, false);
9655                if (mDisplayList != null) {
9656                    mDisplayList.setAlpha(alpha);
9657                }
9658            }
9659        }
9660    }
9661
9662    /**
9663     * Faster version of setAlpha() which performs the same steps except there are
9664     * no calls to invalidate(). The caller of this function should perform proper invalidation
9665     * on the parent and this object. The return value indicates whether the subclass handles
9666     * alpha (the return value for onSetAlpha()).
9667     *
9668     * @param alpha The new value for the alpha property
9669     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9670     *         the new value for the alpha property is different from the old value
9671     */
9672    boolean setAlphaNoInvalidation(float alpha) {
9673        ensureTransformationInfo();
9674        if (mTransformationInfo.mAlpha != alpha) {
9675            mTransformationInfo.mAlpha = alpha;
9676            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9677            if (subclassHandlesAlpha) {
9678                mPrivateFlags |= PFLAG_ALPHA_SET;
9679                return true;
9680            } else {
9681                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9682                if (mDisplayList != null) {
9683                    mDisplayList.setAlpha(alpha);
9684                }
9685            }
9686        }
9687        return false;
9688    }
9689
9690    /**
9691     * Top position of this view relative to its parent.
9692     *
9693     * @return The top of this view, in pixels.
9694     */
9695    @ViewDebug.CapturedViewProperty
9696    public final int getTop() {
9697        return mTop;
9698    }
9699
9700    /**
9701     * Sets the top position of this view relative to its parent. This method is meant to be called
9702     * by the layout system and should not generally be called otherwise, because the property
9703     * may be changed at any time by the layout.
9704     *
9705     * @param top The top of this view, in pixels.
9706     */
9707    public final void setTop(int top) {
9708        if (top != mTop) {
9709            updateMatrix();
9710            final boolean matrixIsIdentity = mTransformationInfo == null
9711                    || mTransformationInfo.mMatrixIsIdentity;
9712            if (matrixIsIdentity) {
9713                if (mAttachInfo != null) {
9714                    int minTop;
9715                    int yLoc;
9716                    if (top < mTop) {
9717                        minTop = top;
9718                        yLoc = top - mTop;
9719                    } else {
9720                        minTop = mTop;
9721                        yLoc = 0;
9722                    }
9723                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9724                }
9725            } else {
9726                // Double-invalidation is necessary to capture view's old and new areas
9727                invalidate(true);
9728            }
9729
9730            int width = mRight - mLeft;
9731            int oldHeight = mBottom - mTop;
9732
9733            mTop = top;
9734            if (mDisplayList != null) {
9735                mDisplayList.setTop(mTop);
9736            }
9737
9738            sizeChange(width, mBottom - mTop, width, oldHeight);
9739
9740            if (!matrixIsIdentity) {
9741                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9742                    // A change in dimension means an auto-centered pivot point changes, too
9743                    mTransformationInfo.mMatrixDirty = true;
9744                }
9745                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9746                invalidate(true);
9747            }
9748            mBackgroundSizeChanged = true;
9749            invalidateParentIfNeeded();
9750            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9751                // View was rejected last time it was drawn by its parent; this may have changed
9752                invalidateParentIfNeeded();
9753            }
9754        }
9755    }
9756
9757    /**
9758     * Bottom position of this view relative to its parent.
9759     *
9760     * @return The bottom of this view, in pixels.
9761     */
9762    @ViewDebug.CapturedViewProperty
9763    public final int getBottom() {
9764        return mBottom;
9765    }
9766
9767    /**
9768     * True if this view has changed since the last time being drawn.
9769     *
9770     * @return The dirty state of this view.
9771     */
9772    public boolean isDirty() {
9773        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9774    }
9775
9776    /**
9777     * Sets the bottom position of this view relative to its parent. This method is meant to be
9778     * called by the layout system and should not generally be called otherwise, because the
9779     * property may be changed at any time by the layout.
9780     *
9781     * @param bottom The bottom of this view, in pixels.
9782     */
9783    public final void setBottom(int bottom) {
9784        if (bottom != mBottom) {
9785            updateMatrix();
9786            final boolean matrixIsIdentity = mTransformationInfo == null
9787                    || mTransformationInfo.mMatrixIsIdentity;
9788            if (matrixIsIdentity) {
9789                if (mAttachInfo != null) {
9790                    int maxBottom;
9791                    if (bottom < mBottom) {
9792                        maxBottom = mBottom;
9793                    } else {
9794                        maxBottom = bottom;
9795                    }
9796                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9797                }
9798            } else {
9799                // Double-invalidation is necessary to capture view's old and new areas
9800                invalidate(true);
9801            }
9802
9803            int width = mRight - mLeft;
9804            int oldHeight = mBottom - mTop;
9805
9806            mBottom = bottom;
9807            if (mDisplayList != null) {
9808                mDisplayList.setBottom(mBottom);
9809            }
9810
9811            sizeChange(width, mBottom - mTop, width, oldHeight);
9812
9813            if (!matrixIsIdentity) {
9814                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9815                    // A change in dimension means an auto-centered pivot point changes, too
9816                    mTransformationInfo.mMatrixDirty = true;
9817                }
9818                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9819                invalidate(true);
9820            }
9821            mBackgroundSizeChanged = true;
9822            invalidateParentIfNeeded();
9823            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9824                // View was rejected last time it was drawn by its parent; this may have changed
9825                invalidateParentIfNeeded();
9826            }
9827        }
9828    }
9829
9830    /**
9831     * Left position of this view relative to its parent.
9832     *
9833     * @return The left edge of this view, in pixels.
9834     */
9835    @ViewDebug.CapturedViewProperty
9836    public final int getLeft() {
9837        return mLeft;
9838    }
9839
9840    /**
9841     * Sets the left position of this view relative to its parent. This method is meant to be called
9842     * by the layout system and should not generally be called otherwise, because the property
9843     * may be changed at any time by the layout.
9844     *
9845     * @param left The bottom of this view, in pixels.
9846     */
9847    public final void setLeft(int left) {
9848        if (left != mLeft) {
9849            updateMatrix();
9850            final boolean matrixIsIdentity = mTransformationInfo == null
9851                    || mTransformationInfo.mMatrixIsIdentity;
9852            if (matrixIsIdentity) {
9853                if (mAttachInfo != null) {
9854                    int minLeft;
9855                    int xLoc;
9856                    if (left < mLeft) {
9857                        minLeft = left;
9858                        xLoc = left - mLeft;
9859                    } else {
9860                        minLeft = mLeft;
9861                        xLoc = 0;
9862                    }
9863                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9864                }
9865            } else {
9866                // Double-invalidation is necessary to capture view's old and new areas
9867                invalidate(true);
9868            }
9869
9870            int oldWidth = mRight - mLeft;
9871            int height = mBottom - mTop;
9872
9873            mLeft = left;
9874            if (mDisplayList != null) {
9875                mDisplayList.setLeft(left);
9876            }
9877
9878            sizeChange(mRight - mLeft, height, oldWidth, height);
9879
9880            if (!matrixIsIdentity) {
9881                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9882                    // A change in dimension means an auto-centered pivot point changes, too
9883                    mTransformationInfo.mMatrixDirty = true;
9884                }
9885                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9886                invalidate(true);
9887            }
9888            mBackgroundSizeChanged = true;
9889            invalidateParentIfNeeded();
9890            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9891                // View was rejected last time it was drawn by its parent; this may have changed
9892                invalidateParentIfNeeded();
9893            }
9894        }
9895    }
9896
9897    /**
9898     * Right position of this view relative to its parent.
9899     *
9900     * @return The right edge of this view, in pixels.
9901     */
9902    @ViewDebug.CapturedViewProperty
9903    public final int getRight() {
9904        return mRight;
9905    }
9906
9907    /**
9908     * Sets the right position of this view relative to its parent. This method is meant to be called
9909     * by the layout system and should not generally be called otherwise, because the property
9910     * may be changed at any time by the layout.
9911     *
9912     * @param right The bottom of this view, in pixels.
9913     */
9914    public final void setRight(int right) {
9915        if (right != mRight) {
9916            updateMatrix();
9917            final boolean matrixIsIdentity = mTransformationInfo == null
9918                    || mTransformationInfo.mMatrixIsIdentity;
9919            if (matrixIsIdentity) {
9920                if (mAttachInfo != null) {
9921                    int maxRight;
9922                    if (right < mRight) {
9923                        maxRight = mRight;
9924                    } else {
9925                        maxRight = right;
9926                    }
9927                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9928                }
9929            } else {
9930                // Double-invalidation is necessary to capture view's old and new areas
9931                invalidate(true);
9932            }
9933
9934            int oldWidth = mRight - mLeft;
9935            int height = mBottom - mTop;
9936
9937            mRight = right;
9938            if (mDisplayList != null) {
9939                mDisplayList.setRight(mRight);
9940            }
9941
9942            sizeChange(mRight - mLeft, height, oldWidth, height);
9943
9944            if (!matrixIsIdentity) {
9945                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9946                    // A change in dimension means an auto-centered pivot point changes, too
9947                    mTransformationInfo.mMatrixDirty = true;
9948                }
9949                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9950                invalidate(true);
9951            }
9952            mBackgroundSizeChanged = true;
9953            invalidateParentIfNeeded();
9954            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9955                // View was rejected last time it was drawn by its parent; this may have changed
9956                invalidateParentIfNeeded();
9957            }
9958        }
9959    }
9960
9961    /**
9962     * The visual x position of this view, in pixels. This is equivalent to the
9963     * {@link #setTranslationX(float) translationX} property plus the current
9964     * {@link #getLeft() left} property.
9965     *
9966     * @return The visual x position of this view, in pixels.
9967     */
9968    @ViewDebug.ExportedProperty(category = "drawing")
9969    public float getX() {
9970        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9971    }
9972
9973    /**
9974     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9975     * {@link #setTranslationX(float) translationX} property to be the difference between
9976     * the x value passed in and the current {@link #getLeft() left} property.
9977     *
9978     * @param x The visual x position of this view, in pixels.
9979     */
9980    public void setX(float x) {
9981        setTranslationX(x - mLeft);
9982    }
9983
9984    /**
9985     * The visual y position of this view, in pixels. This is equivalent to the
9986     * {@link #setTranslationY(float) translationY} property plus the current
9987     * {@link #getTop() top} property.
9988     *
9989     * @return The visual y position of this view, in pixels.
9990     */
9991    @ViewDebug.ExportedProperty(category = "drawing")
9992    public float getY() {
9993        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9994    }
9995
9996    /**
9997     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9998     * {@link #setTranslationY(float) translationY} property to be the difference between
9999     * the y value passed in and the current {@link #getTop() top} property.
10000     *
10001     * @param y The visual y position of this view, in pixels.
10002     */
10003    public void setY(float y) {
10004        setTranslationY(y - mTop);
10005    }
10006
10007
10008    /**
10009     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10010     * This position is post-layout, in addition to wherever the object's
10011     * layout placed it.
10012     *
10013     * @return The horizontal position of this view relative to its left position, in pixels.
10014     */
10015    @ViewDebug.ExportedProperty(category = "drawing")
10016    public float getTranslationX() {
10017        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10018    }
10019
10020    /**
10021     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10022     * This effectively positions the object post-layout, in addition to wherever the object's
10023     * layout placed it.
10024     *
10025     * @param translationX The horizontal position of this view relative to its left position,
10026     * in pixels.
10027     *
10028     * @attr ref android.R.styleable#View_translationX
10029     */
10030    public void setTranslationX(float translationX) {
10031        ensureTransformationInfo();
10032        final TransformationInfo info = mTransformationInfo;
10033        if (info.mTranslationX != translationX) {
10034            // Double-invalidation is necessary to capture view's old and new areas
10035            invalidateViewProperty(true, false);
10036            info.mTranslationX = translationX;
10037            info.mMatrixDirty = true;
10038            invalidateViewProperty(false, true);
10039            if (mDisplayList != null) {
10040                mDisplayList.setTranslationX(translationX);
10041            }
10042            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10043                // View was rejected last time it was drawn by its parent; this may have changed
10044                invalidateParentIfNeeded();
10045            }
10046        }
10047    }
10048
10049    /**
10050     * The horizontal location of this view relative to its {@link #getTop() top} position.
10051     * This position is post-layout, in addition to wherever the object's
10052     * layout placed it.
10053     *
10054     * @return The vertical position of this view relative to its top position,
10055     * in pixels.
10056     */
10057    @ViewDebug.ExportedProperty(category = "drawing")
10058    public float getTranslationY() {
10059        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10060    }
10061
10062    /**
10063     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10064     * This effectively positions the object post-layout, in addition to wherever the object's
10065     * layout placed it.
10066     *
10067     * @param translationY The vertical position of this view relative to its top position,
10068     * in pixels.
10069     *
10070     * @attr ref android.R.styleable#View_translationY
10071     */
10072    public void setTranslationY(float translationY) {
10073        ensureTransformationInfo();
10074        final TransformationInfo info = mTransformationInfo;
10075        if (info.mTranslationY != translationY) {
10076            invalidateViewProperty(true, false);
10077            info.mTranslationY = translationY;
10078            info.mMatrixDirty = true;
10079            invalidateViewProperty(false, true);
10080            if (mDisplayList != null) {
10081                mDisplayList.setTranslationY(translationY);
10082            }
10083            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10084                // View was rejected last time it was drawn by its parent; this may have changed
10085                invalidateParentIfNeeded();
10086            }
10087        }
10088    }
10089
10090    /**
10091     * Hit rectangle in parent's coordinates
10092     *
10093     * @param outRect The hit rectangle of the view.
10094     */
10095    public void getHitRect(Rect outRect) {
10096        updateMatrix();
10097        final TransformationInfo info = mTransformationInfo;
10098        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10099            outRect.set(mLeft, mTop, mRight, mBottom);
10100        } else {
10101            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10102            tmpRect.set(0, 0, getWidth(), getHeight());
10103            info.mMatrix.mapRect(tmpRect);
10104            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10105                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10106        }
10107    }
10108
10109    /**
10110     * Determines whether the given point, in local coordinates is inside the view.
10111     */
10112    /*package*/ final boolean pointInView(float localX, float localY) {
10113        return localX >= 0 && localX < (mRight - mLeft)
10114                && localY >= 0 && localY < (mBottom - mTop);
10115    }
10116
10117    /**
10118     * Utility method to determine whether the given point, in local coordinates,
10119     * is inside the view, where the area of the view is expanded by the slop factor.
10120     * This method is called while processing touch-move events to determine if the event
10121     * is still within the view.
10122     *
10123     * @hide
10124     */
10125    public boolean pointInView(float localX, float localY, float slop) {
10126        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10127                localY < ((mBottom - mTop) + slop);
10128    }
10129
10130    /**
10131     * When a view has focus and the user navigates away from it, the next view is searched for
10132     * starting from the rectangle filled in by this method.
10133     *
10134     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10135     * of the view.  However, if your view maintains some idea of internal selection,
10136     * such as a cursor, or a selected row or column, you should override this method and
10137     * fill in a more specific rectangle.
10138     *
10139     * @param r The rectangle to fill in, in this view's coordinates.
10140     */
10141    public void getFocusedRect(Rect r) {
10142        getDrawingRect(r);
10143    }
10144
10145    /**
10146     * If some part of this view is not clipped by any of its parents, then
10147     * return that area in r in global (root) coordinates. To convert r to local
10148     * coordinates (without taking possible View rotations into account), offset
10149     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10150     * If the view is completely clipped or translated out, return false.
10151     *
10152     * @param r If true is returned, r holds the global coordinates of the
10153     *        visible portion of this view.
10154     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10155     *        between this view and its root. globalOffet may be null.
10156     * @return true if r is non-empty (i.e. part of the view is visible at the
10157     *         root level.
10158     */
10159    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10160        int width = mRight - mLeft;
10161        int height = mBottom - mTop;
10162        if (width > 0 && height > 0) {
10163            r.set(0, 0, width, height);
10164            if (globalOffset != null) {
10165                globalOffset.set(-mScrollX, -mScrollY);
10166            }
10167            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10168        }
10169        return false;
10170    }
10171
10172    public final boolean getGlobalVisibleRect(Rect r) {
10173        return getGlobalVisibleRect(r, null);
10174    }
10175
10176    public final boolean getLocalVisibleRect(Rect r) {
10177        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10178        if (getGlobalVisibleRect(r, offset)) {
10179            r.offset(-offset.x, -offset.y); // make r local
10180            return true;
10181        }
10182        return false;
10183    }
10184
10185    /**
10186     * Offset this view's vertical location by the specified number of pixels.
10187     *
10188     * @param offset the number of pixels to offset the view by
10189     */
10190    public void offsetTopAndBottom(int offset) {
10191        if (offset != 0) {
10192            updateMatrix();
10193            final boolean matrixIsIdentity = mTransformationInfo == null
10194                    || mTransformationInfo.mMatrixIsIdentity;
10195            if (matrixIsIdentity) {
10196                if (mDisplayList != null) {
10197                    invalidateViewProperty(false, false);
10198                } else {
10199                    final ViewParent p = mParent;
10200                    if (p != null && mAttachInfo != null) {
10201                        final Rect r = mAttachInfo.mTmpInvalRect;
10202                        int minTop;
10203                        int maxBottom;
10204                        int yLoc;
10205                        if (offset < 0) {
10206                            minTop = mTop + offset;
10207                            maxBottom = mBottom;
10208                            yLoc = offset;
10209                        } else {
10210                            minTop = mTop;
10211                            maxBottom = mBottom + offset;
10212                            yLoc = 0;
10213                        }
10214                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10215                        p.invalidateChild(this, r);
10216                    }
10217                }
10218            } else {
10219                invalidateViewProperty(false, false);
10220            }
10221
10222            mTop += offset;
10223            mBottom += offset;
10224            if (mDisplayList != null) {
10225                mDisplayList.offsetTopAndBottom(offset);
10226                invalidateViewProperty(false, false);
10227            } else {
10228                if (!matrixIsIdentity) {
10229                    invalidateViewProperty(false, true);
10230                }
10231                invalidateParentIfNeeded();
10232            }
10233        }
10234    }
10235
10236    /**
10237     * Offset this view's horizontal location by the specified amount of pixels.
10238     *
10239     * @param offset the number of pixels to offset the view by
10240     */
10241    public void offsetLeftAndRight(int offset) {
10242        if (offset != 0) {
10243            updateMatrix();
10244            final boolean matrixIsIdentity = mTransformationInfo == null
10245                    || mTransformationInfo.mMatrixIsIdentity;
10246            if (matrixIsIdentity) {
10247                if (mDisplayList != null) {
10248                    invalidateViewProperty(false, false);
10249                } else {
10250                    final ViewParent p = mParent;
10251                    if (p != null && mAttachInfo != null) {
10252                        final Rect r = mAttachInfo.mTmpInvalRect;
10253                        int minLeft;
10254                        int maxRight;
10255                        if (offset < 0) {
10256                            minLeft = mLeft + offset;
10257                            maxRight = mRight;
10258                        } else {
10259                            minLeft = mLeft;
10260                            maxRight = mRight + offset;
10261                        }
10262                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10263                        p.invalidateChild(this, r);
10264                    }
10265                }
10266            } else {
10267                invalidateViewProperty(false, false);
10268            }
10269
10270            mLeft += offset;
10271            mRight += offset;
10272            if (mDisplayList != null) {
10273                mDisplayList.offsetLeftAndRight(offset);
10274                invalidateViewProperty(false, false);
10275            } else {
10276                if (!matrixIsIdentity) {
10277                    invalidateViewProperty(false, true);
10278                }
10279                invalidateParentIfNeeded();
10280            }
10281        }
10282    }
10283
10284    /**
10285     * Get the LayoutParams associated with this view. All views should have
10286     * layout parameters. These supply parameters to the <i>parent</i> of this
10287     * view specifying how it should be arranged. There are many subclasses of
10288     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10289     * of ViewGroup that are responsible for arranging their children.
10290     *
10291     * This method may return null if this View is not attached to a parent
10292     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10293     * was not invoked successfully. When a View is attached to a parent
10294     * ViewGroup, this method must not return null.
10295     *
10296     * @return The LayoutParams associated with this view, or null if no
10297     *         parameters have been set yet
10298     */
10299    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10300    public ViewGroup.LayoutParams getLayoutParams() {
10301        return mLayoutParams;
10302    }
10303
10304    /**
10305     * Set the layout parameters associated with this view. These supply
10306     * parameters to the <i>parent</i> of this view specifying how it should be
10307     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10308     * correspond to the different subclasses of ViewGroup that are responsible
10309     * for arranging their children.
10310     *
10311     * @param params The layout parameters for this view, cannot be null
10312     */
10313    public void setLayoutParams(ViewGroup.LayoutParams params) {
10314        if (params == null) {
10315            throw new NullPointerException("Layout parameters cannot be null");
10316        }
10317        mLayoutParams = params;
10318        resolveLayoutParams();
10319        if (mParent instanceof ViewGroup) {
10320            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10321        }
10322        requestLayout();
10323    }
10324
10325    /**
10326     * Resolve the layout parameters depending on the resolved layout direction
10327     *
10328     * @hide
10329     */
10330    public void resolveLayoutParams() {
10331        if (mLayoutParams != null) {
10332            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10333        }
10334    }
10335
10336    /**
10337     * Set the scrolled position of your view. This will cause a call to
10338     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10339     * invalidated.
10340     * @param x the x position to scroll to
10341     * @param y the y position to scroll to
10342     */
10343    public void scrollTo(int x, int y) {
10344        if (mScrollX != x || mScrollY != y) {
10345            int oldX = mScrollX;
10346            int oldY = mScrollY;
10347            mScrollX = x;
10348            mScrollY = y;
10349            invalidateParentCaches();
10350            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10351            if (!awakenScrollBars()) {
10352                postInvalidateOnAnimation();
10353            }
10354        }
10355    }
10356
10357    /**
10358     * Move the scrolled position of your view. This will cause a call to
10359     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10360     * invalidated.
10361     * @param x the amount of pixels to scroll by horizontally
10362     * @param y the amount of pixels to scroll by vertically
10363     */
10364    public void scrollBy(int x, int y) {
10365        scrollTo(mScrollX + x, mScrollY + y);
10366    }
10367
10368    /**
10369     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10370     * animation to fade the scrollbars out after a default delay. If a subclass
10371     * provides animated scrolling, the start delay should equal the duration
10372     * of the scrolling animation.</p>
10373     *
10374     * <p>The animation starts only if at least one of the scrollbars is
10375     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10376     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10377     * this method returns true, and false otherwise. If the animation is
10378     * started, this method calls {@link #invalidate()}; in that case the
10379     * caller should not call {@link #invalidate()}.</p>
10380     *
10381     * <p>This method should be invoked every time a subclass directly updates
10382     * the scroll parameters.</p>
10383     *
10384     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10385     * and {@link #scrollTo(int, int)}.</p>
10386     *
10387     * @return true if the animation is played, false otherwise
10388     *
10389     * @see #awakenScrollBars(int)
10390     * @see #scrollBy(int, int)
10391     * @see #scrollTo(int, int)
10392     * @see #isHorizontalScrollBarEnabled()
10393     * @see #isVerticalScrollBarEnabled()
10394     * @see #setHorizontalScrollBarEnabled(boolean)
10395     * @see #setVerticalScrollBarEnabled(boolean)
10396     */
10397    protected boolean awakenScrollBars() {
10398        return mScrollCache != null &&
10399                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10400    }
10401
10402    /**
10403     * Trigger the scrollbars to draw.
10404     * This method differs from awakenScrollBars() only in its default duration.
10405     * initialAwakenScrollBars() will show the scroll bars for longer than
10406     * usual to give the user more of a chance to notice them.
10407     *
10408     * @return true if the animation is played, false otherwise.
10409     */
10410    private boolean initialAwakenScrollBars() {
10411        return mScrollCache != null &&
10412                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10413    }
10414
10415    /**
10416     * <p>
10417     * Trigger the scrollbars to draw. When invoked this method starts an
10418     * animation to fade the scrollbars out after a fixed delay. If a subclass
10419     * provides animated scrolling, the start delay should equal the duration of
10420     * the scrolling animation.
10421     * </p>
10422     *
10423     * <p>
10424     * The animation starts only if at least one of the scrollbars is enabled,
10425     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10426     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10427     * this method returns true, and false otherwise. If the animation is
10428     * started, this method calls {@link #invalidate()}; in that case the caller
10429     * should not call {@link #invalidate()}.
10430     * </p>
10431     *
10432     * <p>
10433     * This method should be invoked everytime a subclass directly updates the
10434     * scroll parameters.
10435     * </p>
10436     *
10437     * @param startDelay the delay, in milliseconds, after which the animation
10438     *        should start; when the delay is 0, the animation starts
10439     *        immediately
10440     * @return true if the animation is played, false otherwise
10441     *
10442     * @see #scrollBy(int, int)
10443     * @see #scrollTo(int, int)
10444     * @see #isHorizontalScrollBarEnabled()
10445     * @see #isVerticalScrollBarEnabled()
10446     * @see #setHorizontalScrollBarEnabled(boolean)
10447     * @see #setVerticalScrollBarEnabled(boolean)
10448     */
10449    protected boolean awakenScrollBars(int startDelay) {
10450        return awakenScrollBars(startDelay, true);
10451    }
10452
10453    /**
10454     * <p>
10455     * Trigger the scrollbars to draw. When invoked this method starts an
10456     * animation to fade the scrollbars out after a fixed delay. If a subclass
10457     * provides animated scrolling, the start delay should equal the duration of
10458     * the scrolling animation.
10459     * </p>
10460     *
10461     * <p>
10462     * The animation starts only if at least one of the scrollbars is enabled,
10463     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10464     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10465     * this method returns true, and false otherwise. If the animation is
10466     * started, this method calls {@link #invalidate()} if the invalidate parameter
10467     * is set to true; in that case the caller
10468     * should not call {@link #invalidate()}.
10469     * </p>
10470     *
10471     * <p>
10472     * This method should be invoked everytime a subclass directly updates the
10473     * scroll parameters.
10474     * </p>
10475     *
10476     * @param startDelay the delay, in milliseconds, after which the animation
10477     *        should start; when the delay is 0, the animation starts
10478     *        immediately
10479     *
10480     * @param invalidate Wheter this method should call invalidate
10481     *
10482     * @return true if the animation is played, false otherwise
10483     *
10484     * @see #scrollBy(int, int)
10485     * @see #scrollTo(int, int)
10486     * @see #isHorizontalScrollBarEnabled()
10487     * @see #isVerticalScrollBarEnabled()
10488     * @see #setHorizontalScrollBarEnabled(boolean)
10489     * @see #setVerticalScrollBarEnabled(boolean)
10490     */
10491    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10492        final ScrollabilityCache scrollCache = mScrollCache;
10493
10494        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10495            return false;
10496        }
10497
10498        if (scrollCache.scrollBar == null) {
10499            scrollCache.scrollBar = new ScrollBarDrawable();
10500        }
10501
10502        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10503
10504            if (invalidate) {
10505                // Invalidate to show the scrollbars
10506                postInvalidateOnAnimation();
10507            }
10508
10509            if (scrollCache.state == ScrollabilityCache.OFF) {
10510                // FIXME: this is copied from WindowManagerService.
10511                // We should get this value from the system when it
10512                // is possible to do so.
10513                final int KEY_REPEAT_FIRST_DELAY = 750;
10514                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10515            }
10516
10517            // Tell mScrollCache when we should start fading. This may
10518            // extend the fade start time if one was already scheduled
10519            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10520            scrollCache.fadeStartTime = fadeStartTime;
10521            scrollCache.state = ScrollabilityCache.ON;
10522
10523            // Schedule our fader to run, unscheduling any old ones first
10524            if (mAttachInfo != null) {
10525                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10526                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10527            }
10528
10529            return true;
10530        }
10531
10532        return false;
10533    }
10534
10535    /**
10536     * Do not invalidate views which are not visible and which are not running an animation. They
10537     * will not get drawn and they should not set dirty flags as if they will be drawn
10538     */
10539    private boolean skipInvalidate() {
10540        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10541                (!(mParent instanceof ViewGroup) ||
10542                        !((ViewGroup) mParent).isViewTransitioning(this));
10543    }
10544    /**
10545     * Mark the area defined by dirty as needing to be drawn. If the view is
10546     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10547     * in the future. This must be called from a UI thread. To call from a non-UI
10548     * thread, call {@link #postInvalidate()}.
10549     *
10550     * WARNING: This method is destructive to dirty.
10551     * @param dirty the rectangle representing the bounds of the dirty region
10552     */
10553    public void invalidate(Rect dirty) {
10554        if (skipInvalidate()) {
10555            return;
10556        }
10557        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10558                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10559                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10560            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10561            mPrivateFlags |= PFLAG_INVALIDATED;
10562            mPrivateFlags |= PFLAG_DIRTY;
10563            final ViewParent p = mParent;
10564            final AttachInfo ai = mAttachInfo;
10565            //noinspection PointlessBooleanExpression,ConstantConditions
10566            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10567                if (p != null && ai != null && ai.mHardwareAccelerated) {
10568                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10569                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10570                    p.invalidateChild(this, null);
10571                    return;
10572                }
10573            }
10574            if (p != null && ai != null) {
10575                final int scrollX = mScrollX;
10576                final int scrollY = mScrollY;
10577                final Rect r = ai.mTmpInvalRect;
10578                r.set(dirty.left - scrollX, dirty.top - scrollY,
10579                        dirty.right - scrollX, dirty.bottom - scrollY);
10580                mParent.invalidateChild(this, r);
10581            }
10582        }
10583    }
10584
10585    /**
10586     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10587     * The coordinates of the dirty rect are relative to the view.
10588     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10589     * will be called at some point in the future. This must be called from
10590     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10591     * @param l the left position of the dirty region
10592     * @param t the top position of the dirty region
10593     * @param r the right position of the dirty region
10594     * @param b the bottom position of the dirty region
10595     */
10596    public void invalidate(int l, int t, int r, int b) {
10597        if (skipInvalidate()) {
10598            return;
10599        }
10600        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10601                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10602                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10603            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10604            mPrivateFlags |= PFLAG_INVALIDATED;
10605            mPrivateFlags |= PFLAG_DIRTY;
10606            final ViewParent p = mParent;
10607            final AttachInfo ai = mAttachInfo;
10608            //noinspection PointlessBooleanExpression,ConstantConditions
10609            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10610                if (p != null && ai != null && ai.mHardwareAccelerated) {
10611                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10612                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10613                    p.invalidateChild(this, null);
10614                    return;
10615                }
10616            }
10617            if (p != null && ai != null && l < r && t < b) {
10618                final int scrollX = mScrollX;
10619                final int scrollY = mScrollY;
10620                final Rect tmpr = ai.mTmpInvalRect;
10621                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10622                p.invalidateChild(this, tmpr);
10623            }
10624        }
10625    }
10626
10627    /**
10628     * Invalidate the whole view. If the view is visible,
10629     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10630     * the future. This must be called from a UI thread. To call from a non-UI thread,
10631     * call {@link #postInvalidate()}.
10632     */
10633    public void invalidate() {
10634        invalidate(true);
10635    }
10636
10637    /**
10638     * This is where the invalidate() work actually happens. A full invalidate()
10639     * causes the drawing cache to be invalidated, but this function can be called with
10640     * invalidateCache set to false to skip that invalidation step for cases that do not
10641     * need it (for example, a component that remains at the same dimensions with the same
10642     * content).
10643     *
10644     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10645     * well. This is usually true for a full invalidate, but may be set to false if the
10646     * View's contents or dimensions have not changed.
10647     */
10648    void invalidate(boolean invalidateCache) {
10649        if (skipInvalidate()) {
10650            return;
10651        }
10652        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10653                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10654                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10655            mLastIsOpaque = isOpaque();
10656            mPrivateFlags &= ~PFLAG_DRAWN;
10657            mPrivateFlags |= PFLAG_DIRTY;
10658            if (invalidateCache) {
10659                mPrivateFlags |= PFLAG_INVALIDATED;
10660                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10661            }
10662            final AttachInfo ai = mAttachInfo;
10663            final ViewParent p = mParent;
10664            //noinspection PointlessBooleanExpression,ConstantConditions
10665            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10666                if (p != null && ai != null && ai.mHardwareAccelerated) {
10667                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10668                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10669                    p.invalidateChild(this, null);
10670                    return;
10671                }
10672            }
10673
10674            if (p != null && ai != null) {
10675                final Rect r = ai.mTmpInvalRect;
10676                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10677                // Don't call invalidate -- we don't want to internally scroll
10678                // our own bounds
10679                p.invalidateChild(this, r);
10680            }
10681        }
10682    }
10683
10684    /**
10685     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10686     * set any flags or handle all of the cases handled by the default invalidation methods.
10687     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10688     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10689     * walk up the hierarchy, transforming the dirty rect as necessary.
10690     *
10691     * The method also handles normal invalidation logic if display list properties are not
10692     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10693     * backup approach, to handle these cases used in the various property-setting methods.
10694     *
10695     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10696     * are not being used in this view
10697     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10698     * list properties are not being used in this view
10699     */
10700    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10701        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10702            if (invalidateParent) {
10703                invalidateParentCaches();
10704            }
10705            if (forceRedraw) {
10706                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10707            }
10708            invalidate(false);
10709        } else {
10710            final AttachInfo ai = mAttachInfo;
10711            final ViewParent p = mParent;
10712            if (p != null && ai != null) {
10713                final Rect r = ai.mTmpInvalRect;
10714                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10715                if (mParent instanceof ViewGroup) {
10716                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10717                } else {
10718                    mParent.invalidateChild(this, r);
10719                }
10720            }
10721        }
10722    }
10723
10724    /**
10725     * Utility method to transform a given Rect by the current matrix of this view.
10726     */
10727    void transformRect(final Rect rect) {
10728        if (!getMatrix().isIdentity()) {
10729            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10730            boundingRect.set(rect);
10731            getMatrix().mapRect(boundingRect);
10732            rect.set((int) Math.floor(boundingRect.left),
10733                    (int) Math.floor(boundingRect.top),
10734                    (int) Math.ceil(boundingRect.right),
10735                    (int) Math.ceil(boundingRect.bottom));
10736        }
10737    }
10738
10739    /**
10740     * Used to indicate that the parent of this view should clear its caches. This functionality
10741     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10742     * which is necessary when various parent-managed properties of the view change, such as
10743     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10744     * clears the parent caches and does not causes an invalidate event.
10745     *
10746     * @hide
10747     */
10748    protected void invalidateParentCaches() {
10749        if (mParent instanceof View) {
10750            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10751        }
10752    }
10753
10754    /**
10755     * Used to indicate that the parent of this view should be invalidated. This functionality
10756     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10757     * which is necessary when various parent-managed properties of the view change, such as
10758     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10759     * an invalidation event to the parent.
10760     *
10761     * @hide
10762     */
10763    protected void invalidateParentIfNeeded() {
10764        if (isHardwareAccelerated() && mParent instanceof View) {
10765            ((View) mParent).invalidate(true);
10766        }
10767    }
10768
10769    /**
10770     * Indicates whether this View is opaque. An opaque View guarantees that it will
10771     * draw all the pixels overlapping its bounds using a fully opaque color.
10772     *
10773     * Subclasses of View should override this method whenever possible to indicate
10774     * whether an instance is opaque. Opaque Views are treated in a special way by
10775     * the View hierarchy, possibly allowing it to perform optimizations during
10776     * invalidate/draw passes.
10777     *
10778     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10779     */
10780    @ViewDebug.ExportedProperty(category = "drawing")
10781    public boolean isOpaque() {
10782        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10783                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10784    }
10785
10786    /**
10787     * @hide
10788     */
10789    protected void computeOpaqueFlags() {
10790        // Opaque if:
10791        //   - Has a background
10792        //   - Background is opaque
10793        //   - Doesn't have scrollbars or scrollbars overlay
10794
10795        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10796            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10797        } else {
10798            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10799        }
10800
10801        final int flags = mViewFlags;
10802        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10803                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10804                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10805            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10806        } else {
10807            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10808        }
10809    }
10810
10811    /**
10812     * @hide
10813     */
10814    protected boolean hasOpaqueScrollbars() {
10815        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10816    }
10817
10818    /**
10819     * @return A handler associated with the thread running the View. This
10820     * handler can be used to pump events in the UI events queue.
10821     */
10822    public Handler getHandler() {
10823        final AttachInfo attachInfo = mAttachInfo;
10824        if (attachInfo != null) {
10825            return attachInfo.mHandler;
10826        }
10827        return null;
10828    }
10829
10830    /**
10831     * Gets the view root associated with the View.
10832     * @return The view root, or null if none.
10833     * @hide
10834     */
10835    public ViewRootImpl getViewRootImpl() {
10836        if (mAttachInfo != null) {
10837            return mAttachInfo.mViewRootImpl;
10838        }
10839        return null;
10840    }
10841
10842    /**
10843     * <p>Causes the Runnable to be added to the message queue.
10844     * The runnable will be run on the user interface thread.</p>
10845     *
10846     * @param action The Runnable that will be executed.
10847     *
10848     * @return Returns true if the Runnable was successfully placed in to the
10849     *         message queue.  Returns false on failure, usually because the
10850     *         looper processing the message queue is exiting.
10851     *
10852     * @see #postDelayed
10853     * @see #removeCallbacks
10854     */
10855    public boolean post(Runnable action) {
10856        final AttachInfo attachInfo = mAttachInfo;
10857        if (attachInfo != null) {
10858            return attachInfo.mHandler.post(action);
10859        }
10860        // Assume that post will succeed later
10861        ViewRootImpl.getRunQueue().post(action);
10862        return true;
10863    }
10864
10865    /**
10866     * <p>Causes the Runnable to be added to the message queue, to be run
10867     * after the specified amount of time elapses.
10868     * The runnable will be run on the user interface thread.</p>
10869     *
10870     * @param action The Runnable that will be executed.
10871     * @param delayMillis The delay (in milliseconds) until the Runnable
10872     *        will be executed.
10873     *
10874     * @return true if the Runnable was successfully placed in to the
10875     *         message queue.  Returns false on failure, usually because the
10876     *         looper processing the message queue is exiting.  Note that a
10877     *         result of true does not mean the Runnable will be processed --
10878     *         if the looper is quit before the delivery time of the message
10879     *         occurs then the message will be dropped.
10880     *
10881     * @see #post
10882     * @see #removeCallbacks
10883     */
10884    public boolean postDelayed(Runnable action, long delayMillis) {
10885        final AttachInfo attachInfo = mAttachInfo;
10886        if (attachInfo != null) {
10887            return attachInfo.mHandler.postDelayed(action, delayMillis);
10888        }
10889        // Assume that post will succeed later
10890        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10891        return true;
10892    }
10893
10894    /**
10895     * <p>Causes the Runnable to execute on the next animation time step.
10896     * The runnable will be run on the user interface thread.</p>
10897     *
10898     * @param action The Runnable that will be executed.
10899     *
10900     * @see #postOnAnimationDelayed
10901     * @see #removeCallbacks
10902     */
10903    public void postOnAnimation(Runnable action) {
10904        final AttachInfo attachInfo = mAttachInfo;
10905        if (attachInfo != null) {
10906            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10907                    Choreographer.CALLBACK_ANIMATION, action, null);
10908        } else {
10909            // Assume that post will succeed later
10910            ViewRootImpl.getRunQueue().post(action);
10911        }
10912    }
10913
10914    /**
10915     * <p>Causes the Runnable to execute on the next animation time step,
10916     * after the specified amount of time elapses.
10917     * The runnable will be run on the user interface thread.</p>
10918     *
10919     * @param action The Runnable that will be executed.
10920     * @param delayMillis The delay (in milliseconds) until the Runnable
10921     *        will be executed.
10922     *
10923     * @see #postOnAnimation
10924     * @see #removeCallbacks
10925     */
10926    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10927        final AttachInfo attachInfo = mAttachInfo;
10928        if (attachInfo != null) {
10929            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10930                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10931        } else {
10932            // Assume that post will succeed later
10933            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10934        }
10935    }
10936
10937    /**
10938     * <p>Removes the specified Runnable from the message queue.</p>
10939     *
10940     * @param action The Runnable to remove from the message handling queue
10941     *
10942     * @return true if this view could ask the Handler to remove the Runnable,
10943     *         false otherwise. When the returned value is true, the Runnable
10944     *         may or may not have been actually removed from the message queue
10945     *         (for instance, if the Runnable was not in the queue already.)
10946     *
10947     * @see #post
10948     * @see #postDelayed
10949     * @see #postOnAnimation
10950     * @see #postOnAnimationDelayed
10951     */
10952    public boolean removeCallbacks(Runnable action) {
10953        if (action != null) {
10954            final AttachInfo attachInfo = mAttachInfo;
10955            if (attachInfo != null) {
10956                attachInfo.mHandler.removeCallbacks(action);
10957                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10958                        Choreographer.CALLBACK_ANIMATION, action, null);
10959            } else {
10960                // Assume that post will succeed later
10961                ViewRootImpl.getRunQueue().removeCallbacks(action);
10962            }
10963        }
10964        return true;
10965    }
10966
10967    /**
10968     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10969     * Use this to invalidate the View from a non-UI thread.</p>
10970     *
10971     * <p>This method can be invoked from outside of the UI thread
10972     * only when this View is attached to a window.</p>
10973     *
10974     * @see #invalidate()
10975     * @see #postInvalidateDelayed(long)
10976     */
10977    public void postInvalidate() {
10978        postInvalidateDelayed(0);
10979    }
10980
10981    /**
10982     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10983     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10984     *
10985     * <p>This method can be invoked from outside of the UI thread
10986     * only when this View is attached to a window.</p>
10987     *
10988     * @param left The left coordinate of the rectangle to invalidate.
10989     * @param top The top coordinate of the rectangle to invalidate.
10990     * @param right The right coordinate of the rectangle to invalidate.
10991     * @param bottom The bottom coordinate of the rectangle to invalidate.
10992     *
10993     * @see #invalidate(int, int, int, int)
10994     * @see #invalidate(Rect)
10995     * @see #postInvalidateDelayed(long, int, int, int, int)
10996     */
10997    public void postInvalidate(int left, int top, int right, int bottom) {
10998        postInvalidateDelayed(0, left, top, right, bottom);
10999    }
11000
11001    /**
11002     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11003     * loop. Waits for the specified amount of time.</p>
11004     *
11005     * <p>This method can be invoked from outside of the UI thread
11006     * only when this View is attached to a window.</p>
11007     *
11008     * @param delayMilliseconds the duration in milliseconds to delay the
11009     *         invalidation by
11010     *
11011     * @see #invalidate()
11012     * @see #postInvalidate()
11013     */
11014    public void postInvalidateDelayed(long delayMilliseconds) {
11015        // We try only with the AttachInfo because there's no point in invalidating
11016        // if we are not attached to our window
11017        final AttachInfo attachInfo = mAttachInfo;
11018        if (attachInfo != null) {
11019            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11020        }
11021    }
11022
11023    /**
11024     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11025     * through the event loop. Waits for the specified amount of time.</p>
11026     *
11027     * <p>This method can be invoked from outside of the UI thread
11028     * only when this View is attached to a window.</p>
11029     *
11030     * @param delayMilliseconds the duration in milliseconds to delay the
11031     *         invalidation by
11032     * @param left The left coordinate of the rectangle to invalidate.
11033     * @param top The top coordinate of the rectangle to invalidate.
11034     * @param right The right coordinate of the rectangle to invalidate.
11035     * @param bottom The bottom coordinate of the rectangle to invalidate.
11036     *
11037     * @see #invalidate(int, int, int, int)
11038     * @see #invalidate(Rect)
11039     * @see #postInvalidate(int, int, int, int)
11040     */
11041    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11042            int right, int bottom) {
11043
11044        // We try only with the AttachInfo because there's no point in invalidating
11045        // if we are not attached to our window
11046        final AttachInfo attachInfo = mAttachInfo;
11047        if (attachInfo != null) {
11048            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11049            info.target = this;
11050            info.left = left;
11051            info.top = top;
11052            info.right = right;
11053            info.bottom = bottom;
11054
11055            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11056        }
11057    }
11058
11059    /**
11060     * <p>Cause an invalidate to happen on the next animation time step, typically the
11061     * next display frame.</p>
11062     *
11063     * <p>This method can be invoked from outside of the UI thread
11064     * only when this View is attached to a window.</p>
11065     *
11066     * @see #invalidate()
11067     */
11068    public void postInvalidateOnAnimation() {
11069        // We try only with the AttachInfo because there's no point in invalidating
11070        // if we are not attached to our window
11071        final AttachInfo attachInfo = mAttachInfo;
11072        if (attachInfo != null) {
11073            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11074        }
11075    }
11076
11077    /**
11078     * <p>Cause an invalidate of the specified area to happen on the next animation
11079     * time step, typically the next display frame.</p>
11080     *
11081     * <p>This method can be invoked from outside of the UI thread
11082     * only when this View is attached to a window.</p>
11083     *
11084     * @param left The left coordinate of the rectangle to invalidate.
11085     * @param top The top coordinate of the rectangle to invalidate.
11086     * @param right The right coordinate of the rectangle to invalidate.
11087     * @param bottom The bottom coordinate of the rectangle to invalidate.
11088     *
11089     * @see #invalidate(int, int, int, int)
11090     * @see #invalidate(Rect)
11091     */
11092    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11093        // We try only with the AttachInfo because there's no point in invalidating
11094        // if we are not attached to our window
11095        final AttachInfo attachInfo = mAttachInfo;
11096        if (attachInfo != null) {
11097            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11098            info.target = this;
11099            info.left = left;
11100            info.top = top;
11101            info.right = right;
11102            info.bottom = bottom;
11103
11104            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11105        }
11106    }
11107
11108    /**
11109     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11110     * This event is sent at most once every
11111     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11112     */
11113    private void postSendViewScrolledAccessibilityEventCallback() {
11114        if (mSendViewScrolledAccessibilityEvent == null) {
11115            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11116        }
11117        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11118            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11119            postDelayed(mSendViewScrolledAccessibilityEvent,
11120                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11121        }
11122    }
11123
11124    /**
11125     * Called by a parent to request that a child update its values for mScrollX
11126     * and mScrollY if necessary. This will typically be done if the child is
11127     * animating a scroll using a {@link android.widget.Scroller Scroller}
11128     * object.
11129     */
11130    public void computeScroll() {
11131    }
11132
11133    /**
11134     * <p>Indicate whether the horizontal edges are faded when the view is
11135     * scrolled horizontally.</p>
11136     *
11137     * @return true if the horizontal edges should are faded on scroll, false
11138     *         otherwise
11139     *
11140     * @see #setHorizontalFadingEdgeEnabled(boolean)
11141     *
11142     * @attr ref android.R.styleable#View_requiresFadingEdge
11143     */
11144    public boolean isHorizontalFadingEdgeEnabled() {
11145        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11146    }
11147
11148    /**
11149     * <p>Define whether the horizontal edges should be faded when this view
11150     * is scrolled horizontally.</p>
11151     *
11152     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11153     *                                    be faded when the view is scrolled
11154     *                                    horizontally
11155     *
11156     * @see #isHorizontalFadingEdgeEnabled()
11157     *
11158     * @attr ref android.R.styleable#View_requiresFadingEdge
11159     */
11160    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11161        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11162            if (horizontalFadingEdgeEnabled) {
11163                initScrollCache();
11164            }
11165
11166            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11167        }
11168    }
11169
11170    /**
11171     * <p>Indicate whether the vertical edges are faded when the view is
11172     * scrolled horizontally.</p>
11173     *
11174     * @return true if the vertical edges should are faded on scroll, false
11175     *         otherwise
11176     *
11177     * @see #setVerticalFadingEdgeEnabled(boolean)
11178     *
11179     * @attr ref android.R.styleable#View_requiresFadingEdge
11180     */
11181    public boolean isVerticalFadingEdgeEnabled() {
11182        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11183    }
11184
11185    /**
11186     * <p>Define whether the vertical edges should be faded when this view
11187     * is scrolled vertically.</p>
11188     *
11189     * @param verticalFadingEdgeEnabled true if the vertical edges should
11190     *                                  be faded when the view is scrolled
11191     *                                  vertically
11192     *
11193     * @see #isVerticalFadingEdgeEnabled()
11194     *
11195     * @attr ref android.R.styleable#View_requiresFadingEdge
11196     */
11197    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11198        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11199            if (verticalFadingEdgeEnabled) {
11200                initScrollCache();
11201            }
11202
11203            mViewFlags ^= FADING_EDGE_VERTICAL;
11204        }
11205    }
11206
11207    /**
11208     * Returns the strength, or intensity, of the top faded edge. The strength is
11209     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11210     * returns 0.0 or 1.0 but no value in between.
11211     *
11212     * Subclasses should override this method to provide a smoother fade transition
11213     * when scrolling occurs.
11214     *
11215     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11216     */
11217    protected float getTopFadingEdgeStrength() {
11218        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11219    }
11220
11221    /**
11222     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11223     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11224     * returns 0.0 or 1.0 but no value in between.
11225     *
11226     * Subclasses should override this method to provide a smoother fade transition
11227     * when scrolling occurs.
11228     *
11229     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11230     */
11231    protected float getBottomFadingEdgeStrength() {
11232        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11233                computeVerticalScrollRange() ? 1.0f : 0.0f;
11234    }
11235
11236    /**
11237     * Returns the strength, or intensity, of the left faded edge. The strength is
11238     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11239     * returns 0.0 or 1.0 but no value in between.
11240     *
11241     * Subclasses should override this method to provide a smoother fade transition
11242     * when scrolling occurs.
11243     *
11244     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11245     */
11246    protected float getLeftFadingEdgeStrength() {
11247        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11248    }
11249
11250    /**
11251     * Returns the strength, or intensity, of the right faded edge. The strength is
11252     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11253     * returns 0.0 or 1.0 but no value in between.
11254     *
11255     * Subclasses should override this method to provide a smoother fade transition
11256     * when scrolling occurs.
11257     *
11258     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11259     */
11260    protected float getRightFadingEdgeStrength() {
11261        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11262                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11263    }
11264
11265    /**
11266     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11267     * scrollbar is not drawn by default.</p>
11268     *
11269     * @return true if the horizontal scrollbar should be painted, false
11270     *         otherwise
11271     *
11272     * @see #setHorizontalScrollBarEnabled(boolean)
11273     */
11274    public boolean isHorizontalScrollBarEnabled() {
11275        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11276    }
11277
11278    /**
11279     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11280     * scrollbar is not drawn by default.</p>
11281     *
11282     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11283     *                                   be painted
11284     *
11285     * @see #isHorizontalScrollBarEnabled()
11286     */
11287    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11288        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11289            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11290            computeOpaqueFlags();
11291            resolvePadding();
11292        }
11293    }
11294
11295    /**
11296     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11297     * scrollbar is not drawn by default.</p>
11298     *
11299     * @return true if the vertical scrollbar should be painted, false
11300     *         otherwise
11301     *
11302     * @see #setVerticalScrollBarEnabled(boolean)
11303     */
11304    public boolean isVerticalScrollBarEnabled() {
11305        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11306    }
11307
11308    /**
11309     * <p>Define whether the vertical scrollbar should be drawn or not. The
11310     * scrollbar is not drawn by default.</p>
11311     *
11312     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11313     *                                 be painted
11314     *
11315     * @see #isVerticalScrollBarEnabled()
11316     */
11317    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11318        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11319            mViewFlags ^= SCROLLBARS_VERTICAL;
11320            computeOpaqueFlags();
11321            resolvePadding();
11322        }
11323    }
11324
11325    /**
11326     * @hide
11327     */
11328    protected void recomputePadding() {
11329        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11330    }
11331
11332    /**
11333     * Define whether scrollbars will fade when the view is not scrolling.
11334     *
11335     * @param fadeScrollbars wheter to enable fading
11336     *
11337     * @attr ref android.R.styleable#View_fadeScrollbars
11338     */
11339    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11340        initScrollCache();
11341        final ScrollabilityCache scrollabilityCache = mScrollCache;
11342        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11343        if (fadeScrollbars) {
11344            scrollabilityCache.state = ScrollabilityCache.OFF;
11345        } else {
11346            scrollabilityCache.state = ScrollabilityCache.ON;
11347        }
11348    }
11349
11350    /**
11351     *
11352     * Returns true if scrollbars will fade when this view is not scrolling
11353     *
11354     * @return true if scrollbar fading is enabled
11355     *
11356     * @attr ref android.R.styleable#View_fadeScrollbars
11357     */
11358    public boolean isScrollbarFadingEnabled() {
11359        return mScrollCache != null && mScrollCache.fadeScrollBars;
11360    }
11361
11362    /**
11363     *
11364     * Returns the delay before scrollbars fade.
11365     *
11366     * @return the delay before scrollbars fade
11367     *
11368     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11369     */
11370    public int getScrollBarDefaultDelayBeforeFade() {
11371        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11372                mScrollCache.scrollBarDefaultDelayBeforeFade;
11373    }
11374
11375    /**
11376     * Define the delay before scrollbars fade.
11377     *
11378     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11379     *
11380     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11381     */
11382    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11383        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11384    }
11385
11386    /**
11387     *
11388     * Returns the scrollbar fade duration.
11389     *
11390     * @return the scrollbar fade duration
11391     *
11392     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11393     */
11394    public int getScrollBarFadeDuration() {
11395        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11396                mScrollCache.scrollBarFadeDuration;
11397    }
11398
11399    /**
11400     * Define the scrollbar fade duration.
11401     *
11402     * @param scrollBarFadeDuration - the scrollbar fade duration
11403     *
11404     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11405     */
11406    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11407        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11408    }
11409
11410    /**
11411     *
11412     * Returns the scrollbar size.
11413     *
11414     * @return the scrollbar size
11415     *
11416     * @attr ref android.R.styleable#View_scrollbarSize
11417     */
11418    public int getScrollBarSize() {
11419        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11420                mScrollCache.scrollBarSize;
11421    }
11422
11423    /**
11424     * Define the scrollbar size.
11425     *
11426     * @param scrollBarSize - the scrollbar size
11427     *
11428     * @attr ref android.R.styleable#View_scrollbarSize
11429     */
11430    public void setScrollBarSize(int scrollBarSize) {
11431        getScrollCache().scrollBarSize = scrollBarSize;
11432    }
11433
11434    /**
11435     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11436     * inset. When inset, they add to the padding of the view. And the scrollbars
11437     * can be drawn inside the padding area or on the edge of the view. For example,
11438     * if a view has a background drawable and you want to draw the scrollbars
11439     * inside the padding specified by the drawable, you can use
11440     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11441     * appear at the edge of the view, ignoring the padding, then you can use
11442     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11443     * @param style the style of the scrollbars. Should be one of
11444     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11445     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11446     * @see #SCROLLBARS_INSIDE_OVERLAY
11447     * @see #SCROLLBARS_INSIDE_INSET
11448     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11449     * @see #SCROLLBARS_OUTSIDE_INSET
11450     *
11451     * @attr ref android.R.styleable#View_scrollbarStyle
11452     */
11453    public void setScrollBarStyle(int style) {
11454        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11455            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11456            computeOpaqueFlags();
11457            resolvePadding();
11458        }
11459    }
11460
11461    /**
11462     * <p>Returns the current scrollbar style.</p>
11463     * @return the current scrollbar style
11464     * @see #SCROLLBARS_INSIDE_OVERLAY
11465     * @see #SCROLLBARS_INSIDE_INSET
11466     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11467     * @see #SCROLLBARS_OUTSIDE_INSET
11468     *
11469     * @attr ref android.R.styleable#View_scrollbarStyle
11470     */
11471    @ViewDebug.ExportedProperty(mapping = {
11472            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11473            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11474            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11475            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11476    })
11477    public int getScrollBarStyle() {
11478        return mViewFlags & SCROLLBARS_STYLE_MASK;
11479    }
11480
11481    /**
11482     * <p>Compute the horizontal range that the horizontal scrollbar
11483     * represents.</p>
11484     *
11485     * <p>The range is expressed in arbitrary units that must be the same as the
11486     * units used by {@link #computeHorizontalScrollExtent()} and
11487     * {@link #computeHorizontalScrollOffset()}.</p>
11488     *
11489     * <p>The default range is the drawing width of this view.</p>
11490     *
11491     * @return the total horizontal range represented by the horizontal
11492     *         scrollbar
11493     *
11494     * @see #computeHorizontalScrollExtent()
11495     * @see #computeHorizontalScrollOffset()
11496     * @see android.widget.ScrollBarDrawable
11497     */
11498    protected int computeHorizontalScrollRange() {
11499        return getWidth();
11500    }
11501
11502    /**
11503     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11504     * within the horizontal range. This value is used to compute the position
11505     * of the thumb within the scrollbar's track.</p>
11506     *
11507     * <p>The range is expressed in arbitrary units that must be the same as the
11508     * units used by {@link #computeHorizontalScrollRange()} and
11509     * {@link #computeHorizontalScrollExtent()}.</p>
11510     *
11511     * <p>The default offset is the scroll offset of this view.</p>
11512     *
11513     * @return the horizontal offset of the scrollbar's thumb
11514     *
11515     * @see #computeHorizontalScrollRange()
11516     * @see #computeHorizontalScrollExtent()
11517     * @see android.widget.ScrollBarDrawable
11518     */
11519    protected int computeHorizontalScrollOffset() {
11520        return mScrollX;
11521    }
11522
11523    /**
11524     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11525     * within the horizontal range. This value is used to compute the length
11526     * of the thumb within the scrollbar's track.</p>
11527     *
11528     * <p>The range is expressed in arbitrary units that must be the same as the
11529     * units used by {@link #computeHorizontalScrollRange()} and
11530     * {@link #computeHorizontalScrollOffset()}.</p>
11531     *
11532     * <p>The default extent is the drawing width of this view.</p>
11533     *
11534     * @return the horizontal extent of the scrollbar's thumb
11535     *
11536     * @see #computeHorizontalScrollRange()
11537     * @see #computeHorizontalScrollOffset()
11538     * @see android.widget.ScrollBarDrawable
11539     */
11540    protected int computeHorizontalScrollExtent() {
11541        return getWidth();
11542    }
11543
11544    /**
11545     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11546     *
11547     * <p>The range is expressed in arbitrary units that must be the same as the
11548     * units used by {@link #computeVerticalScrollExtent()} and
11549     * {@link #computeVerticalScrollOffset()}.</p>
11550     *
11551     * @return the total vertical range represented by the vertical scrollbar
11552     *
11553     * <p>The default range is the drawing height of this view.</p>
11554     *
11555     * @see #computeVerticalScrollExtent()
11556     * @see #computeVerticalScrollOffset()
11557     * @see android.widget.ScrollBarDrawable
11558     */
11559    protected int computeVerticalScrollRange() {
11560        return getHeight();
11561    }
11562
11563    /**
11564     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11565     * within the horizontal range. This value is used to compute the position
11566     * of the thumb within the scrollbar's track.</p>
11567     *
11568     * <p>The range is expressed in arbitrary units that must be the same as the
11569     * units used by {@link #computeVerticalScrollRange()} and
11570     * {@link #computeVerticalScrollExtent()}.</p>
11571     *
11572     * <p>The default offset is the scroll offset of this view.</p>
11573     *
11574     * @return the vertical offset of the scrollbar's thumb
11575     *
11576     * @see #computeVerticalScrollRange()
11577     * @see #computeVerticalScrollExtent()
11578     * @see android.widget.ScrollBarDrawable
11579     */
11580    protected int computeVerticalScrollOffset() {
11581        return mScrollY;
11582    }
11583
11584    /**
11585     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11586     * within the vertical range. This value is used to compute the length
11587     * of the thumb within the scrollbar's track.</p>
11588     *
11589     * <p>The range is expressed in arbitrary units that must be the same as the
11590     * units used by {@link #computeVerticalScrollRange()} and
11591     * {@link #computeVerticalScrollOffset()}.</p>
11592     *
11593     * <p>The default extent is the drawing height of this view.</p>
11594     *
11595     * @return the vertical extent of the scrollbar's thumb
11596     *
11597     * @see #computeVerticalScrollRange()
11598     * @see #computeVerticalScrollOffset()
11599     * @see android.widget.ScrollBarDrawable
11600     */
11601    protected int computeVerticalScrollExtent() {
11602        return getHeight();
11603    }
11604
11605    /**
11606     * Check if this view can be scrolled horizontally in a certain direction.
11607     *
11608     * @param direction Negative to check scrolling left, positive to check scrolling right.
11609     * @return true if this view can be scrolled in the specified direction, false otherwise.
11610     */
11611    public boolean canScrollHorizontally(int direction) {
11612        final int offset = computeHorizontalScrollOffset();
11613        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11614        if (range == 0) return false;
11615        if (direction < 0) {
11616            return offset > 0;
11617        } else {
11618            return offset < range - 1;
11619        }
11620    }
11621
11622    /**
11623     * Check if this view can be scrolled vertically in a certain direction.
11624     *
11625     * @param direction Negative to check scrolling up, positive to check scrolling down.
11626     * @return true if this view can be scrolled in the specified direction, false otherwise.
11627     */
11628    public boolean canScrollVertically(int direction) {
11629        final int offset = computeVerticalScrollOffset();
11630        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11631        if (range == 0) return false;
11632        if (direction < 0) {
11633            return offset > 0;
11634        } else {
11635            return offset < range - 1;
11636        }
11637    }
11638
11639    /**
11640     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11641     * scrollbars are painted only if they have been awakened first.</p>
11642     *
11643     * @param canvas the canvas on which to draw the scrollbars
11644     *
11645     * @see #awakenScrollBars(int)
11646     */
11647    protected final void onDrawScrollBars(Canvas canvas) {
11648        // scrollbars are drawn only when the animation is running
11649        final ScrollabilityCache cache = mScrollCache;
11650        if (cache != null) {
11651
11652            int state = cache.state;
11653
11654            if (state == ScrollabilityCache.OFF) {
11655                return;
11656            }
11657
11658            boolean invalidate = false;
11659
11660            if (state == ScrollabilityCache.FADING) {
11661                // We're fading -- get our fade interpolation
11662                if (cache.interpolatorValues == null) {
11663                    cache.interpolatorValues = new float[1];
11664                }
11665
11666                float[] values = cache.interpolatorValues;
11667
11668                // Stops the animation if we're done
11669                if (cache.scrollBarInterpolator.timeToValues(values) ==
11670                        Interpolator.Result.FREEZE_END) {
11671                    cache.state = ScrollabilityCache.OFF;
11672                } else {
11673                    cache.scrollBar.setAlpha(Math.round(values[0]));
11674                }
11675
11676                // This will make the scroll bars inval themselves after
11677                // drawing. We only want this when we're fading so that
11678                // we prevent excessive redraws
11679                invalidate = true;
11680            } else {
11681                // We're just on -- but we may have been fading before so
11682                // reset alpha
11683                cache.scrollBar.setAlpha(255);
11684            }
11685
11686
11687            final int viewFlags = mViewFlags;
11688
11689            final boolean drawHorizontalScrollBar =
11690                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11691            final boolean drawVerticalScrollBar =
11692                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11693                && !isVerticalScrollBarHidden();
11694
11695            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11696                final int width = mRight - mLeft;
11697                final int height = mBottom - mTop;
11698
11699                final ScrollBarDrawable scrollBar = cache.scrollBar;
11700
11701                final int scrollX = mScrollX;
11702                final int scrollY = mScrollY;
11703                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11704
11705                int left;
11706                int top;
11707                int right;
11708                int bottom;
11709
11710                if (drawHorizontalScrollBar) {
11711                    int size = scrollBar.getSize(false);
11712                    if (size <= 0) {
11713                        size = cache.scrollBarSize;
11714                    }
11715
11716                    scrollBar.setParameters(computeHorizontalScrollRange(),
11717                                            computeHorizontalScrollOffset(),
11718                                            computeHorizontalScrollExtent(), false);
11719                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11720                            getVerticalScrollbarWidth() : 0;
11721                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11722                    left = scrollX + (mPaddingLeft & inside);
11723                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11724                    bottom = top + size;
11725                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11726                    if (invalidate) {
11727                        invalidate(left, top, right, bottom);
11728                    }
11729                }
11730
11731                if (drawVerticalScrollBar) {
11732                    int size = scrollBar.getSize(true);
11733                    if (size <= 0) {
11734                        size = cache.scrollBarSize;
11735                    }
11736
11737                    scrollBar.setParameters(computeVerticalScrollRange(),
11738                                            computeVerticalScrollOffset(),
11739                                            computeVerticalScrollExtent(), true);
11740                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11741                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11742                        verticalScrollbarPosition = isLayoutRtl() ?
11743                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11744                    }
11745                    switch (verticalScrollbarPosition) {
11746                        default:
11747                        case SCROLLBAR_POSITION_RIGHT:
11748                            left = scrollX + width - size - (mUserPaddingRight & inside);
11749                            break;
11750                        case SCROLLBAR_POSITION_LEFT:
11751                            left = scrollX + (mUserPaddingLeft & inside);
11752                            break;
11753                    }
11754                    top = scrollY + (mPaddingTop & inside);
11755                    right = left + size;
11756                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11757                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11758                    if (invalidate) {
11759                        invalidate(left, top, right, bottom);
11760                    }
11761                }
11762            }
11763        }
11764    }
11765
11766    /**
11767     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11768     * FastScroller is visible.
11769     * @return whether to temporarily hide the vertical scrollbar
11770     * @hide
11771     */
11772    protected boolean isVerticalScrollBarHidden() {
11773        return false;
11774    }
11775
11776    /**
11777     * <p>Draw the horizontal scrollbar if
11778     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11779     *
11780     * @param canvas the canvas on which to draw the scrollbar
11781     * @param scrollBar the scrollbar's drawable
11782     *
11783     * @see #isHorizontalScrollBarEnabled()
11784     * @see #computeHorizontalScrollRange()
11785     * @see #computeHorizontalScrollExtent()
11786     * @see #computeHorizontalScrollOffset()
11787     * @see android.widget.ScrollBarDrawable
11788     * @hide
11789     */
11790    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11791            int l, int t, int r, int b) {
11792        scrollBar.setBounds(l, t, r, b);
11793        scrollBar.draw(canvas);
11794    }
11795
11796    /**
11797     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11798     * returns true.</p>
11799     *
11800     * @param canvas the canvas on which to draw the scrollbar
11801     * @param scrollBar the scrollbar's drawable
11802     *
11803     * @see #isVerticalScrollBarEnabled()
11804     * @see #computeVerticalScrollRange()
11805     * @see #computeVerticalScrollExtent()
11806     * @see #computeVerticalScrollOffset()
11807     * @see android.widget.ScrollBarDrawable
11808     * @hide
11809     */
11810    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11811            int l, int t, int r, int b) {
11812        scrollBar.setBounds(l, t, r, b);
11813        scrollBar.draw(canvas);
11814    }
11815
11816    /**
11817     * Implement this to do your drawing.
11818     *
11819     * @param canvas the canvas on which the background will be drawn
11820     */
11821    protected void onDraw(Canvas canvas) {
11822    }
11823
11824    /*
11825     * Caller is responsible for calling requestLayout if necessary.
11826     * (This allows addViewInLayout to not request a new layout.)
11827     */
11828    void assignParent(ViewParent parent) {
11829        if (mParent == null) {
11830            mParent = parent;
11831        } else if (parent == null) {
11832            mParent = null;
11833        } else {
11834            throw new RuntimeException("view " + this + " being added, but"
11835                    + " it already has a parent");
11836        }
11837    }
11838
11839    /**
11840     * This is called when the view is attached to a window.  At this point it
11841     * has a Surface and will start drawing.  Note that this function is
11842     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11843     * however it may be called any time before the first onDraw -- including
11844     * before or after {@link #onMeasure(int, int)}.
11845     *
11846     * @see #onDetachedFromWindow()
11847     */
11848    protected void onAttachedToWindow() {
11849        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11850            mParent.requestTransparentRegion(this);
11851        }
11852
11853        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11854            initialAwakenScrollBars();
11855            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11856        }
11857
11858        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11859
11860        jumpDrawablesToCurrentState();
11861
11862        clearAccessibilityFocus();
11863        resetSubtreeAccessibilityStateChanged();
11864
11865        if (isFocused()) {
11866            InputMethodManager imm = InputMethodManager.peekInstance();
11867            imm.focusIn(this);
11868        }
11869
11870        if (mDisplayList != null) {
11871            mDisplayList.clearDirty();
11872        }
11873    }
11874
11875    /**
11876     * Resolve all RTL related properties.
11877     *
11878     * @return true if resolution of RTL properties has been done
11879     *
11880     * @hide
11881     */
11882    public boolean resolveRtlPropertiesIfNeeded() {
11883        if (!needRtlPropertiesResolution()) return false;
11884
11885        // Order is important here: LayoutDirection MUST be resolved first
11886        if (!isLayoutDirectionResolved()) {
11887            resolveLayoutDirection();
11888            resolveLayoutParams();
11889        }
11890        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11891        if (!isTextDirectionResolved()) {
11892            resolveTextDirection();
11893        }
11894        if (!isTextAlignmentResolved()) {
11895            resolveTextAlignment();
11896        }
11897        if (!isPaddingResolved()) {
11898            resolvePadding();
11899        }
11900        if (!isDrawablesResolved()) {
11901            resolveDrawables();
11902        }
11903        onRtlPropertiesChanged(getLayoutDirection());
11904        return true;
11905    }
11906
11907    /**
11908     * Reset resolution of all RTL related properties.
11909     *
11910     * @hide
11911     */
11912    public void resetRtlProperties() {
11913        resetResolvedLayoutDirection();
11914        resetResolvedTextDirection();
11915        resetResolvedTextAlignment();
11916        resetResolvedPadding();
11917        resetResolvedDrawables();
11918    }
11919
11920    /**
11921     * @see #onScreenStateChanged(int)
11922     */
11923    void dispatchScreenStateChanged(int screenState) {
11924        onScreenStateChanged(screenState);
11925    }
11926
11927    /**
11928     * This method is called whenever the state of the screen this view is
11929     * attached to changes. A state change will usually occurs when the screen
11930     * turns on or off (whether it happens automatically or the user does it
11931     * manually.)
11932     *
11933     * @param screenState The new state of the screen. Can be either
11934     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11935     */
11936    public void onScreenStateChanged(int screenState) {
11937    }
11938
11939    /**
11940     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11941     */
11942    private boolean hasRtlSupport() {
11943        return mContext.getApplicationInfo().hasRtlSupport();
11944    }
11945
11946    /**
11947     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11948     * RTL not supported)
11949     */
11950    private boolean isRtlCompatibilityMode() {
11951        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11952        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11953    }
11954
11955    /**
11956     * @return true if RTL properties need resolution.
11957     *
11958     */
11959    private boolean needRtlPropertiesResolution() {
11960        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11961    }
11962
11963    /**
11964     * Called when any RTL property (layout direction or text direction or text alignment) has
11965     * been changed.
11966     *
11967     * Subclasses need to override this method to take care of cached information that depends on the
11968     * resolved layout direction, or to inform child views that inherit their layout direction.
11969     *
11970     * The default implementation does nothing.
11971     *
11972     * @param layoutDirection the direction of the layout
11973     *
11974     * @see #LAYOUT_DIRECTION_LTR
11975     * @see #LAYOUT_DIRECTION_RTL
11976     */
11977    public void onRtlPropertiesChanged(int layoutDirection) {
11978    }
11979
11980    /**
11981     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11982     * that the parent directionality can and will be resolved before its children.
11983     *
11984     * @return true if resolution has been done, false otherwise.
11985     *
11986     * @hide
11987     */
11988    public boolean resolveLayoutDirection() {
11989        // Clear any previous layout direction resolution
11990        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11991
11992        if (hasRtlSupport()) {
11993            // Set resolved depending on layout direction
11994            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11995                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11996                case LAYOUT_DIRECTION_INHERIT:
11997                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11998                    // later to get the correct resolved value
11999                    if (!canResolveLayoutDirection()) return false;
12000
12001                    // Parent has not yet resolved, LTR is still the default
12002                    try {
12003                        if (!mParent.isLayoutDirectionResolved()) return false;
12004
12005                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12006                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12007                        }
12008                    } catch (AbstractMethodError e) {
12009                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12010                                " does not fully implement ViewParent", e);
12011                    }
12012                    break;
12013                case LAYOUT_DIRECTION_RTL:
12014                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12015                    break;
12016                case LAYOUT_DIRECTION_LOCALE:
12017                    if((LAYOUT_DIRECTION_RTL ==
12018                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12019                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12020                    }
12021                    break;
12022                default:
12023                    // Nothing to do, LTR by default
12024            }
12025        }
12026
12027        // Set to resolved
12028        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12029        return true;
12030    }
12031
12032    /**
12033     * Check if layout direction resolution can be done.
12034     *
12035     * @return true if layout direction resolution can be done otherwise return false.
12036     */
12037    public boolean canResolveLayoutDirection() {
12038        switch (getRawLayoutDirection()) {
12039            case LAYOUT_DIRECTION_INHERIT:
12040                if (mParent != null) {
12041                    try {
12042                        return mParent.canResolveLayoutDirection();
12043                    } catch (AbstractMethodError e) {
12044                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12045                                " does not fully implement ViewParent", e);
12046                    }
12047                }
12048                return false;
12049
12050            default:
12051                return true;
12052        }
12053    }
12054
12055    /**
12056     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12057     * {@link #onMeasure(int, int)}.
12058     *
12059     * @hide
12060     */
12061    public void resetResolvedLayoutDirection() {
12062        // Reset the current resolved bits
12063        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12064    }
12065
12066    /**
12067     * @return true if the layout direction is inherited.
12068     *
12069     * @hide
12070     */
12071    public boolean isLayoutDirectionInherited() {
12072        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12073    }
12074
12075    /**
12076     * @return true if layout direction has been resolved.
12077     */
12078    public boolean isLayoutDirectionResolved() {
12079        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12080    }
12081
12082    /**
12083     * Return if padding has been resolved
12084     *
12085     * @hide
12086     */
12087    boolean isPaddingResolved() {
12088        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12089    }
12090
12091    /**
12092     * Resolves padding depending on layout direction, if applicable, and
12093     * recomputes internal padding values to adjust for scroll bars.
12094     *
12095     * @hide
12096     */
12097    public void resolvePadding() {
12098        final int resolvedLayoutDirection = getLayoutDirection();
12099
12100        if (!isRtlCompatibilityMode()) {
12101            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12102            // If start / end padding are defined, they will be resolved (hence overriding) to
12103            // left / right or right / left depending on the resolved layout direction.
12104            // If start / end padding are not defined, use the left / right ones.
12105            switch (resolvedLayoutDirection) {
12106                case LAYOUT_DIRECTION_RTL:
12107                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12108                        mUserPaddingRight = mUserPaddingStart;
12109                    } else {
12110                        mUserPaddingRight = mUserPaddingRightInitial;
12111                    }
12112                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12113                        mUserPaddingLeft = mUserPaddingEnd;
12114                    } else {
12115                        mUserPaddingLeft = mUserPaddingLeftInitial;
12116                    }
12117                    break;
12118                case LAYOUT_DIRECTION_LTR:
12119                default:
12120                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12121                        mUserPaddingLeft = mUserPaddingStart;
12122                    } else {
12123                        mUserPaddingLeft = mUserPaddingLeftInitial;
12124                    }
12125                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12126                        mUserPaddingRight = mUserPaddingEnd;
12127                    } else {
12128                        mUserPaddingRight = mUserPaddingRightInitial;
12129                    }
12130            }
12131
12132            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12133        }
12134
12135        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12136        onRtlPropertiesChanged(resolvedLayoutDirection);
12137
12138        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12139    }
12140
12141    /**
12142     * Reset the resolved layout direction.
12143     *
12144     * @hide
12145     */
12146    public void resetResolvedPadding() {
12147        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12148    }
12149
12150    /**
12151     * This is called when the view is detached from a window.  At this point it
12152     * no longer has a surface for drawing.
12153     *
12154     * @see #onAttachedToWindow()
12155     */
12156    protected void onDetachedFromWindow() {
12157        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12158        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12159
12160        removeUnsetPressCallback();
12161        removeLongPressCallback();
12162        removePerformClickCallback();
12163        removeSendViewScrolledAccessibilityEventCallback();
12164
12165        destroyDrawingCache();
12166        destroyLayer(false);
12167
12168        cleanupDraw();
12169
12170        mCurrentAnimation = null;
12171        mCurrentScene = null;
12172    }
12173
12174    private void cleanupDraw() {
12175        if (mAttachInfo != null) {
12176            if (mDisplayList != null) {
12177                mDisplayList.markDirty();
12178                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12179            }
12180            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12181        } else {
12182            // Should never happen
12183            resetDisplayList();
12184        }
12185    }
12186
12187    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12188    }
12189
12190    /**
12191     * @return The number of times this view has been attached to a window
12192     */
12193    protected int getWindowAttachCount() {
12194        return mWindowAttachCount;
12195    }
12196
12197    /**
12198     * Retrieve a unique token identifying the window this view is attached to.
12199     * @return Return the window's token for use in
12200     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12201     */
12202    public IBinder getWindowToken() {
12203        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12204    }
12205
12206    /**
12207     * Retrieve the {@link WindowId} for the window this view is
12208     * currently attached to.
12209     */
12210    public WindowId getWindowId() {
12211        if (mAttachInfo == null) {
12212            return null;
12213        }
12214        if (mAttachInfo.mWindowId == null) {
12215            try {
12216                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12217                        mAttachInfo.mWindowToken);
12218                mAttachInfo.mWindowId = new WindowId(
12219                        mAttachInfo.mIWindowId);
12220            } catch (RemoteException e) {
12221            }
12222        }
12223        return mAttachInfo.mWindowId;
12224    }
12225
12226    /**
12227     * Retrieve a unique token identifying the top-level "real" window of
12228     * the window that this view is attached to.  That is, this is like
12229     * {@link #getWindowToken}, except if the window this view in is a panel
12230     * window (attached to another containing window), then the token of
12231     * the containing window is returned instead.
12232     *
12233     * @return Returns the associated window token, either
12234     * {@link #getWindowToken()} or the containing window's token.
12235     */
12236    public IBinder getApplicationWindowToken() {
12237        AttachInfo ai = mAttachInfo;
12238        if (ai != null) {
12239            IBinder appWindowToken = ai.mPanelParentWindowToken;
12240            if (appWindowToken == null) {
12241                appWindowToken = ai.mWindowToken;
12242            }
12243            return appWindowToken;
12244        }
12245        return null;
12246    }
12247
12248    /**
12249     * Gets the logical display to which the view's window has been attached.
12250     *
12251     * @return The logical display, or null if the view is not currently attached to a window.
12252     */
12253    public Display getDisplay() {
12254        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12255    }
12256
12257    /**
12258     * Retrieve private session object this view hierarchy is using to
12259     * communicate with the window manager.
12260     * @return the session object to communicate with the window manager
12261     */
12262    /*package*/ IWindowSession getWindowSession() {
12263        return mAttachInfo != null ? mAttachInfo.mSession : null;
12264    }
12265
12266    /**
12267     * @param info the {@link android.view.View.AttachInfo} to associated with
12268     *        this view
12269     */
12270    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12271        //System.out.println("Attached! " + this);
12272        mAttachInfo = info;
12273        if (mOverlay != null) {
12274            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12275        }
12276        mWindowAttachCount++;
12277        // We will need to evaluate the drawable state at least once.
12278        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12279        if (mFloatingTreeObserver != null) {
12280            info.mTreeObserver.merge(mFloatingTreeObserver);
12281            mFloatingTreeObserver = null;
12282        }
12283        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12284            mAttachInfo.mScrollContainers.add(this);
12285            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12286        }
12287        performCollectViewAttributes(mAttachInfo, visibility);
12288        onAttachedToWindow();
12289
12290        ListenerInfo li = mListenerInfo;
12291        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12292                li != null ? li.mOnAttachStateChangeListeners : null;
12293        if (listeners != null && listeners.size() > 0) {
12294            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12295            // perform the dispatching. The iterator is a safe guard against listeners that
12296            // could mutate the list by calling the various add/remove methods. This prevents
12297            // the array from being modified while we iterate it.
12298            for (OnAttachStateChangeListener listener : listeners) {
12299                listener.onViewAttachedToWindow(this);
12300            }
12301        }
12302
12303        int vis = info.mWindowVisibility;
12304        if (vis != GONE) {
12305            onWindowVisibilityChanged(vis);
12306        }
12307        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12308            // If nobody has evaluated the drawable state yet, then do it now.
12309            refreshDrawableState();
12310        }
12311        needGlobalAttributesUpdate(false);
12312    }
12313
12314    void dispatchDetachedFromWindow() {
12315        AttachInfo info = mAttachInfo;
12316        if (info != null) {
12317            int vis = info.mWindowVisibility;
12318            if (vis != GONE) {
12319                onWindowVisibilityChanged(GONE);
12320            }
12321        }
12322
12323        onDetachedFromWindow();
12324
12325        ListenerInfo li = mListenerInfo;
12326        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12327                li != null ? li.mOnAttachStateChangeListeners : null;
12328        if (listeners != null && listeners.size() > 0) {
12329            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12330            // perform the dispatching. The iterator is a safe guard against listeners that
12331            // could mutate the list by calling the various add/remove methods. This prevents
12332            // the array from being modified while we iterate it.
12333            for (OnAttachStateChangeListener listener : listeners) {
12334                listener.onViewDetachedFromWindow(this);
12335            }
12336        }
12337
12338        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12339            mAttachInfo.mScrollContainers.remove(this);
12340            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12341        }
12342
12343        mAttachInfo = null;
12344        if (mOverlay != null) {
12345            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12346        }
12347    }
12348
12349    /**
12350     * Store this view hierarchy's frozen state into the given container.
12351     *
12352     * @param container The SparseArray in which to save the view's state.
12353     *
12354     * @see #restoreHierarchyState(android.util.SparseArray)
12355     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12356     * @see #onSaveInstanceState()
12357     */
12358    public void saveHierarchyState(SparseArray<Parcelable> container) {
12359        dispatchSaveInstanceState(container);
12360    }
12361
12362    /**
12363     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12364     * this view and its children. May be overridden to modify how freezing happens to a
12365     * view's children; for example, some views may want to not store state for their children.
12366     *
12367     * @param container The SparseArray in which to save the view's state.
12368     *
12369     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12370     * @see #saveHierarchyState(android.util.SparseArray)
12371     * @see #onSaveInstanceState()
12372     */
12373    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12374        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12375            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12376            Parcelable state = onSaveInstanceState();
12377            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12378                throw new IllegalStateException(
12379                        "Derived class did not call super.onSaveInstanceState()");
12380            }
12381            if (state != null) {
12382                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12383                // + ": " + state);
12384                container.put(mID, state);
12385            }
12386        }
12387    }
12388
12389    /**
12390     * Hook allowing a view to generate a representation of its internal state
12391     * that can later be used to create a new instance with that same state.
12392     * This state should only contain information that is not persistent or can
12393     * not be reconstructed later. For example, you will never store your
12394     * current position on screen because that will be computed again when a
12395     * new instance of the view is placed in its view hierarchy.
12396     * <p>
12397     * Some examples of things you may store here: the current cursor position
12398     * in a text view (but usually not the text itself since that is stored in a
12399     * content provider or other persistent storage), the currently selected
12400     * item in a list view.
12401     *
12402     * @return Returns a Parcelable object containing the view's current dynamic
12403     *         state, or null if there is nothing interesting to save. The
12404     *         default implementation returns null.
12405     * @see #onRestoreInstanceState(android.os.Parcelable)
12406     * @see #saveHierarchyState(android.util.SparseArray)
12407     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12408     * @see #setSaveEnabled(boolean)
12409     */
12410    protected Parcelable onSaveInstanceState() {
12411        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12412        return BaseSavedState.EMPTY_STATE;
12413    }
12414
12415    /**
12416     * Restore this view hierarchy's frozen state from the given container.
12417     *
12418     * @param container The SparseArray which holds previously frozen states.
12419     *
12420     * @see #saveHierarchyState(android.util.SparseArray)
12421     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12422     * @see #onRestoreInstanceState(android.os.Parcelable)
12423     */
12424    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12425        dispatchRestoreInstanceState(container);
12426    }
12427
12428    /**
12429     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12430     * state for this view and its children. May be overridden to modify how restoring
12431     * happens to a view's children; for example, some views may want to not store state
12432     * for their children.
12433     *
12434     * @param container The SparseArray which holds previously saved state.
12435     *
12436     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12437     * @see #restoreHierarchyState(android.util.SparseArray)
12438     * @see #onRestoreInstanceState(android.os.Parcelable)
12439     */
12440    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12441        if (mID != NO_ID) {
12442            Parcelable state = container.get(mID);
12443            if (state != null) {
12444                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12445                // + ": " + state);
12446                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12447                onRestoreInstanceState(state);
12448                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12449                    throw new IllegalStateException(
12450                            "Derived class did not call super.onRestoreInstanceState()");
12451                }
12452            }
12453        }
12454    }
12455
12456    /**
12457     * Hook allowing a view to re-apply a representation of its internal state that had previously
12458     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12459     * null state.
12460     *
12461     * @param state The frozen state that had previously been returned by
12462     *        {@link #onSaveInstanceState}.
12463     *
12464     * @see #onSaveInstanceState()
12465     * @see #restoreHierarchyState(android.util.SparseArray)
12466     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12467     */
12468    protected void onRestoreInstanceState(Parcelable state) {
12469        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12470        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12471            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12472                    + "received " + state.getClass().toString() + " instead. This usually happens "
12473                    + "when two views of different type have the same id in the same hierarchy. "
12474                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12475                    + "other views do not use the same id.");
12476        }
12477    }
12478
12479    /**
12480     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12481     *
12482     * @return the drawing start time in milliseconds
12483     */
12484    public long getDrawingTime() {
12485        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12486    }
12487
12488    /**
12489     * <p>Enables or disables the duplication of the parent's state into this view. When
12490     * duplication is enabled, this view gets its drawable state from its parent rather
12491     * than from its own internal properties.</p>
12492     *
12493     * <p>Note: in the current implementation, setting this property to true after the
12494     * view was added to a ViewGroup might have no effect at all. This property should
12495     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12496     *
12497     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12498     * property is enabled, an exception will be thrown.</p>
12499     *
12500     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12501     * parent, these states should not be affected by this method.</p>
12502     *
12503     * @param enabled True to enable duplication of the parent's drawable state, false
12504     *                to disable it.
12505     *
12506     * @see #getDrawableState()
12507     * @see #isDuplicateParentStateEnabled()
12508     */
12509    public void setDuplicateParentStateEnabled(boolean enabled) {
12510        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12511    }
12512
12513    /**
12514     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12515     *
12516     * @return True if this view's drawable state is duplicated from the parent,
12517     *         false otherwise
12518     *
12519     * @see #getDrawableState()
12520     * @see #setDuplicateParentStateEnabled(boolean)
12521     */
12522    public boolean isDuplicateParentStateEnabled() {
12523        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12524    }
12525
12526    /**
12527     * <p>Specifies the type of layer backing this view. The layer can be
12528     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12529     * {@link #LAYER_TYPE_HARDWARE}.</p>
12530     *
12531     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12532     * instance that controls how the layer is composed on screen. The following
12533     * properties of the paint are taken into account when composing the layer:</p>
12534     * <ul>
12535     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12536     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12537     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12538     * </ul>
12539     *
12540     * <p>If this view has an alpha value set to < 1.0 by calling
12541     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12542     * by this view's alpha value.</p>
12543     *
12544     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12545     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12546     * for more information on when and how to use layers.</p>
12547     *
12548     * @param layerType The type of layer to use with this view, must be one of
12549     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12550     *        {@link #LAYER_TYPE_HARDWARE}
12551     * @param paint The paint used to compose the layer. This argument is optional
12552     *        and can be null. It is ignored when the layer type is
12553     *        {@link #LAYER_TYPE_NONE}
12554     *
12555     * @see #getLayerType()
12556     * @see #LAYER_TYPE_NONE
12557     * @see #LAYER_TYPE_SOFTWARE
12558     * @see #LAYER_TYPE_HARDWARE
12559     * @see #setAlpha(float)
12560     *
12561     * @attr ref android.R.styleable#View_layerType
12562     */
12563    public void setLayerType(int layerType, Paint paint) {
12564        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12565            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12566                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12567        }
12568
12569        if (layerType == mLayerType) {
12570            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12571                mLayerPaint = paint == null ? new Paint() : paint;
12572                invalidateParentCaches();
12573                invalidate(true);
12574            }
12575            return;
12576        }
12577
12578        // Destroy any previous software drawing cache if needed
12579        switch (mLayerType) {
12580            case LAYER_TYPE_HARDWARE:
12581                destroyLayer(false);
12582                // fall through - non-accelerated views may use software layer mechanism instead
12583            case LAYER_TYPE_SOFTWARE:
12584                destroyDrawingCache();
12585                break;
12586            default:
12587                break;
12588        }
12589
12590        mLayerType = layerType;
12591        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12592        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12593        mLocalDirtyRect = layerDisabled ? null : new Rect();
12594
12595        invalidateParentCaches();
12596        invalidate(true);
12597    }
12598
12599    /**
12600     * Updates the {@link Paint} object used with the current layer (used only if the current
12601     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12602     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12603     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12604     * ensure that the view gets redrawn immediately.
12605     *
12606     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12607     * instance that controls how the layer is composed on screen. The following
12608     * properties of the paint are taken into account when composing the layer:</p>
12609     * <ul>
12610     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12611     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12612     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12613     * </ul>
12614     *
12615     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12616     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12617     *
12618     * @param paint The paint used to compose the layer. This argument is optional
12619     *        and can be null. It is ignored when the layer type is
12620     *        {@link #LAYER_TYPE_NONE}
12621     *
12622     * @see #setLayerType(int, android.graphics.Paint)
12623     */
12624    public void setLayerPaint(Paint paint) {
12625        int layerType = getLayerType();
12626        if (layerType != LAYER_TYPE_NONE) {
12627            mLayerPaint = paint == null ? new Paint() : paint;
12628            if (layerType == LAYER_TYPE_HARDWARE) {
12629                HardwareLayer layer = getHardwareLayer();
12630                if (layer != null) {
12631                    layer.setLayerPaint(paint);
12632                }
12633                invalidateViewProperty(false, false);
12634            } else {
12635                invalidate();
12636            }
12637        }
12638    }
12639
12640    /**
12641     * Indicates whether this view has a static layer. A view with layer type
12642     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12643     * dynamic.
12644     */
12645    boolean hasStaticLayer() {
12646        return true;
12647    }
12648
12649    /**
12650     * Indicates what type of layer is currently associated with this view. By default
12651     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12652     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12653     * for more information on the different types of layers.
12654     *
12655     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12656     *         {@link #LAYER_TYPE_HARDWARE}
12657     *
12658     * @see #setLayerType(int, android.graphics.Paint)
12659     * @see #buildLayer()
12660     * @see #LAYER_TYPE_NONE
12661     * @see #LAYER_TYPE_SOFTWARE
12662     * @see #LAYER_TYPE_HARDWARE
12663     */
12664    public int getLayerType() {
12665        return mLayerType;
12666    }
12667
12668    /**
12669     * Forces this view's layer to be created and this view to be rendered
12670     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12671     * invoking this method will have no effect.
12672     *
12673     * This method can for instance be used to render a view into its layer before
12674     * starting an animation. If this view is complex, rendering into the layer
12675     * before starting the animation will avoid skipping frames.
12676     *
12677     * @throws IllegalStateException If this view is not attached to a window
12678     *
12679     * @see #setLayerType(int, android.graphics.Paint)
12680     */
12681    public void buildLayer() {
12682        if (mLayerType == LAYER_TYPE_NONE) return;
12683
12684        final AttachInfo attachInfo = mAttachInfo;
12685        if (attachInfo == null) {
12686            throw new IllegalStateException("This view must be attached to a window first");
12687        }
12688
12689        switch (mLayerType) {
12690            case LAYER_TYPE_HARDWARE:
12691                if (attachInfo.mHardwareRenderer != null &&
12692                        attachInfo.mHardwareRenderer.isEnabled() &&
12693                        attachInfo.mHardwareRenderer.validate()) {
12694                    getHardwareLayer();
12695                    // TODO: We need a better way to handle this case
12696                    // If views have registered pre-draw listeners they need
12697                    // to be notified before we build the layer. Those listeners
12698                    // may however rely on other events to happen first so we
12699                    // cannot just invoke them here until they don't cancel the
12700                    // current frame
12701                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12702                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12703                    }
12704                }
12705                break;
12706            case LAYER_TYPE_SOFTWARE:
12707                buildDrawingCache(true);
12708                break;
12709        }
12710    }
12711
12712    /**
12713     * <p>Returns a hardware layer that can be used to draw this view again
12714     * without executing its draw method.</p>
12715     *
12716     * @return A HardwareLayer ready to render, or null if an error occurred.
12717     */
12718    HardwareLayer getHardwareLayer() {
12719        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12720                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12721            return null;
12722        }
12723
12724        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12725
12726        final int width = mRight - mLeft;
12727        final int height = mBottom - mTop;
12728
12729        if (width == 0 || height == 0) {
12730            return null;
12731        }
12732
12733        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12734            if (mHardwareLayer == null) {
12735                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12736                        width, height, isOpaque());
12737                mLocalDirtyRect.set(0, 0, width, height);
12738            } else {
12739                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12740                    if (mHardwareLayer.resize(width, height)) {
12741                        mLocalDirtyRect.set(0, 0, width, height);
12742                    }
12743                }
12744
12745                // This should not be necessary but applications that change
12746                // the parameters of their background drawable without calling
12747                // this.setBackground(Drawable) can leave the view in a bad state
12748                // (for instance isOpaque() returns true, but the background is
12749                // not opaque.)
12750                computeOpaqueFlags();
12751
12752                final boolean opaque = isOpaque();
12753                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12754                    mHardwareLayer.setOpaque(opaque);
12755                    mLocalDirtyRect.set(0, 0, width, height);
12756                }
12757            }
12758
12759            // The layer is not valid if the underlying GPU resources cannot be allocated
12760            if (!mHardwareLayer.isValid()) {
12761                return null;
12762            }
12763
12764            mHardwareLayer.setLayerPaint(mLayerPaint);
12765            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12766            ViewRootImpl viewRoot = getViewRootImpl();
12767            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12768
12769            mLocalDirtyRect.setEmpty();
12770        }
12771
12772        return mHardwareLayer;
12773    }
12774
12775    /**
12776     * Destroys this View's hardware layer if possible.
12777     *
12778     * @return True if the layer was destroyed, false otherwise.
12779     *
12780     * @see #setLayerType(int, android.graphics.Paint)
12781     * @see #LAYER_TYPE_HARDWARE
12782     */
12783    boolean destroyLayer(boolean valid) {
12784        if (mHardwareLayer != null) {
12785            AttachInfo info = mAttachInfo;
12786            if (info != null && info.mHardwareRenderer != null &&
12787                    info.mHardwareRenderer.isEnabled() &&
12788                    (valid || info.mHardwareRenderer.validate())) {
12789
12790                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12791                mHardwareLayer.destroy();
12792                mHardwareLayer = null;
12793
12794                invalidate(true);
12795                invalidateParentCaches();
12796            }
12797            return true;
12798        }
12799        return false;
12800    }
12801
12802    /**
12803     * Destroys all hardware rendering resources. This method is invoked
12804     * when the system needs to reclaim resources. Upon execution of this
12805     * method, you should free any OpenGL resources created by the view.
12806     *
12807     * Note: you <strong>must</strong> call
12808     * <code>super.destroyHardwareResources()</code> when overriding
12809     * this method.
12810     *
12811     * @hide
12812     */
12813    protected void destroyHardwareResources() {
12814        resetDisplayList();
12815        destroyLayer(true);
12816    }
12817
12818    /**
12819     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12820     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12821     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12822     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12823     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12824     * null.</p>
12825     *
12826     * <p>Enabling the drawing cache is similar to
12827     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12828     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12829     * drawing cache has no effect on rendering because the system uses a different mechanism
12830     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12831     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12832     * for information on how to enable software and hardware layers.</p>
12833     *
12834     * <p>This API can be used to manually generate
12835     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12836     * {@link #getDrawingCache()}.</p>
12837     *
12838     * @param enabled true to enable the drawing cache, false otherwise
12839     *
12840     * @see #isDrawingCacheEnabled()
12841     * @see #getDrawingCache()
12842     * @see #buildDrawingCache()
12843     * @see #setLayerType(int, android.graphics.Paint)
12844     */
12845    public void setDrawingCacheEnabled(boolean enabled) {
12846        mCachingFailed = false;
12847        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12848    }
12849
12850    /**
12851     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12852     *
12853     * @return true if the drawing cache is enabled
12854     *
12855     * @see #setDrawingCacheEnabled(boolean)
12856     * @see #getDrawingCache()
12857     */
12858    @ViewDebug.ExportedProperty(category = "drawing")
12859    public boolean isDrawingCacheEnabled() {
12860        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12861    }
12862
12863    /**
12864     * Debugging utility which recursively outputs the dirty state of a view and its
12865     * descendants.
12866     *
12867     * @hide
12868     */
12869    @SuppressWarnings({"UnusedDeclaration"})
12870    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12871        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12872                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12873                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12874                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12875        if (clear) {
12876            mPrivateFlags &= clearMask;
12877        }
12878        if (this instanceof ViewGroup) {
12879            ViewGroup parent = (ViewGroup) this;
12880            final int count = parent.getChildCount();
12881            for (int i = 0; i < count; i++) {
12882                final View child = parent.getChildAt(i);
12883                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12884            }
12885        }
12886    }
12887
12888    /**
12889     * This method is used by ViewGroup to cause its children to restore or recreate their
12890     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12891     * to recreate its own display list, which would happen if it went through the normal
12892     * draw/dispatchDraw mechanisms.
12893     *
12894     * @hide
12895     */
12896    protected void dispatchGetDisplayList() {}
12897
12898    /**
12899     * A view that is not attached or hardware accelerated cannot create a display list.
12900     * This method checks these conditions and returns the appropriate result.
12901     *
12902     * @return true if view has the ability to create a display list, false otherwise.
12903     *
12904     * @hide
12905     */
12906    public boolean canHaveDisplayList() {
12907        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12908    }
12909
12910    /**
12911     * @return The {@link HardwareRenderer} associated with that view or null if
12912     *         hardware rendering is not supported or this view is not attached
12913     *         to a window.
12914     *
12915     * @hide
12916     */
12917    public HardwareRenderer getHardwareRenderer() {
12918        if (mAttachInfo != null) {
12919            return mAttachInfo.mHardwareRenderer;
12920        }
12921        return null;
12922    }
12923
12924    /**
12925     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12926     * Otherwise, the same display list will be returned (after having been rendered into
12927     * along the way, depending on the invalidation state of the view).
12928     *
12929     * @param displayList The previous version of this displayList, could be null.
12930     * @param isLayer Whether the requester of the display list is a layer. If so,
12931     * the view will avoid creating a layer inside the resulting display list.
12932     * @return A new or reused DisplayList object.
12933     */
12934    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12935        if (!canHaveDisplayList()) {
12936            return null;
12937        }
12938
12939        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12940                displayList == null || !displayList.isValid() ||
12941                (!isLayer && mRecreateDisplayList))) {
12942            // Don't need to recreate the display list, just need to tell our
12943            // children to restore/recreate theirs
12944            if (displayList != null && displayList.isValid() &&
12945                    !isLayer && !mRecreateDisplayList) {
12946                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12947                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12948                dispatchGetDisplayList();
12949
12950                return displayList;
12951            }
12952
12953            if (!isLayer) {
12954                // If we got here, we're recreating it. Mark it as such to ensure that
12955                // we copy in child display lists into ours in drawChild()
12956                mRecreateDisplayList = true;
12957            }
12958            if (displayList == null) {
12959                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12960                // If we're creating a new display list, make sure our parent gets invalidated
12961                // since they will need to recreate their display list to account for this
12962                // new child display list.
12963                invalidateParentCaches();
12964            }
12965
12966            boolean caching = false;
12967            int width = mRight - mLeft;
12968            int height = mBottom - mTop;
12969            int layerType = getLayerType();
12970
12971            final HardwareCanvas canvas = displayList.start(width, height);
12972
12973            try {
12974                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12975                    if (layerType == LAYER_TYPE_HARDWARE) {
12976                        final HardwareLayer layer = getHardwareLayer();
12977                        if (layer != null && layer.isValid()) {
12978                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12979                        } else {
12980                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12981                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12982                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12983                        }
12984                        caching = true;
12985                    } else {
12986                        buildDrawingCache(true);
12987                        Bitmap cache = getDrawingCache(true);
12988                        if (cache != null) {
12989                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12990                            caching = true;
12991                        }
12992                    }
12993                } else {
12994
12995                    computeScroll();
12996
12997                    canvas.translate(-mScrollX, -mScrollY);
12998                    if (!isLayer) {
12999                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13000                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13001                    }
13002
13003                    // Fast path for layouts with no backgrounds
13004                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13005                        dispatchDraw(canvas);
13006                        if (mOverlay != null && !mOverlay.isEmpty()) {
13007                            mOverlay.getOverlayView().draw(canvas);
13008                        }
13009                    } else {
13010                        draw(canvas);
13011                    }
13012                }
13013            } finally {
13014                displayList.end();
13015                displayList.setCaching(caching);
13016                if (isLayer) {
13017                    displayList.setLeftTopRightBottom(0, 0, width, height);
13018                } else {
13019                    setDisplayListProperties(displayList);
13020                }
13021            }
13022        } else if (!isLayer) {
13023            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13024            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13025        }
13026
13027        return displayList;
13028    }
13029
13030    /**
13031     * Get the DisplayList for the HardwareLayer
13032     *
13033     * @param layer The HardwareLayer whose DisplayList we want
13034     * @return A DisplayList fopr the specified HardwareLayer
13035     */
13036    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13037        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13038        layer.setDisplayList(displayList);
13039        return displayList;
13040    }
13041
13042
13043    /**
13044     * <p>Returns a display list that can be used to draw this view again
13045     * without executing its draw method.</p>
13046     *
13047     * @return A DisplayList ready to replay, or null if caching is not enabled.
13048     *
13049     * @hide
13050     */
13051    public DisplayList getDisplayList() {
13052        mDisplayList = getDisplayList(mDisplayList, false);
13053        return mDisplayList;
13054    }
13055
13056    private void clearDisplayList() {
13057        if (mDisplayList != null) {
13058            mDisplayList.clear();
13059        }
13060    }
13061
13062    private void resetDisplayList() {
13063        if (mDisplayList != null) {
13064            mDisplayList.reset();
13065        }
13066    }
13067
13068    /**
13069     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13070     *
13071     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13072     *
13073     * @see #getDrawingCache(boolean)
13074     */
13075    public Bitmap getDrawingCache() {
13076        return getDrawingCache(false);
13077    }
13078
13079    /**
13080     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13081     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13082     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13083     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13084     * request the drawing cache by calling this method and draw it on screen if the
13085     * returned bitmap is not null.</p>
13086     *
13087     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13088     * this method will create a bitmap of the same size as this view. Because this bitmap
13089     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13090     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13091     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13092     * size than the view. This implies that your application must be able to handle this
13093     * size.</p>
13094     *
13095     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13096     *        the current density of the screen when the application is in compatibility
13097     *        mode.
13098     *
13099     * @return A bitmap representing this view or null if cache is disabled.
13100     *
13101     * @see #setDrawingCacheEnabled(boolean)
13102     * @see #isDrawingCacheEnabled()
13103     * @see #buildDrawingCache(boolean)
13104     * @see #destroyDrawingCache()
13105     */
13106    public Bitmap getDrawingCache(boolean autoScale) {
13107        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13108            return null;
13109        }
13110        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13111            buildDrawingCache(autoScale);
13112        }
13113        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13114    }
13115
13116    /**
13117     * <p>Frees the resources used by the drawing cache. If you call
13118     * {@link #buildDrawingCache()} manually without calling
13119     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13120     * should cleanup the cache with this method afterwards.</p>
13121     *
13122     * @see #setDrawingCacheEnabled(boolean)
13123     * @see #buildDrawingCache()
13124     * @see #getDrawingCache()
13125     */
13126    public void destroyDrawingCache() {
13127        if (mDrawingCache != null) {
13128            mDrawingCache.recycle();
13129            mDrawingCache = null;
13130        }
13131        if (mUnscaledDrawingCache != null) {
13132            mUnscaledDrawingCache.recycle();
13133            mUnscaledDrawingCache = null;
13134        }
13135    }
13136
13137    /**
13138     * Setting a solid background color for the drawing cache's bitmaps will improve
13139     * performance and memory usage. Note, though that this should only be used if this
13140     * view will always be drawn on top of a solid color.
13141     *
13142     * @param color The background color to use for the drawing cache's bitmap
13143     *
13144     * @see #setDrawingCacheEnabled(boolean)
13145     * @see #buildDrawingCache()
13146     * @see #getDrawingCache()
13147     */
13148    public void setDrawingCacheBackgroundColor(int color) {
13149        if (color != mDrawingCacheBackgroundColor) {
13150            mDrawingCacheBackgroundColor = color;
13151            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13152        }
13153    }
13154
13155    /**
13156     * @see #setDrawingCacheBackgroundColor(int)
13157     *
13158     * @return The background color to used for the drawing cache's bitmap
13159     */
13160    public int getDrawingCacheBackgroundColor() {
13161        return mDrawingCacheBackgroundColor;
13162    }
13163
13164    /**
13165     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13166     *
13167     * @see #buildDrawingCache(boolean)
13168     */
13169    public void buildDrawingCache() {
13170        buildDrawingCache(false);
13171    }
13172
13173    /**
13174     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13175     *
13176     * <p>If you call {@link #buildDrawingCache()} manually without calling
13177     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13178     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13179     *
13180     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13181     * this method will create a bitmap of the same size as this view. Because this bitmap
13182     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13183     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13184     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13185     * size than the view. This implies that your application must be able to handle this
13186     * size.</p>
13187     *
13188     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13189     * you do not need the drawing cache bitmap, calling this method will increase memory
13190     * usage and cause the view to be rendered in software once, thus negatively impacting
13191     * performance.</p>
13192     *
13193     * @see #getDrawingCache()
13194     * @see #destroyDrawingCache()
13195     */
13196    public void buildDrawingCache(boolean autoScale) {
13197        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13198                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13199            mCachingFailed = false;
13200
13201            int width = mRight - mLeft;
13202            int height = mBottom - mTop;
13203
13204            final AttachInfo attachInfo = mAttachInfo;
13205            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13206
13207            if (autoScale && scalingRequired) {
13208                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13209                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13210            }
13211
13212            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13213            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13214            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13215
13216            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13217            final long drawingCacheSize =
13218                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13219            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13220                if (width > 0 && height > 0) {
13221                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13222                            + projectedBitmapSize + " bytes, only "
13223                            + drawingCacheSize + " available");
13224                }
13225                destroyDrawingCache();
13226                mCachingFailed = true;
13227                return;
13228            }
13229
13230            boolean clear = true;
13231            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13232
13233            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13234                Bitmap.Config quality;
13235                if (!opaque) {
13236                    // Never pick ARGB_4444 because it looks awful
13237                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13238                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13239                        case DRAWING_CACHE_QUALITY_AUTO:
13240                            quality = Bitmap.Config.ARGB_8888;
13241                            break;
13242                        case DRAWING_CACHE_QUALITY_LOW:
13243                            quality = Bitmap.Config.ARGB_8888;
13244                            break;
13245                        case DRAWING_CACHE_QUALITY_HIGH:
13246                            quality = Bitmap.Config.ARGB_8888;
13247                            break;
13248                        default:
13249                            quality = Bitmap.Config.ARGB_8888;
13250                            break;
13251                    }
13252                } else {
13253                    // Optimization for translucent windows
13254                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13255                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13256                }
13257
13258                // Try to cleanup memory
13259                if (bitmap != null) bitmap.recycle();
13260
13261                try {
13262                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13263                            width, height, quality);
13264                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13265                    if (autoScale) {
13266                        mDrawingCache = bitmap;
13267                    } else {
13268                        mUnscaledDrawingCache = bitmap;
13269                    }
13270                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13271                } catch (OutOfMemoryError e) {
13272                    // If there is not enough memory to create the bitmap cache, just
13273                    // ignore the issue as bitmap caches are not required to draw the
13274                    // view hierarchy
13275                    if (autoScale) {
13276                        mDrawingCache = null;
13277                    } else {
13278                        mUnscaledDrawingCache = null;
13279                    }
13280                    mCachingFailed = true;
13281                    return;
13282                }
13283
13284                clear = drawingCacheBackgroundColor != 0;
13285            }
13286
13287            Canvas canvas;
13288            if (attachInfo != null) {
13289                canvas = attachInfo.mCanvas;
13290                if (canvas == null) {
13291                    canvas = new Canvas();
13292                }
13293                canvas.setBitmap(bitmap);
13294                // Temporarily clobber the cached Canvas in case one of our children
13295                // is also using a drawing cache. Without this, the children would
13296                // steal the canvas by attaching their own bitmap to it and bad, bad
13297                // thing would happen (invisible views, corrupted drawings, etc.)
13298                attachInfo.mCanvas = null;
13299            } else {
13300                // This case should hopefully never or seldom happen
13301                canvas = new Canvas(bitmap);
13302            }
13303
13304            if (clear) {
13305                bitmap.eraseColor(drawingCacheBackgroundColor);
13306            }
13307
13308            computeScroll();
13309            final int restoreCount = canvas.save();
13310
13311            if (autoScale && scalingRequired) {
13312                final float scale = attachInfo.mApplicationScale;
13313                canvas.scale(scale, scale);
13314            }
13315
13316            canvas.translate(-mScrollX, -mScrollY);
13317
13318            mPrivateFlags |= PFLAG_DRAWN;
13319            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13320                    mLayerType != LAYER_TYPE_NONE) {
13321                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13322            }
13323
13324            // Fast path for layouts with no backgrounds
13325            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13326                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13327                dispatchDraw(canvas);
13328                if (mOverlay != null && !mOverlay.isEmpty()) {
13329                    mOverlay.getOverlayView().draw(canvas);
13330                }
13331            } else {
13332                draw(canvas);
13333            }
13334
13335            canvas.restoreToCount(restoreCount);
13336            canvas.setBitmap(null);
13337
13338            if (attachInfo != null) {
13339                // Restore the cached Canvas for our siblings
13340                attachInfo.mCanvas = canvas;
13341            }
13342        }
13343    }
13344
13345    /**
13346     * Create a snapshot of the view into a bitmap.  We should probably make
13347     * some form of this public, but should think about the API.
13348     */
13349    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13350        int width = mRight - mLeft;
13351        int height = mBottom - mTop;
13352
13353        final AttachInfo attachInfo = mAttachInfo;
13354        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13355        width = (int) ((width * scale) + 0.5f);
13356        height = (int) ((height * scale) + 0.5f);
13357
13358        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13359                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13360        if (bitmap == null) {
13361            throw new OutOfMemoryError();
13362        }
13363
13364        Resources resources = getResources();
13365        if (resources != null) {
13366            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13367        }
13368
13369        Canvas canvas;
13370        if (attachInfo != null) {
13371            canvas = attachInfo.mCanvas;
13372            if (canvas == null) {
13373                canvas = new Canvas();
13374            }
13375            canvas.setBitmap(bitmap);
13376            // Temporarily clobber the cached Canvas in case one of our children
13377            // is also using a drawing cache. Without this, the children would
13378            // steal the canvas by attaching their own bitmap to it and bad, bad
13379            // things would happen (invisible views, corrupted drawings, etc.)
13380            attachInfo.mCanvas = null;
13381        } else {
13382            // This case should hopefully never or seldom happen
13383            canvas = new Canvas(bitmap);
13384        }
13385
13386        if ((backgroundColor & 0xff000000) != 0) {
13387            bitmap.eraseColor(backgroundColor);
13388        }
13389
13390        computeScroll();
13391        final int restoreCount = canvas.save();
13392        canvas.scale(scale, scale);
13393        canvas.translate(-mScrollX, -mScrollY);
13394
13395        // Temporarily remove the dirty mask
13396        int flags = mPrivateFlags;
13397        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13398
13399        // Fast path for layouts with no backgrounds
13400        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13401            dispatchDraw(canvas);
13402        } else {
13403            draw(canvas);
13404        }
13405
13406        mPrivateFlags = flags;
13407
13408        canvas.restoreToCount(restoreCount);
13409        canvas.setBitmap(null);
13410
13411        if (attachInfo != null) {
13412            // Restore the cached Canvas for our siblings
13413            attachInfo.mCanvas = canvas;
13414        }
13415
13416        return bitmap;
13417    }
13418
13419    /**
13420     * Indicates whether this View is currently in edit mode. A View is usually
13421     * in edit mode when displayed within a developer tool. For instance, if
13422     * this View is being drawn by a visual user interface builder, this method
13423     * should return true.
13424     *
13425     * Subclasses should check the return value of this method to provide
13426     * different behaviors if their normal behavior might interfere with the
13427     * host environment. For instance: the class spawns a thread in its
13428     * constructor, the drawing code relies on device-specific features, etc.
13429     *
13430     * This method is usually checked in the drawing code of custom widgets.
13431     *
13432     * @return True if this View is in edit mode, false otherwise.
13433     */
13434    public boolean isInEditMode() {
13435        return false;
13436    }
13437
13438    /**
13439     * If the View draws content inside its padding and enables fading edges,
13440     * it needs to support padding offsets. Padding offsets are added to the
13441     * fading edges to extend the length of the fade so that it covers pixels
13442     * drawn inside the padding.
13443     *
13444     * Subclasses of this class should override this method if they need
13445     * to draw content inside the padding.
13446     *
13447     * @return True if padding offset must be applied, false otherwise.
13448     *
13449     * @see #getLeftPaddingOffset()
13450     * @see #getRightPaddingOffset()
13451     * @see #getTopPaddingOffset()
13452     * @see #getBottomPaddingOffset()
13453     *
13454     * @since CURRENT
13455     */
13456    protected boolean isPaddingOffsetRequired() {
13457        return false;
13458    }
13459
13460    /**
13461     * Amount by which to extend the left fading region. Called only when
13462     * {@link #isPaddingOffsetRequired()} returns true.
13463     *
13464     * @return The left padding offset in pixels.
13465     *
13466     * @see #isPaddingOffsetRequired()
13467     *
13468     * @since CURRENT
13469     */
13470    protected int getLeftPaddingOffset() {
13471        return 0;
13472    }
13473
13474    /**
13475     * Amount by which to extend the right fading region. Called only when
13476     * {@link #isPaddingOffsetRequired()} returns true.
13477     *
13478     * @return The right padding offset in pixels.
13479     *
13480     * @see #isPaddingOffsetRequired()
13481     *
13482     * @since CURRENT
13483     */
13484    protected int getRightPaddingOffset() {
13485        return 0;
13486    }
13487
13488    /**
13489     * Amount by which to extend the top fading region. Called only when
13490     * {@link #isPaddingOffsetRequired()} returns true.
13491     *
13492     * @return The top padding offset in pixels.
13493     *
13494     * @see #isPaddingOffsetRequired()
13495     *
13496     * @since CURRENT
13497     */
13498    protected int getTopPaddingOffset() {
13499        return 0;
13500    }
13501
13502    /**
13503     * Amount by which to extend the bottom fading region. Called only when
13504     * {@link #isPaddingOffsetRequired()} returns true.
13505     *
13506     * @return The bottom padding offset in pixels.
13507     *
13508     * @see #isPaddingOffsetRequired()
13509     *
13510     * @since CURRENT
13511     */
13512    protected int getBottomPaddingOffset() {
13513        return 0;
13514    }
13515
13516    /**
13517     * @hide
13518     * @param offsetRequired
13519     */
13520    protected int getFadeTop(boolean offsetRequired) {
13521        int top = mPaddingTop;
13522        if (offsetRequired) top += getTopPaddingOffset();
13523        return top;
13524    }
13525
13526    /**
13527     * @hide
13528     * @param offsetRequired
13529     */
13530    protected int getFadeHeight(boolean offsetRequired) {
13531        int padding = mPaddingTop;
13532        if (offsetRequired) padding += getTopPaddingOffset();
13533        return mBottom - mTop - mPaddingBottom - padding;
13534    }
13535
13536    /**
13537     * <p>Indicates whether this view is attached to a hardware accelerated
13538     * window or not.</p>
13539     *
13540     * <p>Even if this method returns true, it does not mean that every call
13541     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13542     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13543     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13544     * window is hardware accelerated,
13545     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13546     * return false, and this method will return true.</p>
13547     *
13548     * @return True if the view is attached to a window and the window is
13549     *         hardware accelerated; false in any other case.
13550     */
13551    public boolean isHardwareAccelerated() {
13552        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13553    }
13554
13555    /**
13556     * Sets a rectangular area on this view to which the view will be clipped
13557     * when it is drawn. Setting the value to null will remove the clip bounds
13558     * and the view will draw normally, using its full bounds.
13559     *
13560     * @param clipBounds The rectangular area, in the local coordinates of
13561     * this view, to which future drawing operations will be clipped.
13562     */
13563    public void setClipBounds(Rect clipBounds) {
13564        if (clipBounds != null) {
13565            if (clipBounds.equals(mClipBounds)) {
13566                return;
13567            }
13568            if (mClipBounds == null) {
13569                invalidate();
13570                mClipBounds = new Rect(clipBounds);
13571            } else {
13572                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13573                        Math.min(mClipBounds.top, clipBounds.top),
13574                        Math.max(mClipBounds.right, clipBounds.right),
13575                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13576                mClipBounds.set(clipBounds);
13577            }
13578        } else {
13579            if (mClipBounds != null) {
13580                invalidate();
13581                mClipBounds = null;
13582            }
13583        }
13584    }
13585
13586    /**
13587     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13588     *
13589     * @return A copy of the current clip bounds if clip bounds are set,
13590     * otherwise null.
13591     */
13592    public Rect getClipBounds() {
13593        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13594    }
13595
13596    /**
13597     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13598     * case of an active Animation being run on the view.
13599     */
13600    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13601            Animation a, boolean scalingRequired) {
13602        Transformation invalidationTransform;
13603        final int flags = parent.mGroupFlags;
13604        final boolean initialized = a.isInitialized();
13605        if (!initialized) {
13606            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13607            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13608            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13609            onAnimationStart();
13610        }
13611
13612        final Transformation t = parent.getChildTransformation();
13613        boolean more = a.getTransformation(drawingTime, t, 1f);
13614        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13615            if (parent.mInvalidationTransformation == null) {
13616                parent.mInvalidationTransformation = new Transformation();
13617            }
13618            invalidationTransform = parent.mInvalidationTransformation;
13619            a.getTransformation(drawingTime, invalidationTransform, 1f);
13620        } else {
13621            invalidationTransform = t;
13622        }
13623
13624        if (more) {
13625            if (!a.willChangeBounds()) {
13626                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13627                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13628                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13629                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13630                    // The child need to draw an animation, potentially offscreen, so
13631                    // make sure we do not cancel invalidate requests
13632                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13633                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13634                }
13635            } else {
13636                if (parent.mInvalidateRegion == null) {
13637                    parent.mInvalidateRegion = new RectF();
13638                }
13639                final RectF region = parent.mInvalidateRegion;
13640                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13641                        invalidationTransform);
13642
13643                // The child need to draw an animation, potentially offscreen, so
13644                // make sure we do not cancel invalidate requests
13645                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13646
13647                final int left = mLeft + (int) region.left;
13648                final int top = mTop + (int) region.top;
13649                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13650                        top + (int) (region.height() + .5f));
13651            }
13652        }
13653        return more;
13654    }
13655
13656    /**
13657     * This method is called by getDisplayList() when a display list is created or re-rendered.
13658     * It sets or resets the current value of all properties on that display list (resetting is
13659     * necessary when a display list is being re-created, because we need to make sure that
13660     * previously-set transform values
13661     */
13662    void setDisplayListProperties(DisplayList displayList) {
13663        if (displayList != null) {
13664            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13665            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13666            if (mParent instanceof ViewGroup) {
13667                displayList.setClipToBounds(
13668                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13669            }
13670            float alpha = 1;
13671            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13672                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13673                ViewGroup parentVG = (ViewGroup) mParent;
13674                final Transformation t = parentVG.getChildTransformation();
13675                if (parentVG.getChildStaticTransformation(this, t)) {
13676                    final int transformType = t.getTransformationType();
13677                    if (transformType != Transformation.TYPE_IDENTITY) {
13678                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13679                            alpha = t.getAlpha();
13680                        }
13681                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13682                            displayList.setMatrix(t.getMatrix());
13683                        }
13684                    }
13685                }
13686            }
13687            if (mTransformationInfo != null) {
13688                alpha *= mTransformationInfo.mAlpha;
13689                if (alpha < 1) {
13690                    final int multipliedAlpha = (int) (255 * alpha);
13691                    if (onSetAlpha(multipliedAlpha)) {
13692                        alpha = 1;
13693                    }
13694                }
13695                displayList.setTransformationInfo(alpha,
13696                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13697                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13698                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13699                        mTransformationInfo.mScaleY);
13700                if (mTransformationInfo.mCamera == null) {
13701                    mTransformationInfo.mCamera = new Camera();
13702                    mTransformationInfo.matrix3D = new Matrix();
13703                }
13704                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13705                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13706                    displayList.setPivotX(getPivotX());
13707                    displayList.setPivotY(getPivotY());
13708                }
13709            } else if (alpha < 1) {
13710                displayList.setAlpha(alpha);
13711            }
13712        }
13713    }
13714
13715    /**
13716     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13717     * This draw() method is an implementation detail and is not intended to be overridden or
13718     * to be called from anywhere else other than ViewGroup.drawChild().
13719     */
13720    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13721        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13722        boolean more = false;
13723        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13724        final int flags = parent.mGroupFlags;
13725
13726        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13727            parent.getChildTransformation().clear();
13728            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13729        }
13730
13731        Transformation transformToApply = null;
13732        boolean concatMatrix = false;
13733
13734        boolean scalingRequired = false;
13735        boolean caching;
13736        int layerType = getLayerType();
13737
13738        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13739        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13740                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13741            caching = true;
13742            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13743            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13744        } else {
13745            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13746        }
13747
13748        final Animation a = getAnimation();
13749        if (a != null) {
13750            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13751            concatMatrix = a.willChangeTransformationMatrix();
13752            if (concatMatrix) {
13753                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13754            }
13755            transformToApply = parent.getChildTransformation();
13756        } else {
13757            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13758                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13759                // No longer animating: clear out old animation matrix
13760                mDisplayList.setAnimationMatrix(null);
13761                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13762            }
13763            if (!useDisplayListProperties &&
13764                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13765                final Transformation t = parent.getChildTransformation();
13766                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13767                if (hasTransform) {
13768                    final int transformType = t.getTransformationType();
13769                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13770                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13771                }
13772            }
13773        }
13774
13775        concatMatrix |= !childHasIdentityMatrix;
13776
13777        // Sets the flag as early as possible to allow draw() implementations
13778        // to call invalidate() successfully when doing animations
13779        mPrivateFlags |= PFLAG_DRAWN;
13780
13781        if (!concatMatrix &&
13782                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13783                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13784                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13785                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13786            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13787            return more;
13788        }
13789        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13790
13791        if (hardwareAccelerated) {
13792            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13793            // retain the flag's value temporarily in the mRecreateDisplayList flag
13794            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13795            mPrivateFlags &= ~PFLAG_INVALIDATED;
13796        }
13797
13798        DisplayList displayList = null;
13799        Bitmap cache = null;
13800        boolean hasDisplayList = false;
13801        if (caching) {
13802            if (!hardwareAccelerated) {
13803                if (layerType != LAYER_TYPE_NONE) {
13804                    layerType = LAYER_TYPE_SOFTWARE;
13805                    buildDrawingCache(true);
13806                }
13807                cache = getDrawingCache(true);
13808            } else {
13809                switch (layerType) {
13810                    case LAYER_TYPE_SOFTWARE:
13811                        if (useDisplayListProperties) {
13812                            hasDisplayList = canHaveDisplayList();
13813                        } else {
13814                            buildDrawingCache(true);
13815                            cache = getDrawingCache(true);
13816                        }
13817                        break;
13818                    case LAYER_TYPE_HARDWARE:
13819                        if (useDisplayListProperties) {
13820                            hasDisplayList = canHaveDisplayList();
13821                        }
13822                        break;
13823                    case LAYER_TYPE_NONE:
13824                        // Delay getting the display list until animation-driven alpha values are
13825                        // set up and possibly passed on to the view
13826                        hasDisplayList = canHaveDisplayList();
13827                        break;
13828                }
13829            }
13830        }
13831        useDisplayListProperties &= hasDisplayList;
13832        if (useDisplayListProperties) {
13833            displayList = getDisplayList();
13834            if (!displayList.isValid()) {
13835                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13836                // to getDisplayList(), the display list will be marked invalid and we should not
13837                // try to use it again.
13838                displayList = null;
13839                hasDisplayList = false;
13840                useDisplayListProperties = false;
13841            }
13842        }
13843
13844        int sx = 0;
13845        int sy = 0;
13846        if (!hasDisplayList) {
13847            computeScroll();
13848            sx = mScrollX;
13849            sy = mScrollY;
13850        }
13851
13852        final boolean hasNoCache = cache == null || hasDisplayList;
13853        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13854                layerType != LAYER_TYPE_HARDWARE;
13855
13856        int restoreTo = -1;
13857        if (!useDisplayListProperties || transformToApply != null) {
13858            restoreTo = canvas.save();
13859        }
13860        if (offsetForScroll) {
13861            canvas.translate(mLeft - sx, mTop - sy);
13862        } else {
13863            if (!useDisplayListProperties) {
13864                canvas.translate(mLeft, mTop);
13865            }
13866            if (scalingRequired) {
13867                if (useDisplayListProperties) {
13868                    // TODO: Might not need this if we put everything inside the DL
13869                    restoreTo = canvas.save();
13870                }
13871                // mAttachInfo cannot be null, otherwise scalingRequired == false
13872                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13873                canvas.scale(scale, scale);
13874            }
13875        }
13876
13877        float alpha = useDisplayListProperties ? 1 : getAlpha();
13878        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13879                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13880            if (transformToApply != null || !childHasIdentityMatrix) {
13881                int transX = 0;
13882                int transY = 0;
13883
13884                if (offsetForScroll) {
13885                    transX = -sx;
13886                    transY = -sy;
13887                }
13888
13889                if (transformToApply != null) {
13890                    if (concatMatrix) {
13891                        if (useDisplayListProperties) {
13892                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13893                        } else {
13894                            // Undo the scroll translation, apply the transformation matrix,
13895                            // then redo the scroll translate to get the correct result.
13896                            canvas.translate(-transX, -transY);
13897                            canvas.concat(transformToApply.getMatrix());
13898                            canvas.translate(transX, transY);
13899                        }
13900                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13901                    }
13902
13903                    float transformAlpha = transformToApply.getAlpha();
13904                    if (transformAlpha < 1) {
13905                        alpha *= transformAlpha;
13906                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13907                    }
13908                }
13909
13910                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13911                    canvas.translate(-transX, -transY);
13912                    canvas.concat(getMatrix());
13913                    canvas.translate(transX, transY);
13914                }
13915            }
13916
13917            // Deal with alpha if it is or used to be <1
13918            if (alpha < 1 ||
13919                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13920                if (alpha < 1) {
13921                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13922                } else {
13923                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13924                }
13925                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13926                if (hasNoCache) {
13927                    final int multipliedAlpha = (int) (255 * alpha);
13928                    if (!onSetAlpha(multipliedAlpha)) {
13929                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13930                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13931                                layerType != LAYER_TYPE_NONE) {
13932                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13933                        }
13934                        if (useDisplayListProperties) {
13935                            displayList.setAlpha(alpha * getAlpha());
13936                        } else  if (layerType == LAYER_TYPE_NONE) {
13937                            final int scrollX = hasDisplayList ? 0 : sx;
13938                            final int scrollY = hasDisplayList ? 0 : sy;
13939                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13940                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13941                        }
13942                    } else {
13943                        // Alpha is handled by the child directly, clobber the layer's alpha
13944                        mPrivateFlags |= PFLAG_ALPHA_SET;
13945                    }
13946                }
13947            }
13948        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13949            onSetAlpha(255);
13950            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13951        }
13952
13953        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13954                !useDisplayListProperties && cache == null) {
13955            if (offsetForScroll) {
13956                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13957            } else {
13958                if (!scalingRequired || cache == null) {
13959                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13960                } else {
13961                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13962                }
13963            }
13964        }
13965
13966        if (!useDisplayListProperties && hasDisplayList) {
13967            displayList = getDisplayList();
13968            if (!displayList.isValid()) {
13969                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13970                // to getDisplayList(), the display list will be marked invalid and we should not
13971                // try to use it again.
13972                displayList = null;
13973                hasDisplayList = false;
13974            }
13975        }
13976
13977        if (hasNoCache) {
13978            boolean layerRendered = false;
13979            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13980                final HardwareLayer layer = getHardwareLayer();
13981                if (layer != null && layer.isValid()) {
13982                    mLayerPaint.setAlpha((int) (alpha * 255));
13983                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13984                    layerRendered = true;
13985                } else {
13986                    final int scrollX = hasDisplayList ? 0 : sx;
13987                    final int scrollY = hasDisplayList ? 0 : sy;
13988                    canvas.saveLayer(scrollX, scrollY,
13989                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13990                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13991                }
13992            }
13993
13994            if (!layerRendered) {
13995                if (!hasDisplayList) {
13996                    // Fast path for layouts with no backgrounds
13997                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13998                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13999                        dispatchDraw(canvas);
14000                    } else {
14001                        draw(canvas);
14002                    }
14003                } else {
14004                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14005                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14006                }
14007            }
14008        } else if (cache != null) {
14009            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14010            Paint cachePaint;
14011
14012            if (layerType == LAYER_TYPE_NONE) {
14013                cachePaint = parent.mCachePaint;
14014                if (cachePaint == null) {
14015                    cachePaint = new Paint();
14016                    cachePaint.setDither(false);
14017                    parent.mCachePaint = cachePaint;
14018                }
14019                if (alpha < 1) {
14020                    cachePaint.setAlpha((int) (alpha * 255));
14021                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14022                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14023                    cachePaint.setAlpha(255);
14024                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14025                }
14026            } else {
14027                cachePaint = mLayerPaint;
14028                cachePaint.setAlpha((int) (alpha * 255));
14029            }
14030            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14031        }
14032
14033        if (restoreTo >= 0) {
14034            canvas.restoreToCount(restoreTo);
14035        }
14036
14037        if (a != null && !more) {
14038            if (!hardwareAccelerated && !a.getFillAfter()) {
14039                onSetAlpha(255);
14040            }
14041            parent.finishAnimatingView(this, a);
14042        }
14043
14044        if (more && hardwareAccelerated) {
14045            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14046                // alpha animations should cause the child to recreate its display list
14047                invalidate(true);
14048            }
14049        }
14050
14051        mRecreateDisplayList = false;
14052
14053        return more;
14054    }
14055
14056    /**
14057     * Manually render this view (and all of its children) to the given Canvas.
14058     * The view must have already done a full layout before this function is
14059     * called.  When implementing a view, implement
14060     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14061     * If you do need to override this method, call the superclass version.
14062     *
14063     * @param canvas The Canvas to which the View is rendered.
14064     */
14065    public void draw(Canvas canvas) {
14066        if (mClipBounds != null) {
14067            canvas.clipRect(mClipBounds);
14068        }
14069        final int privateFlags = mPrivateFlags;
14070        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14071                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14072        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14073
14074        /*
14075         * Draw traversal performs several drawing steps which must be executed
14076         * in the appropriate order:
14077         *
14078         *      1. Draw the background
14079         *      2. If necessary, save the canvas' layers to prepare for fading
14080         *      3. Draw view's content
14081         *      4. Draw children
14082         *      5. If necessary, draw the fading edges and restore layers
14083         *      6. Draw decorations (scrollbars for instance)
14084         */
14085
14086        // Step 1, draw the background, if needed
14087        int saveCount;
14088
14089        if (!dirtyOpaque) {
14090            final Drawable background = mBackground;
14091            if (background != null) {
14092                final int scrollX = mScrollX;
14093                final int scrollY = mScrollY;
14094
14095                if (mBackgroundSizeChanged) {
14096                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14097                    mBackgroundSizeChanged = false;
14098                }
14099
14100                if ((scrollX | scrollY) == 0) {
14101                    background.draw(canvas);
14102                } else {
14103                    canvas.translate(scrollX, scrollY);
14104                    background.draw(canvas);
14105                    canvas.translate(-scrollX, -scrollY);
14106                }
14107            }
14108        }
14109
14110        // skip step 2 & 5 if possible (common case)
14111        final int viewFlags = mViewFlags;
14112        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14113        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14114        if (!verticalEdges && !horizontalEdges) {
14115            // Step 3, draw the content
14116            if (!dirtyOpaque) onDraw(canvas);
14117
14118            // Step 4, draw the children
14119            dispatchDraw(canvas);
14120
14121            // Step 6, draw decorations (scrollbars)
14122            onDrawScrollBars(canvas);
14123
14124            if (mOverlay != null && !mOverlay.isEmpty()) {
14125                mOverlay.getOverlayView().dispatchDraw(canvas);
14126            }
14127
14128            // we're done...
14129            return;
14130        }
14131
14132        /*
14133         * Here we do the full fledged routine...
14134         * (this is an uncommon case where speed matters less,
14135         * this is why we repeat some of the tests that have been
14136         * done above)
14137         */
14138
14139        boolean drawTop = false;
14140        boolean drawBottom = false;
14141        boolean drawLeft = false;
14142        boolean drawRight = false;
14143
14144        float topFadeStrength = 0.0f;
14145        float bottomFadeStrength = 0.0f;
14146        float leftFadeStrength = 0.0f;
14147        float rightFadeStrength = 0.0f;
14148
14149        // Step 2, save the canvas' layers
14150        int paddingLeft = mPaddingLeft;
14151
14152        final boolean offsetRequired = isPaddingOffsetRequired();
14153        if (offsetRequired) {
14154            paddingLeft += getLeftPaddingOffset();
14155        }
14156
14157        int left = mScrollX + paddingLeft;
14158        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14159        int top = mScrollY + getFadeTop(offsetRequired);
14160        int bottom = top + getFadeHeight(offsetRequired);
14161
14162        if (offsetRequired) {
14163            right += getRightPaddingOffset();
14164            bottom += getBottomPaddingOffset();
14165        }
14166
14167        final ScrollabilityCache scrollabilityCache = mScrollCache;
14168        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14169        int length = (int) fadeHeight;
14170
14171        // clip the fade length if top and bottom fades overlap
14172        // overlapping fades produce odd-looking artifacts
14173        if (verticalEdges && (top + length > bottom - length)) {
14174            length = (bottom - top) / 2;
14175        }
14176
14177        // also clip horizontal fades if necessary
14178        if (horizontalEdges && (left + length > right - length)) {
14179            length = (right - left) / 2;
14180        }
14181
14182        if (verticalEdges) {
14183            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14184            drawTop = topFadeStrength * fadeHeight > 1.0f;
14185            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14186            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14187        }
14188
14189        if (horizontalEdges) {
14190            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14191            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14192            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14193            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14194        }
14195
14196        saveCount = canvas.getSaveCount();
14197
14198        int solidColor = getSolidColor();
14199        if (solidColor == 0) {
14200            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14201
14202            if (drawTop) {
14203                canvas.saveLayer(left, top, right, top + length, null, flags);
14204            }
14205
14206            if (drawBottom) {
14207                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14208            }
14209
14210            if (drawLeft) {
14211                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14212            }
14213
14214            if (drawRight) {
14215                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14216            }
14217        } else {
14218            scrollabilityCache.setFadeColor(solidColor);
14219        }
14220
14221        // Step 3, draw the content
14222        if (!dirtyOpaque) onDraw(canvas);
14223
14224        // Step 4, draw the children
14225        dispatchDraw(canvas);
14226
14227        // Step 5, draw the fade effect and restore layers
14228        final Paint p = scrollabilityCache.paint;
14229        final Matrix matrix = scrollabilityCache.matrix;
14230        final Shader fade = scrollabilityCache.shader;
14231
14232        if (drawTop) {
14233            matrix.setScale(1, fadeHeight * topFadeStrength);
14234            matrix.postTranslate(left, top);
14235            fade.setLocalMatrix(matrix);
14236            canvas.drawRect(left, top, right, top + length, p);
14237        }
14238
14239        if (drawBottom) {
14240            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14241            matrix.postRotate(180);
14242            matrix.postTranslate(left, bottom);
14243            fade.setLocalMatrix(matrix);
14244            canvas.drawRect(left, bottom - length, right, bottom, p);
14245        }
14246
14247        if (drawLeft) {
14248            matrix.setScale(1, fadeHeight * leftFadeStrength);
14249            matrix.postRotate(-90);
14250            matrix.postTranslate(left, top);
14251            fade.setLocalMatrix(matrix);
14252            canvas.drawRect(left, top, left + length, bottom, p);
14253        }
14254
14255        if (drawRight) {
14256            matrix.setScale(1, fadeHeight * rightFadeStrength);
14257            matrix.postRotate(90);
14258            matrix.postTranslate(right, top);
14259            fade.setLocalMatrix(matrix);
14260            canvas.drawRect(right - length, top, right, bottom, p);
14261        }
14262
14263        canvas.restoreToCount(saveCount);
14264
14265        // Step 6, draw decorations (scrollbars)
14266        onDrawScrollBars(canvas);
14267
14268        if (mOverlay != null && !mOverlay.isEmpty()) {
14269            mOverlay.getOverlayView().dispatchDraw(canvas);
14270        }
14271    }
14272
14273    /**
14274     * Returns the overlay for this view, creating it if it does not yet exist.
14275     * Adding drawables to the overlay will cause them to be displayed whenever
14276     * the view itself is redrawn. Objects in the overlay should be actively
14277     * managed: remove them when they should not be displayed anymore. The
14278     * overlay will always have the same size as its host view.
14279     *
14280     * <p>Note: Overlays do not currently work correctly with {@link
14281     * SurfaceView} or {@link TextureView}; contents in overlays for these
14282     * types of views may not display correctly.</p>
14283     *
14284     * @return The ViewOverlay object for this view.
14285     * @see ViewOverlay
14286     */
14287    public ViewOverlay getOverlay() {
14288        if (mOverlay == null) {
14289            mOverlay = new ViewOverlay(mContext, this);
14290        }
14291        return mOverlay;
14292    }
14293
14294    /**
14295     * Override this if your view is known to always be drawn on top of a solid color background,
14296     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14297     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14298     * should be set to 0xFF.
14299     *
14300     * @see #setVerticalFadingEdgeEnabled(boolean)
14301     * @see #setHorizontalFadingEdgeEnabled(boolean)
14302     *
14303     * @return The known solid color background for this view, or 0 if the color may vary
14304     */
14305    @ViewDebug.ExportedProperty(category = "drawing")
14306    public int getSolidColor() {
14307        return 0;
14308    }
14309
14310    /**
14311     * Build a human readable string representation of the specified view flags.
14312     *
14313     * @param flags the view flags to convert to a string
14314     * @return a String representing the supplied flags
14315     */
14316    private static String printFlags(int flags) {
14317        String output = "";
14318        int numFlags = 0;
14319        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14320            output += "TAKES_FOCUS";
14321            numFlags++;
14322        }
14323
14324        switch (flags & VISIBILITY_MASK) {
14325        case INVISIBLE:
14326            if (numFlags > 0) {
14327                output += " ";
14328            }
14329            output += "INVISIBLE";
14330            // USELESS HERE numFlags++;
14331            break;
14332        case GONE:
14333            if (numFlags > 0) {
14334                output += " ";
14335            }
14336            output += "GONE";
14337            // USELESS HERE numFlags++;
14338            break;
14339        default:
14340            break;
14341        }
14342        return output;
14343    }
14344
14345    /**
14346     * Build a human readable string representation of the specified private
14347     * view flags.
14348     *
14349     * @param privateFlags the private view flags to convert to a string
14350     * @return a String representing the supplied flags
14351     */
14352    private static String printPrivateFlags(int privateFlags) {
14353        String output = "";
14354        int numFlags = 0;
14355
14356        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14357            output += "WANTS_FOCUS";
14358            numFlags++;
14359        }
14360
14361        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14362            if (numFlags > 0) {
14363                output += " ";
14364            }
14365            output += "FOCUSED";
14366            numFlags++;
14367        }
14368
14369        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14370            if (numFlags > 0) {
14371                output += " ";
14372            }
14373            output += "SELECTED";
14374            numFlags++;
14375        }
14376
14377        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14378            if (numFlags > 0) {
14379                output += " ";
14380            }
14381            output += "IS_ROOT_NAMESPACE";
14382            numFlags++;
14383        }
14384
14385        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14386            if (numFlags > 0) {
14387                output += " ";
14388            }
14389            output += "HAS_BOUNDS";
14390            numFlags++;
14391        }
14392
14393        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14394            if (numFlags > 0) {
14395                output += " ";
14396            }
14397            output += "DRAWN";
14398            // USELESS HERE numFlags++;
14399        }
14400        return output;
14401    }
14402
14403    /**
14404     * <p>Indicates whether or not this view's layout will be requested during
14405     * the next hierarchy layout pass.</p>
14406     *
14407     * @return true if the layout will be forced during next layout pass
14408     */
14409    public boolean isLayoutRequested() {
14410        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14411    }
14412
14413    /**
14414     * Return true if o is a ViewGroup that is laying out using optical bounds.
14415     * @hide
14416     */
14417    public static boolean isLayoutModeOptical(Object o) {
14418        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14419    }
14420
14421    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14422        Insets parentInsets = mParent instanceof View ?
14423                ((View) mParent).getOpticalInsets() : Insets.NONE;
14424        Insets childInsets = getOpticalInsets();
14425        return setFrame(
14426                left   + parentInsets.left - childInsets.left,
14427                top    + parentInsets.top  - childInsets.top,
14428                right  + parentInsets.left + childInsets.right,
14429                bottom + parentInsets.top  + childInsets.bottom);
14430    }
14431
14432    /**
14433     * Assign a size and position to a view and all of its
14434     * descendants
14435     *
14436     * <p>This is the second phase of the layout mechanism.
14437     * (The first is measuring). In this phase, each parent calls
14438     * layout on all of its children to position them.
14439     * This is typically done using the child measurements
14440     * that were stored in the measure pass().</p>
14441     *
14442     * <p>Derived classes should not override this method.
14443     * Derived classes with children should override
14444     * onLayout. In that method, they should
14445     * call layout on each of their children.</p>
14446     *
14447     * @param l Left position, relative to parent
14448     * @param t Top position, relative to parent
14449     * @param r Right position, relative to parent
14450     * @param b Bottom position, relative to parent
14451     */
14452    @SuppressWarnings({"unchecked"})
14453    public void layout(int l, int t, int r, int b) {
14454        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14455            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14456            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14457        }
14458
14459        int oldL = mLeft;
14460        int oldT = mTop;
14461        int oldB = mBottom;
14462        int oldR = mRight;
14463
14464        boolean changed = isLayoutModeOptical(mParent) ?
14465                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14466
14467        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14468            onLayout(changed, l, t, r, b);
14469            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14470
14471            ListenerInfo li = mListenerInfo;
14472            if (li != null && li.mOnLayoutChangeListeners != null) {
14473                ArrayList<OnLayoutChangeListener> listenersCopy =
14474                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14475                int numListeners = listenersCopy.size();
14476                for (int i = 0; i < numListeners; ++i) {
14477                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14478                }
14479            }
14480        }
14481
14482        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14483        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14484    }
14485
14486    /**
14487     * Called from layout when this view should
14488     * assign a size and position to each of its children.
14489     *
14490     * Derived classes with children should override
14491     * this method and call layout on each of
14492     * their children.
14493     * @param changed This is a new size or position for this view
14494     * @param left Left position, relative to parent
14495     * @param top Top position, relative to parent
14496     * @param right Right position, relative to parent
14497     * @param bottom Bottom position, relative to parent
14498     */
14499    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14500    }
14501
14502    /**
14503     * Assign a size and position to this view.
14504     *
14505     * This is called from layout.
14506     *
14507     * @param left Left position, relative to parent
14508     * @param top Top position, relative to parent
14509     * @param right Right position, relative to parent
14510     * @param bottom Bottom position, relative to parent
14511     * @return true if the new size and position are different than the
14512     *         previous ones
14513     * {@hide}
14514     */
14515    protected boolean setFrame(int left, int top, int right, int bottom) {
14516        boolean changed = false;
14517
14518        if (DBG) {
14519            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14520                    + right + "," + bottom + ")");
14521        }
14522
14523        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14524            changed = true;
14525
14526            // Remember our drawn bit
14527            int drawn = mPrivateFlags & PFLAG_DRAWN;
14528
14529            int oldWidth = mRight - mLeft;
14530            int oldHeight = mBottom - mTop;
14531            int newWidth = right - left;
14532            int newHeight = bottom - top;
14533            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14534
14535            // Invalidate our old position
14536            invalidate(sizeChanged);
14537
14538            mLeft = left;
14539            mTop = top;
14540            mRight = right;
14541            mBottom = bottom;
14542            if (mDisplayList != null) {
14543                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14544            }
14545
14546            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14547
14548
14549            if (sizeChanged) {
14550                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14551                    // A change in dimension means an auto-centered pivot point changes, too
14552                    if (mTransformationInfo != null) {
14553                        mTransformationInfo.mMatrixDirty = true;
14554                    }
14555                }
14556                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14557            }
14558
14559            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14560                // If we are visible, force the DRAWN bit to on so that
14561                // this invalidate will go through (at least to our parent).
14562                // This is because someone may have invalidated this view
14563                // before this call to setFrame came in, thereby clearing
14564                // the DRAWN bit.
14565                mPrivateFlags |= PFLAG_DRAWN;
14566                invalidate(sizeChanged);
14567                // parent display list may need to be recreated based on a change in the bounds
14568                // of any child
14569                invalidateParentCaches();
14570            }
14571
14572            // Reset drawn bit to original value (invalidate turns it off)
14573            mPrivateFlags |= drawn;
14574
14575            mBackgroundSizeChanged = true;
14576
14577            notifySubtreeAccessibilityStateChangedIfNeeded();
14578        }
14579        return changed;
14580    }
14581
14582    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14583        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14584        if (mOverlay != null) {
14585            mOverlay.getOverlayView().setRight(newWidth);
14586            mOverlay.getOverlayView().setBottom(newHeight);
14587        }
14588    }
14589
14590    /**
14591     * Finalize inflating a view from XML.  This is called as the last phase
14592     * of inflation, after all child views have been added.
14593     *
14594     * <p>Even if the subclass overrides onFinishInflate, they should always be
14595     * sure to call the super method, so that we get called.
14596     */
14597    protected void onFinishInflate() {
14598    }
14599
14600    /**
14601     * Returns the resources associated with this view.
14602     *
14603     * @return Resources object.
14604     */
14605    public Resources getResources() {
14606        return mResources;
14607    }
14608
14609    /**
14610     * Invalidates the specified Drawable.
14611     *
14612     * @param drawable the drawable to invalidate
14613     */
14614    public void invalidateDrawable(Drawable drawable) {
14615        if (verifyDrawable(drawable)) {
14616            final Rect dirty = drawable.getBounds();
14617            final int scrollX = mScrollX;
14618            final int scrollY = mScrollY;
14619
14620            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14621                    dirty.right + scrollX, dirty.bottom + scrollY);
14622        }
14623    }
14624
14625    /**
14626     * Schedules an action on a drawable to occur at a specified time.
14627     *
14628     * @param who the recipient of the action
14629     * @param what the action to run on the drawable
14630     * @param when the time at which the action must occur. Uses the
14631     *        {@link SystemClock#uptimeMillis} timebase.
14632     */
14633    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14634        if (verifyDrawable(who) && what != null) {
14635            final long delay = when - SystemClock.uptimeMillis();
14636            if (mAttachInfo != null) {
14637                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14638                        Choreographer.CALLBACK_ANIMATION, what, who,
14639                        Choreographer.subtractFrameDelay(delay));
14640            } else {
14641                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14642            }
14643        }
14644    }
14645
14646    /**
14647     * Cancels a scheduled action on a drawable.
14648     *
14649     * @param who the recipient of the action
14650     * @param what the action to cancel
14651     */
14652    public void unscheduleDrawable(Drawable who, Runnable what) {
14653        if (verifyDrawable(who) && what != null) {
14654            if (mAttachInfo != null) {
14655                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14656                        Choreographer.CALLBACK_ANIMATION, what, who);
14657            } else {
14658                ViewRootImpl.getRunQueue().removeCallbacks(what);
14659            }
14660        }
14661    }
14662
14663    /**
14664     * Unschedule any events associated with the given Drawable.  This can be
14665     * used when selecting a new Drawable into a view, so that the previous
14666     * one is completely unscheduled.
14667     *
14668     * @param who The Drawable to unschedule.
14669     *
14670     * @see #drawableStateChanged
14671     */
14672    public void unscheduleDrawable(Drawable who) {
14673        if (mAttachInfo != null && who != null) {
14674            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14675                    Choreographer.CALLBACK_ANIMATION, null, who);
14676        }
14677    }
14678
14679    /**
14680     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14681     * that the View directionality can and will be resolved before its Drawables.
14682     *
14683     * Will call {@link View#onResolveDrawables} when resolution is done.
14684     *
14685     * @hide
14686     */
14687    protected void resolveDrawables() {
14688        // Drawables resolution may need to happen before resolving the layout direction (which is
14689        // done only during the measure() call).
14690        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
14691        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
14692        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
14693        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
14694        // direction to be resolved as its resolved value will be the same as its raw value.
14695        if (!isLayoutDirectionResolved() &&
14696                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
14697            return;
14698        }
14699
14700        final int layoutDirection = isLayoutDirectionResolved() ?
14701                getLayoutDirection() : getRawLayoutDirection();
14702
14703        if (mBackground != null) {
14704            mBackground.setLayoutDirection(layoutDirection);
14705        }
14706        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14707        onResolveDrawables(layoutDirection);
14708    }
14709
14710    /**
14711     * Called when layout direction has been resolved.
14712     *
14713     * The default implementation does nothing.
14714     *
14715     * @param layoutDirection The resolved layout direction.
14716     *
14717     * @see #LAYOUT_DIRECTION_LTR
14718     * @see #LAYOUT_DIRECTION_RTL
14719     *
14720     * @hide
14721     */
14722    public void onResolveDrawables(int layoutDirection) {
14723    }
14724
14725    /**
14726     * @hide
14727     */
14728    protected void resetResolvedDrawables() {
14729        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14730    }
14731
14732    private boolean isDrawablesResolved() {
14733        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14734    }
14735
14736    /**
14737     * If your view subclass is displaying its own Drawable objects, it should
14738     * override this function and return true for any Drawable it is
14739     * displaying.  This allows animations for those drawables to be
14740     * scheduled.
14741     *
14742     * <p>Be sure to call through to the super class when overriding this
14743     * function.
14744     *
14745     * @param who The Drawable to verify.  Return true if it is one you are
14746     *            displaying, else return the result of calling through to the
14747     *            super class.
14748     *
14749     * @return boolean If true than the Drawable is being displayed in the
14750     *         view; else false and it is not allowed to animate.
14751     *
14752     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14753     * @see #drawableStateChanged()
14754     */
14755    protected boolean verifyDrawable(Drawable who) {
14756        return who == mBackground;
14757    }
14758
14759    /**
14760     * This function is called whenever the state of the view changes in such
14761     * a way that it impacts the state of drawables being shown.
14762     *
14763     * <p>Be sure to call through to the superclass when overriding this
14764     * function.
14765     *
14766     * @see Drawable#setState(int[])
14767     */
14768    protected void drawableStateChanged() {
14769        Drawable d = mBackground;
14770        if (d != null && d.isStateful()) {
14771            d.setState(getDrawableState());
14772        }
14773    }
14774
14775    /**
14776     * Call this to force a view to update its drawable state. This will cause
14777     * drawableStateChanged to be called on this view. Views that are interested
14778     * in the new state should call getDrawableState.
14779     *
14780     * @see #drawableStateChanged
14781     * @see #getDrawableState
14782     */
14783    public void refreshDrawableState() {
14784        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14785        drawableStateChanged();
14786
14787        ViewParent parent = mParent;
14788        if (parent != null) {
14789            parent.childDrawableStateChanged(this);
14790        }
14791    }
14792
14793    /**
14794     * Return an array of resource IDs of the drawable states representing the
14795     * current state of the view.
14796     *
14797     * @return The current drawable state
14798     *
14799     * @see Drawable#setState(int[])
14800     * @see #drawableStateChanged()
14801     * @see #onCreateDrawableState(int)
14802     */
14803    public final int[] getDrawableState() {
14804        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14805            return mDrawableState;
14806        } else {
14807            mDrawableState = onCreateDrawableState(0);
14808            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14809            return mDrawableState;
14810        }
14811    }
14812
14813    /**
14814     * Generate the new {@link android.graphics.drawable.Drawable} state for
14815     * this view. This is called by the view
14816     * system when the cached Drawable state is determined to be invalid.  To
14817     * retrieve the current state, you should use {@link #getDrawableState}.
14818     *
14819     * @param extraSpace if non-zero, this is the number of extra entries you
14820     * would like in the returned array in which you can place your own
14821     * states.
14822     *
14823     * @return Returns an array holding the current {@link Drawable} state of
14824     * the view.
14825     *
14826     * @see #mergeDrawableStates(int[], int[])
14827     */
14828    protected int[] onCreateDrawableState(int extraSpace) {
14829        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14830                mParent instanceof View) {
14831            return ((View) mParent).onCreateDrawableState(extraSpace);
14832        }
14833
14834        int[] drawableState;
14835
14836        int privateFlags = mPrivateFlags;
14837
14838        int viewStateIndex = 0;
14839        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14840        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14841        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14842        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14843        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14844        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14845        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14846                HardwareRenderer.isAvailable()) {
14847            // This is set if HW acceleration is requested, even if the current
14848            // process doesn't allow it.  This is just to allow app preview
14849            // windows to better match their app.
14850            viewStateIndex |= VIEW_STATE_ACCELERATED;
14851        }
14852        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14853
14854        final int privateFlags2 = mPrivateFlags2;
14855        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14856        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14857
14858        drawableState = VIEW_STATE_SETS[viewStateIndex];
14859
14860        //noinspection ConstantIfStatement
14861        if (false) {
14862            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14863            Log.i("View", toString()
14864                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14865                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14866                    + " fo=" + hasFocus()
14867                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14868                    + " wf=" + hasWindowFocus()
14869                    + ": " + Arrays.toString(drawableState));
14870        }
14871
14872        if (extraSpace == 0) {
14873            return drawableState;
14874        }
14875
14876        final int[] fullState;
14877        if (drawableState != null) {
14878            fullState = new int[drawableState.length + extraSpace];
14879            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14880        } else {
14881            fullState = new int[extraSpace];
14882        }
14883
14884        return fullState;
14885    }
14886
14887    /**
14888     * Merge your own state values in <var>additionalState</var> into the base
14889     * state values <var>baseState</var> that were returned by
14890     * {@link #onCreateDrawableState(int)}.
14891     *
14892     * @param baseState The base state values returned by
14893     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14894     * own additional state values.
14895     *
14896     * @param additionalState The additional state values you would like
14897     * added to <var>baseState</var>; this array is not modified.
14898     *
14899     * @return As a convenience, the <var>baseState</var> array you originally
14900     * passed into the function is returned.
14901     *
14902     * @see #onCreateDrawableState(int)
14903     */
14904    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14905        final int N = baseState.length;
14906        int i = N - 1;
14907        while (i >= 0 && baseState[i] == 0) {
14908            i--;
14909        }
14910        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14911        return baseState;
14912    }
14913
14914    /**
14915     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14916     * on all Drawable objects associated with this view.
14917     */
14918    public void jumpDrawablesToCurrentState() {
14919        if (mBackground != null) {
14920            mBackground.jumpToCurrentState();
14921        }
14922    }
14923
14924    /**
14925     * Sets the background color for this view.
14926     * @param color the color of the background
14927     */
14928    @RemotableViewMethod
14929    public void setBackgroundColor(int color) {
14930        if (mBackground instanceof ColorDrawable) {
14931            ((ColorDrawable) mBackground.mutate()).setColor(color);
14932            computeOpaqueFlags();
14933            mBackgroundResource = 0;
14934        } else {
14935            setBackground(new ColorDrawable(color));
14936        }
14937    }
14938
14939    /**
14940     * Set the background to a given resource. The resource should refer to
14941     * a Drawable object or 0 to remove the background.
14942     * @param resid The identifier of the resource.
14943     *
14944     * @attr ref android.R.styleable#View_background
14945     */
14946    @RemotableViewMethod
14947    public void setBackgroundResource(int resid) {
14948        if (resid != 0 && resid == mBackgroundResource) {
14949            return;
14950        }
14951
14952        Drawable d= null;
14953        if (resid != 0) {
14954            d = mResources.getDrawable(resid);
14955        }
14956        setBackground(d);
14957
14958        mBackgroundResource = resid;
14959    }
14960
14961    /**
14962     * Set the background to a given Drawable, or remove the background. If the
14963     * background has padding, this View's padding is set to the background's
14964     * padding. However, when a background is removed, this View's padding isn't
14965     * touched. If setting the padding is desired, please use
14966     * {@link #setPadding(int, int, int, int)}.
14967     *
14968     * @param background The Drawable to use as the background, or null to remove the
14969     *        background
14970     */
14971    public void setBackground(Drawable background) {
14972        //noinspection deprecation
14973        setBackgroundDrawable(background);
14974    }
14975
14976    /**
14977     * @deprecated use {@link #setBackground(Drawable)} instead
14978     */
14979    @Deprecated
14980    public void setBackgroundDrawable(Drawable background) {
14981        computeOpaqueFlags();
14982
14983        if (background == mBackground) {
14984            return;
14985        }
14986
14987        boolean requestLayout = false;
14988
14989        mBackgroundResource = 0;
14990
14991        /*
14992         * Regardless of whether we're setting a new background or not, we want
14993         * to clear the previous drawable.
14994         */
14995        if (mBackground != null) {
14996            mBackground.setCallback(null);
14997            unscheduleDrawable(mBackground);
14998        }
14999
15000        if (background != null) {
15001            Rect padding = sThreadLocal.get();
15002            if (padding == null) {
15003                padding = new Rect();
15004                sThreadLocal.set(padding);
15005            }
15006            resetResolvedDrawables();
15007            background.setLayoutDirection(getLayoutDirection());
15008            if (background.getPadding(padding)) {
15009                resetResolvedPadding();
15010                switch (background.getLayoutDirection()) {
15011                    case LAYOUT_DIRECTION_RTL:
15012                        mUserPaddingLeftInitial = padding.right;
15013                        mUserPaddingRightInitial = padding.left;
15014                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15015                        break;
15016                    case LAYOUT_DIRECTION_LTR:
15017                    default:
15018                        mUserPaddingLeftInitial = padding.left;
15019                        mUserPaddingRightInitial = padding.right;
15020                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15021                }
15022            }
15023
15024            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15025            // if it has a different minimum size, we should layout again
15026            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15027                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15028                requestLayout = true;
15029            }
15030
15031            background.setCallback(this);
15032            if (background.isStateful()) {
15033                background.setState(getDrawableState());
15034            }
15035            background.setVisible(getVisibility() == VISIBLE, false);
15036            mBackground = background;
15037
15038            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15039                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15040                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15041                requestLayout = true;
15042            }
15043        } else {
15044            /* Remove the background */
15045            mBackground = null;
15046
15047            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15048                /*
15049                 * This view ONLY drew the background before and we're removing
15050                 * the background, so now it won't draw anything
15051                 * (hence we SKIP_DRAW)
15052                 */
15053                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15054                mPrivateFlags |= PFLAG_SKIP_DRAW;
15055            }
15056
15057            /*
15058             * When the background is set, we try to apply its padding to this
15059             * View. When the background is removed, we don't touch this View's
15060             * padding. This is noted in the Javadocs. Hence, we don't need to
15061             * requestLayout(), the invalidate() below is sufficient.
15062             */
15063
15064            // The old background's minimum size could have affected this
15065            // View's layout, so let's requestLayout
15066            requestLayout = true;
15067        }
15068
15069        computeOpaqueFlags();
15070
15071        if (requestLayout) {
15072            requestLayout();
15073        }
15074
15075        mBackgroundSizeChanged = true;
15076        invalidate(true);
15077    }
15078
15079    /**
15080     * Gets the background drawable
15081     *
15082     * @return The drawable used as the background for this view, if any.
15083     *
15084     * @see #setBackground(Drawable)
15085     *
15086     * @attr ref android.R.styleable#View_background
15087     */
15088    public Drawable getBackground() {
15089        return mBackground;
15090    }
15091
15092    /**
15093     * Sets the padding. The view may add on the space required to display
15094     * the scrollbars, depending on the style and visibility of the scrollbars.
15095     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15096     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15097     * from the values set in this call.
15098     *
15099     * @attr ref android.R.styleable#View_padding
15100     * @attr ref android.R.styleable#View_paddingBottom
15101     * @attr ref android.R.styleable#View_paddingLeft
15102     * @attr ref android.R.styleable#View_paddingRight
15103     * @attr ref android.R.styleable#View_paddingTop
15104     * @param left the left padding in pixels
15105     * @param top the top padding in pixels
15106     * @param right the right padding in pixels
15107     * @param bottom the bottom padding in pixels
15108     */
15109    public void setPadding(int left, int top, int right, int bottom) {
15110        resetResolvedPadding();
15111
15112        mUserPaddingStart = UNDEFINED_PADDING;
15113        mUserPaddingEnd = UNDEFINED_PADDING;
15114
15115        mUserPaddingLeftInitial = left;
15116        mUserPaddingRightInitial = right;
15117
15118        internalSetPadding(left, top, right, bottom);
15119    }
15120
15121    /**
15122     * @hide
15123     */
15124    protected void internalSetPadding(int left, int top, int right, int bottom) {
15125        mUserPaddingLeft = left;
15126        mUserPaddingRight = right;
15127        mUserPaddingBottom = bottom;
15128
15129        final int viewFlags = mViewFlags;
15130        boolean changed = false;
15131
15132        // Common case is there are no scroll bars.
15133        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15134            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15135                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15136                        ? 0 : getVerticalScrollbarWidth();
15137                switch (mVerticalScrollbarPosition) {
15138                    case SCROLLBAR_POSITION_DEFAULT:
15139                        if (isLayoutRtl()) {
15140                            left += offset;
15141                        } else {
15142                            right += offset;
15143                        }
15144                        break;
15145                    case SCROLLBAR_POSITION_RIGHT:
15146                        right += offset;
15147                        break;
15148                    case SCROLLBAR_POSITION_LEFT:
15149                        left += offset;
15150                        break;
15151                }
15152            }
15153            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15154                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15155                        ? 0 : getHorizontalScrollbarHeight();
15156            }
15157        }
15158
15159        if (mPaddingLeft != left) {
15160            changed = true;
15161            mPaddingLeft = left;
15162        }
15163        if (mPaddingTop != top) {
15164            changed = true;
15165            mPaddingTop = top;
15166        }
15167        if (mPaddingRight != right) {
15168            changed = true;
15169            mPaddingRight = right;
15170        }
15171        if (mPaddingBottom != bottom) {
15172            changed = true;
15173            mPaddingBottom = bottom;
15174        }
15175
15176        if (changed) {
15177            requestLayout();
15178        }
15179    }
15180
15181    /**
15182     * Sets the relative padding. The view may add on the space required to display
15183     * the scrollbars, depending on the style and visibility of the scrollbars.
15184     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15185     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15186     * from the values set in this call.
15187     *
15188     * @attr ref android.R.styleable#View_padding
15189     * @attr ref android.R.styleable#View_paddingBottom
15190     * @attr ref android.R.styleable#View_paddingStart
15191     * @attr ref android.R.styleable#View_paddingEnd
15192     * @attr ref android.R.styleable#View_paddingTop
15193     * @param start the start padding in pixels
15194     * @param top the top padding in pixels
15195     * @param end the end padding in pixels
15196     * @param bottom the bottom padding in pixels
15197     */
15198    public void setPaddingRelative(int start, int top, int end, int bottom) {
15199        resetResolvedPadding();
15200
15201        mUserPaddingStart = start;
15202        mUserPaddingEnd = end;
15203
15204        switch(getLayoutDirection()) {
15205            case LAYOUT_DIRECTION_RTL:
15206                mUserPaddingLeftInitial = end;
15207                mUserPaddingRightInitial = start;
15208                internalSetPadding(end, top, start, bottom);
15209                break;
15210            case LAYOUT_DIRECTION_LTR:
15211            default:
15212                mUserPaddingLeftInitial = start;
15213                mUserPaddingRightInitial = end;
15214                internalSetPadding(start, top, end, bottom);
15215        }
15216    }
15217
15218    /**
15219     * Returns the top padding of this view.
15220     *
15221     * @return the top padding in pixels
15222     */
15223    public int getPaddingTop() {
15224        return mPaddingTop;
15225    }
15226
15227    /**
15228     * Returns the bottom padding of this view. If there are inset and enabled
15229     * scrollbars, this value may include the space required to display the
15230     * scrollbars as well.
15231     *
15232     * @return the bottom padding in pixels
15233     */
15234    public int getPaddingBottom() {
15235        return mPaddingBottom;
15236    }
15237
15238    /**
15239     * Returns the left padding of this view. If there are inset and enabled
15240     * scrollbars, this value may include the space required to display the
15241     * scrollbars as well.
15242     *
15243     * @return the left padding in pixels
15244     */
15245    public int getPaddingLeft() {
15246        if (!isPaddingResolved()) {
15247            resolvePadding();
15248        }
15249        return mPaddingLeft;
15250    }
15251
15252    /**
15253     * Returns the start padding of this view depending on its resolved layout direction.
15254     * If there are inset and enabled scrollbars, this value may include the space
15255     * required to display the scrollbars as well.
15256     *
15257     * @return the start padding in pixels
15258     */
15259    public int getPaddingStart() {
15260        if (!isPaddingResolved()) {
15261            resolvePadding();
15262        }
15263        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15264                mPaddingRight : mPaddingLeft;
15265    }
15266
15267    /**
15268     * Returns the right padding of this view. If there are inset and enabled
15269     * scrollbars, this value may include the space required to display the
15270     * scrollbars as well.
15271     *
15272     * @return the right padding in pixels
15273     */
15274    public int getPaddingRight() {
15275        if (!isPaddingResolved()) {
15276            resolvePadding();
15277        }
15278        return mPaddingRight;
15279    }
15280
15281    /**
15282     * Returns the end padding of this view depending on its resolved layout direction.
15283     * If there are inset and enabled scrollbars, this value may include the space
15284     * required to display the scrollbars as well.
15285     *
15286     * @return the end padding in pixels
15287     */
15288    public int getPaddingEnd() {
15289        if (!isPaddingResolved()) {
15290            resolvePadding();
15291        }
15292        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15293                mPaddingLeft : mPaddingRight;
15294    }
15295
15296    /**
15297     * Return if the padding as been set thru relative values
15298     * {@link #setPaddingRelative(int, int, int, int)} or thru
15299     * @attr ref android.R.styleable#View_paddingStart or
15300     * @attr ref android.R.styleable#View_paddingEnd
15301     *
15302     * @return true if the padding is relative or false if it is not.
15303     */
15304    public boolean isPaddingRelative() {
15305        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15306    }
15307
15308    Insets computeOpticalInsets() {
15309        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15310    }
15311
15312    /**
15313     * @hide
15314     */
15315    public void resetPaddingToInitialValues() {
15316        if (isRtlCompatibilityMode()) {
15317            mPaddingLeft = mUserPaddingLeftInitial;
15318            mPaddingRight = mUserPaddingRightInitial;
15319            return;
15320        }
15321        if (isLayoutRtl()) {
15322            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15323            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15324        } else {
15325            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15326            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15327        }
15328    }
15329
15330    /**
15331     * @hide
15332     */
15333    public Insets getOpticalInsets() {
15334        if (mLayoutInsets == null) {
15335            mLayoutInsets = computeOpticalInsets();
15336        }
15337        return mLayoutInsets;
15338    }
15339
15340    /**
15341     * Changes the selection state of this view. A view can be selected or not.
15342     * Note that selection is not the same as focus. Views are typically
15343     * selected in the context of an AdapterView like ListView or GridView;
15344     * the selected view is the view that is highlighted.
15345     *
15346     * @param selected true if the view must be selected, false otherwise
15347     */
15348    public void setSelected(boolean selected) {
15349        //noinspection DoubleNegation
15350        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15351            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15352            if (!selected) resetPressedState();
15353            invalidate(true);
15354            refreshDrawableState();
15355            dispatchSetSelected(selected);
15356            notifyViewAccessibilityStateChangedIfNeeded();
15357        }
15358    }
15359
15360    /**
15361     * Dispatch setSelected to all of this View's children.
15362     *
15363     * @see #setSelected(boolean)
15364     *
15365     * @param selected The new selected state
15366     */
15367    protected void dispatchSetSelected(boolean selected) {
15368    }
15369
15370    /**
15371     * Indicates the selection state of this view.
15372     *
15373     * @return true if the view is selected, false otherwise
15374     */
15375    @ViewDebug.ExportedProperty
15376    public boolean isSelected() {
15377        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15378    }
15379
15380    /**
15381     * Changes the activated state of this view. A view can be activated or not.
15382     * Note that activation is not the same as selection.  Selection is
15383     * a transient property, representing the view (hierarchy) the user is
15384     * currently interacting with.  Activation is a longer-term state that the
15385     * user can move views in and out of.  For example, in a list view with
15386     * single or multiple selection enabled, the views in the current selection
15387     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15388     * here.)  The activated state is propagated down to children of the view it
15389     * is set on.
15390     *
15391     * @param activated true if the view must be activated, false otherwise
15392     */
15393    public void setActivated(boolean activated) {
15394        //noinspection DoubleNegation
15395        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15396            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15397            invalidate(true);
15398            refreshDrawableState();
15399            dispatchSetActivated(activated);
15400        }
15401    }
15402
15403    /**
15404     * Dispatch setActivated to all of this View's children.
15405     *
15406     * @see #setActivated(boolean)
15407     *
15408     * @param activated The new activated state
15409     */
15410    protected void dispatchSetActivated(boolean activated) {
15411    }
15412
15413    /**
15414     * Indicates the activation state of this view.
15415     *
15416     * @return true if the view is activated, false otherwise
15417     */
15418    @ViewDebug.ExportedProperty
15419    public boolean isActivated() {
15420        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15421    }
15422
15423    /**
15424     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15425     * observer can be used to get notifications when global events, like
15426     * layout, happen.
15427     *
15428     * The returned ViewTreeObserver observer is not guaranteed to remain
15429     * valid for the lifetime of this View. If the caller of this method keeps
15430     * a long-lived reference to ViewTreeObserver, it should always check for
15431     * the return value of {@link ViewTreeObserver#isAlive()}.
15432     *
15433     * @return The ViewTreeObserver for this view's hierarchy.
15434     */
15435    public ViewTreeObserver getViewTreeObserver() {
15436        if (mAttachInfo != null) {
15437            return mAttachInfo.mTreeObserver;
15438        }
15439        if (mFloatingTreeObserver == null) {
15440            mFloatingTreeObserver = new ViewTreeObserver();
15441        }
15442        return mFloatingTreeObserver;
15443    }
15444
15445    /**
15446     * <p>Finds the topmost view in the current view hierarchy.</p>
15447     *
15448     * @return the topmost view containing this view
15449     */
15450    public View getRootView() {
15451        if (mAttachInfo != null) {
15452            final View v = mAttachInfo.mRootView;
15453            if (v != null) {
15454                return v;
15455            }
15456        }
15457
15458        View parent = this;
15459
15460        while (parent.mParent != null && parent.mParent instanceof View) {
15461            parent = (View) parent.mParent;
15462        }
15463
15464        return parent;
15465    }
15466
15467    /**
15468     * Transforms a motion event from view-local coordinates to on-screen
15469     * coordinates.
15470     *
15471     * @param ev the view-local motion event
15472     * @return false if the transformation could not be applied
15473     * @hide
15474     */
15475    public boolean toGlobalMotionEvent(MotionEvent ev) {
15476        final AttachInfo info = mAttachInfo;
15477        if (info == null) {
15478            return false;
15479        }
15480
15481        transformMotionEventToGlobal(ev);
15482        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15483        return true;
15484    }
15485
15486    /**
15487     * Transforms a motion event from on-screen coordinates to view-local
15488     * coordinates.
15489     *
15490     * @param ev the on-screen motion event
15491     * @return false if the transformation could not be applied
15492     * @hide
15493     */
15494    public boolean toLocalMotionEvent(MotionEvent ev) {
15495        final AttachInfo info = mAttachInfo;
15496        if (info == null) {
15497            return false;
15498        }
15499
15500        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15501        transformMotionEventToLocal(ev);
15502        return true;
15503    }
15504
15505    /**
15506     * Recursive helper method that applies transformations in post-order.
15507     *
15508     * @param ev the on-screen motion event
15509     */
15510    private void transformMotionEventToLocal(MotionEvent ev) {
15511        final ViewParent parent = mParent;
15512        if (parent instanceof View) {
15513            final View vp = (View) parent;
15514            vp.transformMotionEventToLocal(ev);
15515            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15516        } else if (parent instanceof ViewRootImpl) {
15517            final ViewRootImpl vr = (ViewRootImpl) parent;
15518            ev.offsetLocation(0, vr.mCurScrollY);
15519        }
15520
15521        ev.offsetLocation(-mLeft, -mTop);
15522
15523        if (!hasIdentityMatrix()) {
15524            ev.transform(getInverseMatrix());
15525        }
15526    }
15527
15528    /**
15529     * Recursive helper method that applies transformations in pre-order.
15530     *
15531     * @param ev the on-screen motion event
15532     */
15533    private void transformMotionEventToGlobal(MotionEvent ev) {
15534        if (!hasIdentityMatrix()) {
15535            ev.transform(getMatrix());
15536        }
15537
15538        ev.offsetLocation(mLeft, mTop);
15539
15540        final ViewParent parent = mParent;
15541        if (parent instanceof View) {
15542            final View vp = (View) parent;
15543            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15544            vp.transformMotionEventToGlobal(ev);
15545        } else if (parent instanceof ViewRootImpl) {
15546            final ViewRootImpl vr = (ViewRootImpl) parent;
15547            ev.offsetLocation(0, -vr.mCurScrollY);
15548        }
15549    }
15550
15551    /**
15552     * <p>Computes the coordinates of this view on the screen. The argument
15553     * must be an array of two integers. After the method returns, the array
15554     * contains the x and y location in that order.</p>
15555     *
15556     * @param location an array of two integers in which to hold the coordinates
15557     */
15558    public void getLocationOnScreen(int[] location) {
15559        getLocationInWindow(location);
15560
15561        final AttachInfo info = mAttachInfo;
15562        if (info != null) {
15563            location[0] += info.mWindowLeft;
15564            location[1] += info.mWindowTop;
15565        }
15566    }
15567
15568    /**
15569     * <p>Computes the coordinates of this view in its window. The argument
15570     * must be an array of two integers. After the method returns, the array
15571     * contains the x and y location in that order.</p>
15572     *
15573     * @param location an array of two integers in which to hold the coordinates
15574     */
15575    public void getLocationInWindow(int[] location) {
15576        if (location == null || location.length < 2) {
15577            throw new IllegalArgumentException("location must be an array of two integers");
15578        }
15579
15580        if (mAttachInfo == null) {
15581            // When the view is not attached to a window, this method does not make sense
15582            location[0] = location[1] = 0;
15583            return;
15584        }
15585
15586        float[] position = mAttachInfo.mTmpTransformLocation;
15587        position[0] = position[1] = 0.0f;
15588
15589        if (!hasIdentityMatrix()) {
15590            getMatrix().mapPoints(position);
15591        }
15592
15593        position[0] += mLeft;
15594        position[1] += mTop;
15595
15596        ViewParent viewParent = mParent;
15597        while (viewParent instanceof View) {
15598            final View view = (View) viewParent;
15599
15600            position[0] -= view.mScrollX;
15601            position[1] -= view.mScrollY;
15602
15603            if (!view.hasIdentityMatrix()) {
15604                view.getMatrix().mapPoints(position);
15605            }
15606
15607            position[0] += view.mLeft;
15608            position[1] += view.mTop;
15609
15610            viewParent = view.mParent;
15611         }
15612
15613        if (viewParent instanceof ViewRootImpl) {
15614            // *cough*
15615            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15616            position[1] -= vr.mCurScrollY;
15617        }
15618
15619        location[0] = (int) (position[0] + 0.5f);
15620        location[1] = (int) (position[1] + 0.5f);
15621    }
15622
15623    /**
15624     * {@hide}
15625     * @param id the id of the view to be found
15626     * @return the view of the specified id, null if cannot be found
15627     */
15628    protected View findViewTraversal(int id) {
15629        if (id == mID) {
15630            return this;
15631        }
15632        return null;
15633    }
15634
15635    /**
15636     * {@hide}
15637     * @param tag the tag of the view to be found
15638     * @return the view of specified tag, null if cannot be found
15639     */
15640    protected View findViewWithTagTraversal(Object tag) {
15641        if (tag != null && tag.equals(mTag)) {
15642            return this;
15643        }
15644        return null;
15645    }
15646
15647    /**
15648     * {@hide}
15649     * @param predicate The predicate to evaluate.
15650     * @param childToSkip If not null, ignores this child during the recursive traversal.
15651     * @return The first view that matches the predicate or null.
15652     */
15653    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15654        if (predicate.apply(this)) {
15655            return this;
15656        }
15657        return null;
15658    }
15659
15660    /**
15661     * Look for a child view with the given id.  If this view has the given
15662     * id, return this view.
15663     *
15664     * @param id The id to search for.
15665     * @return The view that has the given id in the hierarchy or null
15666     */
15667    public final View findViewById(int id) {
15668        if (id < 0) {
15669            return null;
15670        }
15671        return findViewTraversal(id);
15672    }
15673
15674    /**
15675     * Finds a view by its unuque and stable accessibility id.
15676     *
15677     * @param accessibilityId The searched accessibility id.
15678     * @return The found view.
15679     */
15680    final View findViewByAccessibilityId(int accessibilityId) {
15681        if (accessibilityId < 0) {
15682            return null;
15683        }
15684        return findViewByAccessibilityIdTraversal(accessibilityId);
15685    }
15686
15687    /**
15688     * Performs the traversal to find a view by its unuque and stable accessibility id.
15689     *
15690     * <strong>Note:</strong>This method does not stop at the root namespace
15691     * boundary since the user can touch the screen at an arbitrary location
15692     * potentially crossing the root namespace bounday which will send an
15693     * accessibility event to accessibility services and they should be able
15694     * to obtain the event source. Also accessibility ids are guaranteed to be
15695     * unique in the window.
15696     *
15697     * @param accessibilityId The accessibility id.
15698     * @return The found view.
15699     *
15700     * @hide
15701     */
15702    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15703        if (getAccessibilityViewId() == accessibilityId) {
15704            return this;
15705        }
15706        return null;
15707    }
15708
15709    /**
15710     * Look for a child view with the given tag.  If this view has the given
15711     * tag, return this view.
15712     *
15713     * @param tag The tag to search for, using "tag.equals(getTag())".
15714     * @return The View that has the given tag in the hierarchy or null
15715     */
15716    public final View findViewWithTag(Object tag) {
15717        if (tag == null) {
15718            return null;
15719        }
15720        return findViewWithTagTraversal(tag);
15721    }
15722
15723    /**
15724     * {@hide}
15725     * Look for a child view that matches the specified predicate.
15726     * If this view matches the predicate, return this view.
15727     *
15728     * @param predicate The predicate to evaluate.
15729     * @return The first view that matches the predicate or null.
15730     */
15731    public final View findViewByPredicate(Predicate<View> predicate) {
15732        return findViewByPredicateTraversal(predicate, null);
15733    }
15734
15735    /**
15736     * {@hide}
15737     * Look for a child view that matches the specified predicate,
15738     * starting with the specified view and its descendents and then
15739     * recusively searching the ancestors and siblings of that view
15740     * until this view is reached.
15741     *
15742     * This method is useful in cases where the predicate does not match
15743     * a single unique view (perhaps multiple views use the same id)
15744     * and we are trying to find the view that is "closest" in scope to the
15745     * starting view.
15746     *
15747     * @param start The view to start from.
15748     * @param predicate The predicate to evaluate.
15749     * @return The first view that matches the predicate or null.
15750     */
15751    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15752        View childToSkip = null;
15753        for (;;) {
15754            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15755            if (view != null || start == this) {
15756                return view;
15757            }
15758
15759            ViewParent parent = start.getParent();
15760            if (parent == null || !(parent instanceof View)) {
15761                return null;
15762            }
15763
15764            childToSkip = start;
15765            start = (View) parent;
15766        }
15767    }
15768
15769    /**
15770     * Sets the identifier for this view. The identifier does not have to be
15771     * unique in this view's hierarchy. The identifier should be a positive
15772     * number.
15773     *
15774     * @see #NO_ID
15775     * @see #getId()
15776     * @see #findViewById(int)
15777     *
15778     * @param id a number used to identify the view
15779     *
15780     * @attr ref android.R.styleable#View_id
15781     */
15782    public void setId(int id) {
15783        mID = id;
15784        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15785            mID = generateViewId();
15786        }
15787    }
15788
15789    /**
15790     * {@hide}
15791     *
15792     * @param isRoot true if the view belongs to the root namespace, false
15793     *        otherwise
15794     */
15795    public void setIsRootNamespace(boolean isRoot) {
15796        if (isRoot) {
15797            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15798        } else {
15799            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15800        }
15801    }
15802
15803    /**
15804     * {@hide}
15805     *
15806     * @return true if the view belongs to the root namespace, false otherwise
15807     */
15808    public boolean isRootNamespace() {
15809        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15810    }
15811
15812    /**
15813     * Returns this view's identifier.
15814     *
15815     * @return a positive integer used to identify the view or {@link #NO_ID}
15816     *         if the view has no ID
15817     *
15818     * @see #setId(int)
15819     * @see #findViewById(int)
15820     * @attr ref android.R.styleable#View_id
15821     */
15822    @ViewDebug.CapturedViewProperty
15823    public int getId() {
15824        return mID;
15825    }
15826
15827    /**
15828     * Returns this view's tag.
15829     *
15830     * @return the Object stored in this view as a tag
15831     *
15832     * @see #setTag(Object)
15833     * @see #getTag(int)
15834     */
15835    @ViewDebug.ExportedProperty
15836    public Object getTag() {
15837        return mTag;
15838    }
15839
15840    /**
15841     * Sets the tag associated with this view. A tag can be used to mark
15842     * a view in its hierarchy and does not have to be unique within the
15843     * hierarchy. Tags can also be used to store data within a view without
15844     * resorting to another data structure.
15845     *
15846     * @param tag an Object to tag the view with
15847     *
15848     * @see #getTag()
15849     * @see #setTag(int, Object)
15850     */
15851    public void setTag(final Object tag) {
15852        mTag = tag;
15853    }
15854
15855    /**
15856     * Returns the tag associated with this view and the specified key.
15857     *
15858     * @param key The key identifying the tag
15859     *
15860     * @return the Object stored in this view as a tag
15861     *
15862     * @see #setTag(int, Object)
15863     * @see #getTag()
15864     */
15865    public Object getTag(int key) {
15866        if (mKeyedTags != null) return mKeyedTags.get(key);
15867        return null;
15868    }
15869
15870    /**
15871     * Sets a tag associated with this view and a key. A tag can be used
15872     * to mark a view in its hierarchy and does not have to be unique within
15873     * the hierarchy. Tags can also be used to store data within a view
15874     * without resorting to another data structure.
15875     *
15876     * The specified key should be an id declared in the resources of the
15877     * application to ensure it is unique (see the <a
15878     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15879     * Keys identified as belonging to
15880     * the Android framework or not associated with any package will cause
15881     * an {@link IllegalArgumentException} to be thrown.
15882     *
15883     * @param key The key identifying the tag
15884     * @param tag An Object to tag the view with
15885     *
15886     * @throws IllegalArgumentException If they specified key is not valid
15887     *
15888     * @see #setTag(Object)
15889     * @see #getTag(int)
15890     */
15891    public void setTag(int key, final Object tag) {
15892        // If the package id is 0x00 or 0x01, it's either an undefined package
15893        // or a framework id
15894        if ((key >>> 24) < 2) {
15895            throw new IllegalArgumentException("The key must be an application-specific "
15896                    + "resource id.");
15897        }
15898
15899        setKeyedTag(key, tag);
15900    }
15901
15902    /**
15903     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15904     * framework id.
15905     *
15906     * @hide
15907     */
15908    public void setTagInternal(int key, Object tag) {
15909        if ((key >>> 24) != 0x1) {
15910            throw new IllegalArgumentException("The key must be a framework-specific "
15911                    + "resource id.");
15912        }
15913
15914        setKeyedTag(key, tag);
15915    }
15916
15917    private void setKeyedTag(int key, Object tag) {
15918        if (mKeyedTags == null) {
15919            mKeyedTags = new SparseArray<Object>(2);
15920        }
15921
15922        mKeyedTags.put(key, tag);
15923    }
15924
15925    /**
15926     * Prints information about this view in the log output, with the tag
15927     * {@link #VIEW_LOG_TAG}.
15928     *
15929     * @hide
15930     */
15931    public void debug() {
15932        debug(0);
15933    }
15934
15935    /**
15936     * Prints information about this view in the log output, with the tag
15937     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15938     * indentation defined by the <code>depth</code>.
15939     *
15940     * @param depth the indentation level
15941     *
15942     * @hide
15943     */
15944    protected void debug(int depth) {
15945        String output = debugIndent(depth - 1);
15946
15947        output += "+ " + this;
15948        int id = getId();
15949        if (id != -1) {
15950            output += " (id=" + id + ")";
15951        }
15952        Object tag = getTag();
15953        if (tag != null) {
15954            output += " (tag=" + tag + ")";
15955        }
15956        Log.d(VIEW_LOG_TAG, output);
15957
15958        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15959            output = debugIndent(depth) + " FOCUSED";
15960            Log.d(VIEW_LOG_TAG, output);
15961        }
15962
15963        output = debugIndent(depth);
15964        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15965                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15966                + "} ";
15967        Log.d(VIEW_LOG_TAG, output);
15968
15969        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15970                || mPaddingBottom != 0) {
15971            output = debugIndent(depth);
15972            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15973                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15974            Log.d(VIEW_LOG_TAG, output);
15975        }
15976
15977        output = debugIndent(depth);
15978        output += "mMeasureWidth=" + mMeasuredWidth +
15979                " mMeasureHeight=" + mMeasuredHeight;
15980        Log.d(VIEW_LOG_TAG, output);
15981
15982        output = debugIndent(depth);
15983        if (mLayoutParams == null) {
15984            output += "BAD! no layout params";
15985        } else {
15986            output = mLayoutParams.debug(output);
15987        }
15988        Log.d(VIEW_LOG_TAG, output);
15989
15990        output = debugIndent(depth);
15991        output += "flags={";
15992        output += View.printFlags(mViewFlags);
15993        output += "}";
15994        Log.d(VIEW_LOG_TAG, output);
15995
15996        output = debugIndent(depth);
15997        output += "privateFlags={";
15998        output += View.printPrivateFlags(mPrivateFlags);
15999        output += "}";
16000        Log.d(VIEW_LOG_TAG, output);
16001    }
16002
16003    /**
16004     * Creates a string of whitespaces used for indentation.
16005     *
16006     * @param depth the indentation level
16007     * @return a String containing (depth * 2 + 3) * 2 white spaces
16008     *
16009     * @hide
16010     */
16011    protected static String debugIndent(int depth) {
16012        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16013        for (int i = 0; i < (depth * 2) + 3; i++) {
16014            spaces.append(' ').append(' ');
16015        }
16016        return spaces.toString();
16017    }
16018
16019    /**
16020     * <p>Return the offset of the widget's text baseline from the widget's top
16021     * boundary. If this widget does not support baseline alignment, this
16022     * method returns -1. </p>
16023     *
16024     * @return the offset of the baseline within the widget's bounds or -1
16025     *         if baseline alignment is not supported
16026     */
16027    @ViewDebug.ExportedProperty(category = "layout")
16028    public int getBaseline() {
16029        return -1;
16030    }
16031
16032    /**
16033     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16034     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16035     * a layout pass.
16036     *
16037     * @return whether the view hierarchy is currently undergoing a layout pass
16038     */
16039    public boolean isInLayout() {
16040        ViewRootImpl viewRoot = getViewRootImpl();
16041        return (viewRoot != null && viewRoot.isInLayout());
16042    }
16043
16044    /**
16045     * Call this when something has changed which has invalidated the
16046     * layout of this view. This will schedule a layout pass of the view
16047     * tree. This should not be called while the view hierarchy is currently in a layout
16048     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16049     * end of the current layout pass (and then layout will run again) or after the current
16050     * frame is drawn and the next layout occurs.
16051     *
16052     * <p>Subclasses which override this method should call the superclass method to
16053     * handle possible request-during-layout errors correctly.</p>
16054     */
16055    public void requestLayout() {
16056        if (mMeasureCache != null) mMeasureCache.clear();
16057
16058        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16059            // Only trigger request-during-layout logic if this is the view requesting it,
16060            // not the views in its parent hierarchy
16061            ViewRootImpl viewRoot = getViewRootImpl();
16062            if (viewRoot != null && viewRoot.isInLayout()) {
16063                if (!viewRoot.requestLayoutDuringLayout(this)) {
16064                    return;
16065                }
16066            }
16067            mAttachInfo.mViewRequestingLayout = this;
16068        }
16069
16070        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16071        mPrivateFlags |= PFLAG_INVALIDATED;
16072
16073        if (mParent != null && !mParent.isLayoutRequested()) {
16074            mParent.requestLayout();
16075        }
16076        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16077            mAttachInfo.mViewRequestingLayout = null;
16078        }
16079    }
16080
16081    /**
16082     * Forces this view to be laid out during the next layout pass.
16083     * This method does not call requestLayout() or forceLayout()
16084     * on the parent.
16085     */
16086    public void forceLayout() {
16087        if (mMeasureCache != null) mMeasureCache.clear();
16088
16089        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16090        mPrivateFlags |= PFLAG_INVALIDATED;
16091    }
16092
16093    /**
16094     * <p>
16095     * This is called to find out how big a view should be. The parent
16096     * supplies constraint information in the width and height parameters.
16097     * </p>
16098     *
16099     * <p>
16100     * The actual measurement work of a view is performed in
16101     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16102     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16103     * </p>
16104     *
16105     *
16106     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16107     *        parent
16108     * @param heightMeasureSpec Vertical space requirements as imposed by the
16109     *        parent
16110     *
16111     * @see #onMeasure(int, int)
16112     */
16113    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16114        boolean optical = isLayoutModeOptical(this);
16115        if (optical != isLayoutModeOptical(mParent)) {
16116            Insets insets = getOpticalInsets();
16117            int oWidth  = insets.left + insets.right;
16118            int oHeight = insets.top  + insets.bottom;
16119            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16120            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16121        }
16122
16123        // Suppress sign extension for the low bytes
16124        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16125        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16126
16127        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16128                widthMeasureSpec != mOldWidthMeasureSpec ||
16129                heightMeasureSpec != mOldHeightMeasureSpec) {
16130
16131            // first clears the measured dimension flag
16132            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16133
16134            resolveRtlPropertiesIfNeeded();
16135
16136            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16137                    mMeasureCache.indexOfKey(key);
16138            if (cacheIndex < 0) {
16139                // measure ourselves, this should set the measured dimension flag back
16140                onMeasure(widthMeasureSpec, heightMeasureSpec);
16141                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16142            } else {
16143                long value = mMeasureCache.valueAt(cacheIndex);
16144                // Casting a long to int drops the high 32 bits, no mask needed
16145                setMeasuredDimension((int) (value >> 32), (int) value);
16146                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16147            }
16148
16149            // flag not set, setMeasuredDimension() was not invoked, we raise
16150            // an exception to warn the developer
16151            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16152                throw new IllegalStateException("onMeasure() did not set the"
16153                        + " measured dimension by calling"
16154                        + " setMeasuredDimension()");
16155            }
16156
16157            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16158        }
16159
16160        mOldWidthMeasureSpec = widthMeasureSpec;
16161        mOldHeightMeasureSpec = heightMeasureSpec;
16162
16163        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16164                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16165    }
16166
16167    /**
16168     * <p>
16169     * Measure the view and its content to determine the measured width and the
16170     * measured height. This method is invoked by {@link #measure(int, int)} and
16171     * should be overriden by subclasses to provide accurate and efficient
16172     * measurement of their contents.
16173     * </p>
16174     *
16175     * <p>
16176     * <strong>CONTRACT:</strong> When overriding this method, you
16177     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16178     * measured width and height of this view. Failure to do so will trigger an
16179     * <code>IllegalStateException</code>, thrown by
16180     * {@link #measure(int, int)}. Calling the superclass'
16181     * {@link #onMeasure(int, int)} is a valid use.
16182     * </p>
16183     *
16184     * <p>
16185     * The base class implementation of measure defaults to the background size,
16186     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16187     * override {@link #onMeasure(int, int)} to provide better measurements of
16188     * their content.
16189     * </p>
16190     *
16191     * <p>
16192     * If this method is overridden, it is the subclass's responsibility to make
16193     * sure the measured height and width are at least the view's minimum height
16194     * and width ({@link #getSuggestedMinimumHeight()} and
16195     * {@link #getSuggestedMinimumWidth()}).
16196     * </p>
16197     *
16198     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16199     *                         The requirements are encoded with
16200     *                         {@link android.view.View.MeasureSpec}.
16201     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16202     *                         The requirements are encoded with
16203     *                         {@link android.view.View.MeasureSpec}.
16204     *
16205     * @see #getMeasuredWidth()
16206     * @see #getMeasuredHeight()
16207     * @see #setMeasuredDimension(int, int)
16208     * @see #getSuggestedMinimumHeight()
16209     * @see #getSuggestedMinimumWidth()
16210     * @see android.view.View.MeasureSpec#getMode(int)
16211     * @see android.view.View.MeasureSpec#getSize(int)
16212     */
16213    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16214        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16215                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16216    }
16217
16218    /**
16219     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16220     * measured width and measured height. Failing to do so will trigger an
16221     * exception at measurement time.</p>
16222     *
16223     * @param measuredWidth The measured width of this view.  May be a complex
16224     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16225     * {@link #MEASURED_STATE_TOO_SMALL}.
16226     * @param measuredHeight The measured height of this view.  May be a complex
16227     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16228     * {@link #MEASURED_STATE_TOO_SMALL}.
16229     */
16230    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16231        boolean optical = isLayoutModeOptical(this);
16232        if (optical != isLayoutModeOptical(mParent)) {
16233            Insets insets = getOpticalInsets();
16234            int opticalWidth  = insets.left + insets.right;
16235            int opticalHeight = insets.top  + insets.bottom;
16236
16237            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16238            measuredHeight += optical ? opticalHeight : -opticalHeight;
16239        }
16240        mMeasuredWidth = measuredWidth;
16241        mMeasuredHeight = measuredHeight;
16242
16243        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16244    }
16245
16246    /**
16247     * Merge two states as returned by {@link #getMeasuredState()}.
16248     * @param curState The current state as returned from a view or the result
16249     * of combining multiple views.
16250     * @param newState The new view state to combine.
16251     * @return Returns a new integer reflecting the combination of the two
16252     * states.
16253     */
16254    public static int combineMeasuredStates(int curState, int newState) {
16255        return curState | newState;
16256    }
16257
16258    /**
16259     * Version of {@link #resolveSizeAndState(int, int, int)}
16260     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16261     */
16262    public static int resolveSize(int size, int measureSpec) {
16263        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16264    }
16265
16266    /**
16267     * Utility to reconcile a desired size and state, with constraints imposed
16268     * by a MeasureSpec.  Will take the desired size, unless a different size
16269     * is imposed by the constraints.  The returned value is a compound integer,
16270     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16271     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16272     * size is smaller than the size the view wants to be.
16273     *
16274     * @param size How big the view wants to be
16275     * @param measureSpec Constraints imposed by the parent
16276     * @return Size information bit mask as defined by
16277     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16278     */
16279    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16280        int result = size;
16281        int specMode = MeasureSpec.getMode(measureSpec);
16282        int specSize =  MeasureSpec.getSize(measureSpec);
16283        switch (specMode) {
16284        case MeasureSpec.UNSPECIFIED:
16285            result = size;
16286            break;
16287        case MeasureSpec.AT_MOST:
16288            if (specSize < size) {
16289                result = specSize | MEASURED_STATE_TOO_SMALL;
16290            } else {
16291                result = size;
16292            }
16293            break;
16294        case MeasureSpec.EXACTLY:
16295            result = specSize;
16296            break;
16297        }
16298        return result | (childMeasuredState&MEASURED_STATE_MASK);
16299    }
16300
16301    /**
16302     * Utility to return a default size. Uses the supplied size if the
16303     * MeasureSpec imposed no constraints. Will get larger if allowed
16304     * by the MeasureSpec.
16305     *
16306     * @param size Default size for this view
16307     * @param measureSpec Constraints imposed by the parent
16308     * @return The size this view should be.
16309     */
16310    public static int getDefaultSize(int size, int measureSpec) {
16311        int result = size;
16312        int specMode = MeasureSpec.getMode(measureSpec);
16313        int specSize = MeasureSpec.getSize(measureSpec);
16314
16315        switch (specMode) {
16316        case MeasureSpec.UNSPECIFIED:
16317            result = size;
16318            break;
16319        case MeasureSpec.AT_MOST:
16320        case MeasureSpec.EXACTLY:
16321            result = specSize;
16322            break;
16323        }
16324        return result;
16325    }
16326
16327    /**
16328     * Returns the suggested minimum height that the view should use. This
16329     * returns the maximum of the view's minimum height
16330     * and the background's minimum height
16331     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16332     * <p>
16333     * When being used in {@link #onMeasure(int, int)}, the caller should still
16334     * ensure the returned height is within the requirements of the parent.
16335     *
16336     * @return The suggested minimum height of the view.
16337     */
16338    protected int getSuggestedMinimumHeight() {
16339        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16340
16341    }
16342
16343    /**
16344     * Returns the suggested minimum width that the view should use. This
16345     * returns the maximum of the view's minimum width)
16346     * and the background's minimum width
16347     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16348     * <p>
16349     * When being used in {@link #onMeasure(int, int)}, the caller should still
16350     * ensure the returned width is within the requirements of the parent.
16351     *
16352     * @return The suggested minimum width of the view.
16353     */
16354    protected int getSuggestedMinimumWidth() {
16355        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16356    }
16357
16358    /**
16359     * Returns the minimum height of the view.
16360     *
16361     * @return the minimum height the view will try to be.
16362     *
16363     * @see #setMinimumHeight(int)
16364     *
16365     * @attr ref android.R.styleable#View_minHeight
16366     */
16367    public int getMinimumHeight() {
16368        return mMinHeight;
16369    }
16370
16371    /**
16372     * Sets the minimum height of the view. It is not guaranteed the view will
16373     * be able to achieve this minimum height (for example, if its parent layout
16374     * constrains it with less available height).
16375     *
16376     * @param minHeight The minimum height the view will try to be.
16377     *
16378     * @see #getMinimumHeight()
16379     *
16380     * @attr ref android.R.styleable#View_minHeight
16381     */
16382    public void setMinimumHeight(int minHeight) {
16383        mMinHeight = minHeight;
16384        requestLayout();
16385    }
16386
16387    /**
16388     * Returns the minimum width of the view.
16389     *
16390     * @return the minimum width the view will try to be.
16391     *
16392     * @see #setMinimumWidth(int)
16393     *
16394     * @attr ref android.R.styleable#View_minWidth
16395     */
16396    public int getMinimumWidth() {
16397        return mMinWidth;
16398    }
16399
16400    /**
16401     * Sets the minimum width of the view. It is not guaranteed the view will
16402     * be able to achieve this minimum width (for example, if its parent layout
16403     * constrains it with less available width).
16404     *
16405     * @param minWidth The minimum width the view will try to be.
16406     *
16407     * @see #getMinimumWidth()
16408     *
16409     * @attr ref android.R.styleable#View_minWidth
16410     */
16411    public void setMinimumWidth(int minWidth) {
16412        mMinWidth = minWidth;
16413        requestLayout();
16414
16415    }
16416
16417    /**
16418     * Get the animation currently associated with this view.
16419     *
16420     * @return The animation that is currently playing or
16421     *         scheduled to play for this view.
16422     */
16423    public Animation getAnimation() {
16424        return mCurrentAnimation;
16425    }
16426
16427    /**
16428     * Start the specified animation now.
16429     *
16430     * @param animation the animation to start now
16431     */
16432    public void startAnimation(Animation animation) {
16433        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16434        setAnimation(animation);
16435        invalidateParentCaches();
16436        invalidate(true);
16437    }
16438
16439    /**
16440     * Cancels any animations for this view.
16441     */
16442    public void clearAnimation() {
16443        if (mCurrentAnimation != null) {
16444            mCurrentAnimation.detach();
16445        }
16446        mCurrentAnimation = null;
16447        invalidateParentIfNeeded();
16448    }
16449
16450    /**
16451     * Sets the next animation to play for this view.
16452     * If you want the animation to play immediately, use
16453     * {@link #startAnimation(android.view.animation.Animation)} instead.
16454     * This method provides allows fine-grained
16455     * control over the start time and invalidation, but you
16456     * must make sure that 1) the animation has a start time set, and
16457     * 2) the view's parent (which controls animations on its children)
16458     * will be invalidated when the animation is supposed to
16459     * start.
16460     *
16461     * @param animation The next animation, or null.
16462     */
16463    public void setAnimation(Animation animation) {
16464        mCurrentAnimation = animation;
16465
16466        if (animation != null) {
16467            // If the screen is off assume the animation start time is now instead of
16468            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16469            // would cause the animation to start when the screen turns back on
16470            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16471                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16472                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16473            }
16474            animation.reset();
16475        }
16476    }
16477
16478    /**
16479     * Invoked by a parent ViewGroup to notify the start of the animation
16480     * currently associated with this view. If you override this method,
16481     * always call super.onAnimationStart();
16482     *
16483     * @see #setAnimation(android.view.animation.Animation)
16484     * @see #getAnimation()
16485     */
16486    protected void onAnimationStart() {
16487        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16488    }
16489
16490    /**
16491     * Invoked by a parent ViewGroup to notify the end of the animation
16492     * currently associated with this view. If you override this method,
16493     * always call super.onAnimationEnd();
16494     *
16495     * @see #setAnimation(android.view.animation.Animation)
16496     * @see #getAnimation()
16497     */
16498    protected void onAnimationEnd() {
16499        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16500    }
16501
16502    /**
16503     * Invoked if there is a Transform that involves alpha. Subclass that can
16504     * draw themselves with the specified alpha should return true, and then
16505     * respect that alpha when their onDraw() is called. If this returns false
16506     * then the view may be redirected to draw into an offscreen buffer to
16507     * fulfill the request, which will look fine, but may be slower than if the
16508     * subclass handles it internally. The default implementation returns false.
16509     *
16510     * @param alpha The alpha (0..255) to apply to the view's drawing
16511     * @return true if the view can draw with the specified alpha.
16512     */
16513    protected boolean onSetAlpha(int alpha) {
16514        return false;
16515    }
16516
16517    /**
16518     * This is used by the RootView to perform an optimization when
16519     * the view hierarchy contains one or several SurfaceView.
16520     * SurfaceView is always considered transparent, but its children are not,
16521     * therefore all View objects remove themselves from the global transparent
16522     * region (passed as a parameter to this function).
16523     *
16524     * @param region The transparent region for this ViewAncestor (window).
16525     *
16526     * @return Returns true if the effective visibility of the view at this
16527     * point is opaque, regardless of the transparent region; returns false
16528     * if it is possible for underlying windows to be seen behind the view.
16529     *
16530     * {@hide}
16531     */
16532    public boolean gatherTransparentRegion(Region region) {
16533        final AttachInfo attachInfo = mAttachInfo;
16534        if (region != null && attachInfo != null) {
16535            final int pflags = mPrivateFlags;
16536            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16537                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16538                // remove it from the transparent region.
16539                final int[] location = attachInfo.mTransparentLocation;
16540                getLocationInWindow(location);
16541                region.op(location[0], location[1], location[0] + mRight - mLeft,
16542                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16543            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16544                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16545                // exists, so we remove the background drawable's non-transparent
16546                // parts from this transparent region.
16547                applyDrawableToTransparentRegion(mBackground, region);
16548            }
16549        }
16550        return true;
16551    }
16552
16553    /**
16554     * Play a sound effect for this view.
16555     *
16556     * <p>The framework will play sound effects for some built in actions, such as
16557     * clicking, but you may wish to play these effects in your widget,
16558     * for instance, for internal navigation.
16559     *
16560     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16561     * {@link #isSoundEffectsEnabled()} is true.
16562     *
16563     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16564     */
16565    public void playSoundEffect(int soundConstant) {
16566        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16567            return;
16568        }
16569        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16570    }
16571
16572    /**
16573     * BZZZTT!!1!
16574     *
16575     * <p>Provide haptic feedback to the user for this view.
16576     *
16577     * <p>The framework will provide haptic feedback for some built in actions,
16578     * such as long presses, but you may wish to provide feedback for your
16579     * own widget.
16580     *
16581     * <p>The feedback will only be performed if
16582     * {@link #isHapticFeedbackEnabled()} is true.
16583     *
16584     * @param feedbackConstant One of the constants defined in
16585     * {@link HapticFeedbackConstants}
16586     */
16587    public boolean performHapticFeedback(int feedbackConstant) {
16588        return performHapticFeedback(feedbackConstant, 0);
16589    }
16590
16591    /**
16592     * BZZZTT!!1!
16593     *
16594     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16595     *
16596     * @param feedbackConstant One of the constants defined in
16597     * {@link HapticFeedbackConstants}
16598     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16599     */
16600    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16601        if (mAttachInfo == null) {
16602            return false;
16603        }
16604        //noinspection SimplifiableIfStatement
16605        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16606                && !isHapticFeedbackEnabled()) {
16607            return false;
16608        }
16609        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16610                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16611    }
16612
16613    /**
16614     * Request that the visibility of the status bar or other screen/window
16615     * decorations be changed.
16616     *
16617     * <p>This method is used to put the over device UI into temporary modes
16618     * where the user's attention is focused more on the application content,
16619     * by dimming or hiding surrounding system affordances.  This is typically
16620     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16621     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16622     * to be placed behind the action bar (and with these flags other system
16623     * affordances) so that smooth transitions between hiding and showing them
16624     * can be done.
16625     *
16626     * <p>Two representative examples of the use of system UI visibility is
16627     * implementing a content browsing application (like a magazine reader)
16628     * and a video playing application.
16629     *
16630     * <p>The first code shows a typical implementation of a View in a content
16631     * browsing application.  In this implementation, the application goes
16632     * into a content-oriented mode by hiding the status bar and action bar,
16633     * and putting the navigation elements into lights out mode.  The user can
16634     * then interact with content while in this mode.  Such an application should
16635     * provide an easy way for the user to toggle out of the mode (such as to
16636     * check information in the status bar or access notifications).  In the
16637     * implementation here, this is done simply by tapping on the content.
16638     *
16639     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16640     *      content}
16641     *
16642     * <p>This second code sample shows a typical implementation of a View
16643     * in a video playing application.  In this situation, while the video is
16644     * playing the application would like to go into a complete full-screen mode,
16645     * to use as much of the display as possible for the video.  When in this state
16646     * the user can not interact with the application; the system intercepts
16647     * touching on the screen to pop the UI out of full screen mode.  See
16648     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16649     *
16650     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16651     *      content}
16652     *
16653     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16654     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16655     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16656     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
16657     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16658     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16659     */
16660    public void setSystemUiVisibility(int visibility) {
16661        if (visibility != mSystemUiVisibility) {
16662            mSystemUiVisibility = visibility;
16663            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16664                mParent.recomputeViewAttributes(this);
16665            }
16666        }
16667    }
16668
16669    /**
16670     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
16671     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16672     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16673     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16674     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
16675     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16676     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16677     */
16678    public int getSystemUiVisibility() {
16679        return mSystemUiVisibility;
16680    }
16681
16682    /**
16683     * Returns the current system UI visibility that is currently set for
16684     * the entire window.  This is the combination of the
16685     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16686     * views in the window.
16687     */
16688    public int getWindowSystemUiVisibility() {
16689        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16690    }
16691
16692    /**
16693     * Override to find out when the window's requested system UI visibility
16694     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16695     * This is different from the callbacks received through
16696     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16697     * in that this is only telling you about the local request of the window,
16698     * not the actual values applied by the system.
16699     */
16700    public void onWindowSystemUiVisibilityChanged(int visible) {
16701    }
16702
16703    /**
16704     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16705     * the view hierarchy.
16706     */
16707    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16708        onWindowSystemUiVisibilityChanged(visible);
16709    }
16710
16711    /**
16712     * Set a listener to receive callbacks when the visibility of the system bar changes.
16713     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16714     */
16715    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16716        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16717        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16718            mParent.recomputeViewAttributes(this);
16719        }
16720    }
16721
16722    /**
16723     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16724     * the view hierarchy.
16725     */
16726    public void dispatchSystemUiVisibilityChanged(int visibility) {
16727        ListenerInfo li = mListenerInfo;
16728        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16729            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16730                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16731        }
16732    }
16733
16734    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16735        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16736        if (val != mSystemUiVisibility) {
16737            setSystemUiVisibility(val);
16738            return true;
16739        }
16740        return false;
16741    }
16742
16743    /** @hide */
16744    public void setDisabledSystemUiVisibility(int flags) {
16745        if (mAttachInfo != null) {
16746            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16747                mAttachInfo.mDisabledSystemUiVisibility = flags;
16748                if (mParent != null) {
16749                    mParent.recomputeViewAttributes(this);
16750                }
16751            }
16752        }
16753    }
16754
16755    /**
16756     * Creates an image that the system displays during the drag and drop
16757     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16758     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16759     * appearance as the given View. The default also positions the center of the drag shadow
16760     * directly under the touch point. If no View is provided (the constructor with no parameters
16761     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16762     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16763     * default is an invisible drag shadow.
16764     * <p>
16765     * You are not required to use the View you provide to the constructor as the basis of the
16766     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16767     * anything you want as the drag shadow.
16768     * </p>
16769     * <p>
16770     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16771     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16772     *  size and position of the drag shadow. It uses this data to construct a
16773     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16774     *  so that your application can draw the shadow image in the Canvas.
16775     * </p>
16776     *
16777     * <div class="special reference">
16778     * <h3>Developer Guides</h3>
16779     * <p>For a guide to implementing drag and drop features, read the
16780     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16781     * </div>
16782     */
16783    public static class DragShadowBuilder {
16784        private final WeakReference<View> mView;
16785
16786        /**
16787         * Constructs a shadow image builder based on a View. By default, the resulting drag
16788         * shadow will have the same appearance and dimensions as the View, with the touch point
16789         * over the center of the View.
16790         * @param view A View. Any View in scope can be used.
16791         */
16792        public DragShadowBuilder(View view) {
16793            mView = new WeakReference<View>(view);
16794        }
16795
16796        /**
16797         * Construct a shadow builder object with no associated View.  This
16798         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16799         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16800         * to supply the drag shadow's dimensions and appearance without
16801         * reference to any View object. If they are not overridden, then the result is an
16802         * invisible drag shadow.
16803         */
16804        public DragShadowBuilder() {
16805            mView = new WeakReference<View>(null);
16806        }
16807
16808        /**
16809         * Returns the View object that had been passed to the
16810         * {@link #View.DragShadowBuilder(View)}
16811         * constructor.  If that View parameter was {@code null} or if the
16812         * {@link #View.DragShadowBuilder()}
16813         * constructor was used to instantiate the builder object, this method will return
16814         * null.
16815         *
16816         * @return The View object associate with this builder object.
16817         */
16818        @SuppressWarnings({"JavadocReference"})
16819        final public View getView() {
16820            return mView.get();
16821        }
16822
16823        /**
16824         * Provides the metrics for the shadow image. These include the dimensions of
16825         * the shadow image, and the point within that shadow that should
16826         * be centered under the touch location while dragging.
16827         * <p>
16828         * The default implementation sets the dimensions of the shadow to be the
16829         * same as the dimensions of the View itself and centers the shadow under
16830         * the touch point.
16831         * </p>
16832         *
16833         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16834         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16835         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16836         * image.
16837         *
16838         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16839         * shadow image that should be underneath the touch point during the drag and drop
16840         * operation. Your application must set {@link android.graphics.Point#x} to the
16841         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16842         */
16843        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16844            final View view = mView.get();
16845            if (view != null) {
16846                shadowSize.set(view.getWidth(), view.getHeight());
16847                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16848            } else {
16849                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16850            }
16851        }
16852
16853        /**
16854         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16855         * based on the dimensions it received from the
16856         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16857         *
16858         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16859         */
16860        public void onDrawShadow(Canvas canvas) {
16861            final View view = mView.get();
16862            if (view != null) {
16863                view.draw(canvas);
16864            } else {
16865                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16866            }
16867        }
16868    }
16869
16870    /**
16871     * Starts a drag and drop operation. When your application calls this method, it passes a
16872     * {@link android.view.View.DragShadowBuilder} object to the system. The
16873     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16874     * to get metrics for the drag shadow, and then calls the object's
16875     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16876     * <p>
16877     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16878     *  drag events to all the View objects in your application that are currently visible. It does
16879     *  this either by calling the View object's drag listener (an implementation of
16880     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16881     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16882     *  Both are passed a {@link android.view.DragEvent} object that has a
16883     *  {@link android.view.DragEvent#getAction()} value of
16884     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16885     * </p>
16886     * <p>
16887     * Your application can invoke startDrag() on any attached View object. The View object does not
16888     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16889     * be related to the View the user selected for dragging.
16890     * </p>
16891     * @param data A {@link android.content.ClipData} object pointing to the data to be
16892     * transferred by the drag and drop operation.
16893     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16894     * drag shadow.
16895     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16896     * drop operation. This Object is put into every DragEvent object sent by the system during the
16897     * current drag.
16898     * <p>
16899     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16900     * to the target Views. For example, it can contain flags that differentiate between a
16901     * a copy operation and a move operation.
16902     * </p>
16903     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16904     * so the parameter should be set to 0.
16905     * @return {@code true} if the method completes successfully, or
16906     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16907     * do a drag, and so no drag operation is in progress.
16908     */
16909    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16910            Object myLocalState, int flags) {
16911        if (ViewDebug.DEBUG_DRAG) {
16912            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16913        }
16914        boolean okay = false;
16915
16916        Point shadowSize = new Point();
16917        Point shadowTouchPoint = new Point();
16918        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16919
16920        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16921                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16922            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16923        }
16924
16925        if (ViewDebug.DEBUG_DRAG) {
16926            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16927                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16928        }
16929        Surface surface = new Surface();
16930        try {
16931            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16932                    flags, shadowSize.x, shadowSize.y, surface);
16933            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16934                    + " surface=" + surface);
16935            if (token != null) {
16936                Canvas canvas = surface.lockCanvas(null);
16937                try {
16938                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16939                    shadowBuilder.onDrawShadow(canvas);
16940                } finally {
16941                    surface.unlockCanvasAndPost(canvas);
16942                }
16943
16944                final ViewRootImpl root = getViewRootImpl();
16945
16946                // Cache the local state object for delivery with DragEvents
16947                root.setLocalDragState(myLocalState);
16948
16949                // repurpose 'shadowSize' for the last touch point
16950                root.getLastTouchPoint(shadowSize);
16951
16952                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16953                        shadowSize.x, shadowSize.y,
16954                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16955                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16956
16957                // Off and running!  Release our local surface instance; the drag
16958                // shadow surface is now managed by the system process.
16959                surface.release();
16960            }
16961        } catch (Exception e) {
16962            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16963            surface.destroy();
16964        }
16965
16966        return okay;
16967    }
16968
16969    /**
16970     * Handles drag events sent by the system following a call to
16971     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16972     *<p>
16973     * When the system calls this method, it passes a
16974     * {@link android.view.DragEvent} object. A call to
16975     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16976     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16977     * operation.
16978     * @param event The {@link android.view.DragEvent} sent by the system.
16979     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16980     * in DragEvent, indicating the type of drag event represented by this object.
16981     * @return {@code true} if the method was successful, otherwise {@code false}.
16982     * <p>
16983     *  The method should return {@code true} in response to an action type of
16984     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16985     *  operation.
16986     * </p>
16987     * <p>
16988     *  The method should also return {@code true} in response to an action type of
16989     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16990     *  {@code false} if it didn't.
16991     * </p>
16992     */
16993    public boolean onDragEvent(DragEvent event) {
16994        return false;
16995    }
16996
16997    /**
16998     * Detects if this View is enabled and has a drag event listener.
16999     * If both are true, then it calls the drag event listener with the
17000     * {@link android.view.DragEvent} it received. If the drag event listener returns
17001     * {@code true}, then dispatchDragEvent() returns {@code true}.
17002     * <p>
17003     * For all other cases, the method calls the
17004     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17005     * method and returns its result.
17006     * </p>
17007     * <p>
17008     * This ensures that a drag event is always consumed, even if the View does not have a drag
17009     * event listener. However, if the View has a listener and the listener returns true, then
17010     * onDragEvent() is not called.
17011     * </p>
17012     */
17013    public boolean dispatchDragEvent(DragEvent event) {
17014        ListenerInfo li = mListenerInfo;
17015        //noinspection SimplifiableIfStatement
17016        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17017                && li.mOnDragListener.onDrag(this, event)) {
17018            return true;
17019        }
17020        return onDragEvent(event);
17021    }
17022
17023    boolean canAcceptDrag() {
17024        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17025    }
17026
17027    /**
17028     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17029     * it is ever exposed at all.
17030     * @hide
17031     */
17032    public void onCloseSystemDialogs(String reason) {
17033    }
17034
17035    /**
17036     * Given a Drawable whose bounds have been set to draw into this view,
17037     * update a Region being computed for
17038     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17039     * that any non-transparent parts of the Drawable are removed from the
17040     * given transparent region.
17041     *
17042     * @param dr The Drawable whose transparency is to be applied to the region.
17043     * @param region A Region holding the current transparency information,
17044     * where any parts of the region that are set are considered to be
17045     * transparent.  On return, this region will be modified to have the
17046     * transparency information reduced by the corresponding parts of the
17047     * Drawable that are not transparent.
17048     * {@hide}
17049     */
17050    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17051        if (DBG) {
17052            Log.i("View", "Getting transparent region for: " + this);
17053        }
17054        final Region r = dr.getTransparentRegion();
17055        final Rect db = dr.getBounds();
17056        final AttachInfo attachInfo = mAttachInfo;
17057        if (r != null && attachInfo != null) {
17058            final int w = getRight()-getLeft();
17059            final int h = getBottom()-getTop();
17060            if (db.left > 0) {
17061                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17062                r.op(0, 0, db.left, h, Region.Op.UNION);
17063            }
17064            if (db.right < w) {
17065                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17066                r.op(db.right, 0, w, h, Region.Op.UNION);
17067            }
17068            if (db.top > 0) {
17069                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17070                r.op(0, 0, w, db.top, Region.Op.UNION);
17071            }
17072            if (db.bottom < h) {
17073                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17074                r.op(0, db.bottom, w, h, Region.Op.UNION);
17075            }
17076            final int[] location = attachInfo.mTransparentLocation;
17077            getLocationInWindow(location);
17078            r.translate(location[0], location[1]);
17079            region.op(r, Region.Op.INTERSECT);
17080        } else {
17081            region.op(db, Region.Op.DIFFERENCE);
17082        }
17083    }
17084
17085    private void checkForLongClick(int delayOffset) {
17086        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17087            mHasPerformedLongPress = false;
17088
17089            if (mPendingCheckForLongPress == null) {
17090                mPendingCheckForLongPress = new CheckForLongPress();
17091            }
17092            mPendingCheckForLongPress.rememberWindowAttachCount();
17093            postDelayed(mPendingCheckForLongPress,
17094                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17095        }
17096    }
17097
17098    /**
17099     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17100     * LayoutInflater} class, which provides a full range of options for view inflation.
17101     *
17102     * @param context The Context object for your activity or application.
17103     * @param resource The resource ID to inflate
17104     * @param root A view group that will be the parent.  Used to properly inflate the
17105     * layout_* parameters.
17106     * @see LayoutInflater
17107     */
17108    public static View inflate(Context context, int resource, ViewGroup root) {
17109        LayoutInflater factory = LayoutInflater.from(context);
17110        return factory.inflate(resource, root);
17111    }
17112
17113    /**
17114     * Scroll the view with standard behavior for scrolling beyond the normal
17115     * content boundaries. Views that call this method should override
17116     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17117     * results of an over-scroll operation.
17118     *
17119     * Views can use this method to handle any touch or fling-based scrolling.
17120     *
17121     * @param deltaX Change in X in pixels
17122     * @param deltaY Change in Y in pixels
17123     * @param scrollX Current X scroll value in pixels before applying deltaX
17124     * @param scrollY Current Y scroll value in pixels before applying deltaY
17125     * @param scrollRangeX Maximum content scroll range along the X axis
17126     * @param scrollRangeY Maximum content scroll range along the Y axis
17127     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17128     *          along the X axis.
17129     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17130     *          along the Y axis.
17131     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17132     * @return true if scrolling was clamped to an over-scroll boundary along either
17133     *          axis, false otherwise.
17134     */
17135    @SuppressWarnings({"UnusedParameters"})
17136    protected boolean overScrollBy(int deltaX, int deltaY,
17137            int scrollX, int scrollY,
17138            int scrollRangeX, int scrollRangeY,
17139            int maxOverScrollX, int maxOverScrollY,
17140            boolean isTouchEvent) {
17141        final int overScrollMode = mOverScrollMode;
17142        final boolean canScrollHorizontal =
17143                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17144        final boolean canScrollVertical =
17145                computeVerticalScrollRange() > computeVerticalScrollExtent();
17146        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17147                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17148        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17149                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17150
17151        int newScrollX = scrollX + deltaX;
17152        if (!overScrollHorizontal) {
17153            maxOverScrollX = 0;
17154        }
17155
17156        int newScrollY = scrollY + deltaY;
17157        if (!overScrollVertical) {
17158            maxOverScrollY = 0;
17159        }
17160
17161        // Clamp values if at the limits and record
17162        final int left = -maxOverScrollX;
17163        final int right = maxOverScrollX + scrollRangeX;
17164        final int top = -maxOverScrollY;
17165        final int bottom = maxOverScrollY + scrollRangeY;
17166
17167        boolean clampedX = false;
17168        if (newScrollX > right) {
17169            newScrollX = right;
17170            clampedX = true;
17171        } else if (newScrollX < left) {
17172            newScrollX = left;
17173            clampedX = true;
17174        }
17175
17176        boolean clampedY = false;
17177        if (newScrollY > bottom) {
17178            newScrollY = bottom;
17179            clampedY = true;
17180        } else if (newScrollY < top) {
17181            newScrollY = top;
17182            clampedY = true;
17183        }
17184
17185        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17186
17187        return clampedX || clampedY;
17188    }
17189
17190    /**
17191     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17192     * respond to the results of an over-scroll operation.
17193     *
17194     * @param scrollX New X scroll value in pixels
17195     * @param scrollY New Y scroll value in pixels
17196     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17197     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17198     */
17199    protected void onOverScrolled(int scrollX, int scrollY,
17200            boolean clampedX, boolean clampedY) {
17201        // Intentionally empty.
17202    }
17203
17204    /**
17205     * Returns the over-scroll mode for this view. The result will be
17206     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17207     * (allow over-scrolling only if the view content is larger than the container),
17208     * or {@link #OVER_SCROLL_NEVER}.
17209     *
17210     * @return This view's over-scroll mode.
17211     */
17212    public int getOverScrollMode() {
17213        return mOverScrollMode;
17214    }
17215
17216    /**
17217     * Set the over-scroll mode for this view. Valid over-scroll modes are
17218     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17219     * (allow over-scrolling only if the view content is larger than the container),
17220     * or {@link #OVER_SCROLL_NEVER}.
17221     *
17222     * Setting the over-scroll mode of a view will have an effect only if the
17223     * view is capable of scrolling.
17224     *
17225     * @param overScrollMode The new over-scroll mode for this view.
17226     */
17227    public void setOverScrollMode(int overScrollMode) {
17228        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17229                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17230                overScrollMode != OVER_SCROLL_NEVER) {
17231            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17232        }
17233        mOverScrollMode = overScrollMode;
17234    }
17235
17236    /**
17237     * Gets a scale factor that determines the distance the view should scroll
17238     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17239     * @return The vertical scroll scale factor.
17240     * @hide
17241     */
17242    protected float getVerticalScrollFactor() {
17243        if (mVerticalScrollFactor == 0) {
17244            TypedValue outValue = new TypedValue();
17245            if (!mContext.getTheme().resolveAttribute(
17246                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17247                throw new IllegalStateException(
17248                        "Expected theme to define listPreferredItemHeight.");
17249            }
17250            mVerticalScrollFactor = outValue.getDimension(
17251                    mContext.getResources().getDisplayMetrics());
17252        }
17253        return mVerticalScrollFactor;
17254    }
17255
17256    /**
17257     * Gets a scale factor that determines the distance the view should scroll
17258     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17259     * @return The horizontal scroll scale factor.
17260     * @hide
17261     */
17262    protected float getHorizontalScrollFactor() {
17263        // TODO: Should use something else.
17264        return getVerticalScrollFactor();
17265    }
17266
17267    /**
17268     * Return the value specifying the text direction or policy that was set with
17269     * {@link #setTextDirection(int)}.
17270     *
17271     * @return the defined text direction. It can be one of:
17272     *
17273     * {@link #TEXT_DIRECTION_INHERIT},
17274     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17275     * {@link #TEXT_DIRECTION_ANY_RTL},
17276     * {@link #TEXT_DIRECTION_LTR},
17277     * {@link #TEXT_DIRECTION_RTL},
17278     * {@link #TEXT_DIRECTION_LOCALE}
17279     *
17280     * @attr ref android.R.styleable#View_textDirection
17281     *
17282     * @hide
17283     */
17284    @ViewDebug.ExportedProperty(category = "text", mapping = {
17285            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17286            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17287            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17288            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17289            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17290            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17291    })
17292    public int getRawTextDirection() {
17293        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17294    }
17295
17296    /**
17297     * Set the text direction.
17298     *
17299     * @param textDirection the direction to set. Should be one of:
17300     *
17301     * {@link #TEXT_DIRECTION_INHERIT},
17302     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17303     * {@link #TEXT_DIRECTION_ANY_RTL},
17304     * {@link #TEXT_DIRECTION_LTR},
17305     * {@link #TEXT_DIRECTION_RTL},
17306     * {@link #TEXT_DIRECTION_LOCALE}
17307     *
17308     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17309     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17310     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17311     *
17312     * @attr ref android.R.styleable#View_textDirection
17313     */
17314    public void setTextDirection(int textDirection) {
17315        if (getRawTextDirection() != textDirection) {
17316            // Reset the current text direction and the resolved one
17317            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17318            resetResolvedTextDirection();
17319            // Set the new text direction
17320            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17321            // Do resolution
17322            resolveTextDirection();
17323            // Notify change
17324            onRtlPropertiesChanged(getLayoutDirection());
17325            // Refresh
17326            requestLayout();
17327            invalidate(true);
17328        }
17329    }
17330
17331    /**
17332     * Return the resolved text direction.
17333     *
17334     * @return the resolved text direction. Returns one of:
17335     *
17336     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17337     * {@link #TEXT_DIRECTION_ANY_RTL},
17338     * {@link #TEXT_DIRECTION_LTR},
17339     * {@link #TEXT_DIRECTION_RTL},
17340     * {@link #TEXT_DIRECTION_LOCALE}
17341     *
17342     * @attr ref android.R.styleable#View_textDirection
17343     */
17344    @ViewDebug.ExportedProperty(category = "text", mapping = {
17345            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17346            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17347            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17348            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17349            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17350            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17351    })
17352    public int getTextDirection() {
17353        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17354    }
17355
17356    /**
17357     * Resolve the text direction.
17358     *
17359     * @return true if resolution has been done, false otherwise.
17360     *
17361     * @hide
17362     */
17363    public boolean resolveTextDirection() {
17364        // Reset any previous text direction resolution
17365        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17366
17367        if (hasRtlSupport()) {
17368            // Set resolved text direction flag depending on text direction flag
17369            final int textDirection = getRawTextDirection();
17370            switch(textDirection) {
17371                case TEXT_DIRECTION_INHERIT:
17372                    if (!canResolveTextDirection()) {
17373                        // We cannot do the resolution if there is no parent, so use the default one
17374                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17375                        // Resolution will need to happen again later
17376                        return false;
17377                    }
17378
17379                    // Parent has not yet resolved, so we still return the default
17380                    try {
17381                        if (!mParent.isTextDirectionResolved()) {
17382                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17383                            // Resolution will need to happen again later
17384                            return false;
17385                        }
17386                    } catch (AbstractMethodError e) {
17387                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17388                                " does not fully implement ViewParent", e);
17389                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17390                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17391                        return true;
17392                    }
17393
17394                    // Set current resolved direction to the same value as the parent's one
17395                    int parentResolvedDirection;
17396                    try {
17397                        parentResolvedDirection = mParent.getTextDirection();
17398                    } catch (AbstractMethodError e) {
17399                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17400                                " does not fully implement ViewParent", e);
17401                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17402                    }
17403                    switch (parentResolvedDirection) {
17404                        case TEXT_DIRECTION_FIRST_STRONG:
17405                        case TEXT_DIRECTION_ANY_RTL:
17406                        case TEXT_DIRECTION_LTR:
17407                        case TEXT_DIRECTION_RTL:
17408                        case TEXT_DIRECTION_LOCALE:
17409                            mPrivateFlags2 |=
17410                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17411                            break;
17412                        default:
17413                            // Default resolved direction is "first strong" heuristic
17414                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17415                    }
17416                    break;
17417                case TEXT_DIRECTION_FIRST_STRONG:
17418                case TEXT_DIRECTION_ANY_RTL:
17419                case TEXT_DIRECTION_LTR:
17420                case TEXT_DIRECTION_RTL:
17421                case TEXT_DIRECTION_LOCALE:
17422                    // Resolved direction is the same as text direction
17423                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17424                    break;
17425                default:
17426                    // Default resolved direction is "first strong" heuristic
17427                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17428            }
17429        } else {
17430            // Default resolved direction is "first strong" heuristic
17431            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17432        }
17433
17434        // Set to resolved
17435        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17436        return true;
17437    }
17438
17439    /**
17440     * Check if text direction resolution can be done.
17441     *
17442     * @return true if text direction resolution can be done otherwise return false.
17443     */
17444    public boolean canResolveTextDirection() {
17445        switch (getRawTextDirection()) {
17446            case TEXT_DIRECTION_INHERIT:
17447                if (mParent != null) {
17448                    try {
17449                        return mParent.canResolveTextDirection();
17450                    } catch (AbstractMethodError e) {
17451                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17452                                " does not fully implement ViewParent", e);
17453                    }
17454                }
17455                return false;
17456
17457            default:
17458                return true;
17459        }
17460    }
17461
17462    /**
17463     * Reset resolved text direction. Text direction will be resolved during a call to
17464     * {@link #onMeasure(int, int)}.
17465     *
17466     * @hide
17467     */
17468    public void resetResolvedTextDirection() {
17469        // Reset any previous text direction resolution
17470        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17471        // Set to default value
17472        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17473    }
17474
17475    /**
17476     * @return true if text direction is inherited.
17477     *
17478     * @hide
17479     */
17480    public boolean isTextDirectionInherited() {
17481        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17482    }
17483
17484    /**
17485     * @return true if text direction is resolved.
17486     */
17487    public boolean isTextDirectionResolved() {
17488        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17489    }
17490
17491    /**
17492     * Return the value specifying the text alignment or policy that was set with
17493     * {@link #setTextAlignment(int)}.
17494     *
17495     * @return the defined text alignment. It can be one of:
17496     *
17497     * {@link #TEXT_ALIGNMENT_INHERIT},
17498     * {@link #TEXT_ALIGNMENT_GRAVITY},
17499     * {@link #TEXT_ALIGNMENT_CENTER},
17500     * {@link #TEXT_ALIGNMENT_TEXT_START},
17501     * {@link #TEXT_ALIGNMENT_TEXT_END},
17502     * {@link #TEXT_ALIGNMENT_VIEW_START},
17503     * {@link #TEXT_ALIGNMENT_VIEW_END}
17504     *
17505     * @attr ref android.R.styleable#View_textAlignment
17506     *
17507     * @hide
17508     */
17509    @ViewDebug.ExportedProperty(category = "text", mapping = {
17510            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17511            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17512            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17513            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17514            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17515            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17516            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17517    })
17518    public int getRawTextAlignment() {
17519        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17520    }
17521
17522    /**
17523     * Set the text alignment.
17524     *
17525     * @param textAlignment The text alignment to set. Should be one of
17526     *
17527     * {@link #TEXT_ALIGNMENT_INHERIT},
17528     * {@link #TEXT_ALIGNMENT_GRAVITY},
17529     * {@link #TEXT_ALIGNMENT_CENTER},
17530     * {@link #TEXT_ALIGNMENT_TEXT_START},
17531     * {@link #TEXT_ALIGNMENT_TEXT_END},
17532     * {@link #TEXT_ALIGNMENT_VIEW_START},
17533     * {@link #TEXT_ALIGNMENT_VIEW_END}
17534     *
17535     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17536     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17537     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17538     *
17539     * @attr ref android.R.styleable#View_textAlignment
17540     */
17541    public void setTextAlignment(int textAlignment) {
17542        if (textAlignment != getRawTextAlignment()) {
17543            // Reset the current and resolved text alignment
17544            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17545            resetResolvedTextAlignment();
17546            // Set the new text alignment
17547            mPrivateFlags2 |=
17548                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17549            // Do resolution
17550            resolveTextAlignment();
17551            // Notify change
17552            onRtlPropertiesChanged(getLayoutDirection());
17553            // Refresh
17554            requestLayout();
17555            invalidate(true);
17556        }
17557    }
17558
17559    /**
17560     * Return the resolved text alignment.
17561     *
17562     * @return the resolved text alignment. Returns one of:
17563     *
17564     * {@link #TEXT_ALIGNMENT_GRAVITY},
17565     * {@link #TEXT_ALIGNMENT_CENTER},
17566     * {@link #TEXT_ALIGNMENT_TEXT_START},
17567     * {@link #TEXT_ALIGNMENT_TEXT_END},
17568     * {@link #TEXT_ALIGNMENT_VIEW_START},
17569     * {@link #TEXT_ALIGNMENT_VIEW_END}
17570     *
17571     * @attr ref android.R.styleable#View_textAlignment
17572     */
17573    @ViewDebug.ExportedProperty(category = "text", mapping = {
17574            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17575            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17576            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17577            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17578            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17579            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17580            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17581    })
17582    public int getTextAlignment() {
17583        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17584                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17585    }
17586
17587    /**
17588     * Resolve the text alignment.
17589     *
17590     * @return true if resolution has been done, false otherwise.
17591     *
17592     * @hide
17593     */
17594    public boolean resolveTextAlignment() {
17595        // Reset any previous text alignment resolution
17596        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17597
17598        if (hasRtlSupport()) {
17599            // Set resolved text alignment flag depending on text alignment flag
17600            final int textAlignment = getRawTextAlignment();
17601            switch (textAlignment) {
17602                case TEXT_ALIGNMENT_INHERIT:
17603                    // Check if we can resolve the text alignment
17604                    if (!canResolveTextAlignment()) {
17605                        // We cannot do the resolution if there is no parent so use the default
17606                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17607                        // Resolution will need to happen again later
17608                        return false;
17609                    }
17610
17611                    // Parent has not yet resolved, so we still return the default
17612                    try {
17613                        if (!mParent.isTextAlignmentResolved()) {
17614                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17615                            // Resolution will need to happen again later
17616                            return false;
17617                        }
17618                    } catch (AbstractMethodError e) {
17619                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17620                                " does not fully implement ViewParent", e);
17621                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17622                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17623                        return true;
17624                    }
17625
17626                    int parentResolvedTextAlignment;
17627                    try {
17628                        parentResolvedTextAlignment = mParent.getTextAlignment();
17629                    } catch (AbstractMethodError e) {
17630                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17631                                " does not fully implement ViewParent", e);
17632                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17633                    }
17634                    switch (parentResolvedTextAlignment) {
17635                        case TEXT_ALIGNMENT_GRAVITY:
17636                        case TEXT_ALIGNMENT_TEXT_START:
17637                        case TEXT_ALIGNMENT_TEXT_END:
17638                        case TEXT_ALIGNMENT_CENTER:
17639                        case TEXT_ALIGNMENT_VIEW_START:
17640                        case TEXT_ALIGNMENT_VIEW_END:
17641                            // Resolved text alignment is the same as the parent resolved
17642                            // text alignment
17643                            mPrivateFlags2 |=
17644                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17645                            break;
17646                        default:
17647                            // Use default resolved text alignment
17648                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17649                    }
17650                    break;
17651                case TEXT_ALIGNMENT_GRAVITY:
17652                case TEXT_ALIGNMENT_TEXT_START:
17653                case TEXT_ALIGNMENT_TEXT_END:
17654                case TEXT_ALIGNMENT_CENTER:
17655                case TEXT_ALIGNMENT_VIEW_START:
17656                case TEXT_ALIGNMENT_VIEW_END:
17657                    // Resolved text alignment is the same as text alignment
17658                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17659                    break;
17660                default:
17661                    // Use default resolved text alignment
17662                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17663            }
17664        } else {
17665            // Use default resolved text alignment
17666            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17667        }
17668
17669        // Set the resolved
17670        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17671        return true;
17672    }
17673
17674    /**
17675     * Check if text alignment resolution can be done.
17676     *
17677     * @return true if text alignment resolution can be done otherwise return false.
17678     */
17679    public boolean canResolveTextAlignment() {
17680        switch (getRawTextAlignment()) {
17681            case TEXT_DIRECTION_INHERIT:
17682                if (mParent != null) {
17683                    try {
17684                        return mParent.canResolveTextAlignment();
17685                    } catch (AbstractMethodError e) {
17686                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17687                                " does not fully implement ViewParent", e);
17688                    }
17689                }
17690                return false;
17691
17692            default:
17693                return true;
17694        }
17695    }
17696
17697    /**
17698     * Reset resolved text alignment. Text alignment will be resolved during a call to
17699     * {@link #onMeasure(int, int)}.
17700     *
17701     * @hide
17702     */
17703    public void resetResolvedTextAlignment() {
17704        // Reset any previous text alignment resolution
17705        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17706        // Set to default
17707        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17708    }
17709
17710    /**
17711     * @return true if text alignment is inherited.
17712     *
17713     * @hide
17714     */
17715    public boolean isTextAlignmentInherited() {
17716        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17717    }
17718
17719    /**
17720     * @return true if text alignment is resolved.
17721     */
17722    public boolean isTextAlignmentResolved() {
17723        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17724    }
17725
17726    /**
17727     * Generate a value suitable for use in {@link #setId(int)}.
17728     * This value will not collide with ID values generated at build time by aapt for R.id.
17729     *
17730     * @return a generated ID value
17731     */
17732    public static int generateViewId() {
17733        for (;;) {
17734            final int result = sNextGeneratedId.get();
17735            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17736            int newValue = result + 1;
17737            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17738            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17739                return result;
17740            }
17741        }
17742    }
17743
17744    //
17745    // Properties
17746    //
17747    /**
17748     * A Property wrapper around the <code>alpha</code> functionality handled by the
17749     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17750     */
17751    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17752        @Override
17753        public void setValue(View object, float value) {
17754            object.setAlpha(value);
17755        }
17756
17757        @Override
17758        public Float get(View object) {
17759            return object.getAlpha();
17760        }
17761    };
17762
17763    /**
17764     * A Property wrapper around the <code>translationX</code> functionality handled by the
17765     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17766     */
17767    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17768        @Override
17769        public void setValue(View object, float value) {
17770            object.setTranslationX(value);
17771        }
17772
17773                @Override
17774        public Float get(View object) {
17775            return object.getTranslationX();
17776        }
17777    };
17778
17779    /**
17780     * A Property wrapper around the <code>translationY</code> functionality handled by the
17781     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17782     */
17783    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17784        @Override
17785        public void setValue(View object, float value) {
17786            object.setTranslationY(value);
17787        }
17788
17789        @Override
17790        public Float get(View object) {
17791            return object.getTranslationY();
17792        }
17793    };
17794
17795    /**
17796     * A Property wrapper around the <code>x</code> functionality handled by the
17797     * {@link View#setX(float)} and {@link View#getX()} methods.
17798     */
17799    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17800        @Override
17801        public void setValue(View object, float value) {
17802            object.setX(value);
17803        }
17804
17805        @Override
17806        public Float get(View object) {
17807            return object.getX();
17808        }
17809    };
17810
17811    /**
17812     * A Property wrapper around the <code>y</code> functionality handled by the
17813     * {@link View#setY(float)} and {@link View#getY()} methods.
17814     */
17815    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17816        @Override
17817        public void setValue(View object, float value) {
17818            object.setY(value);
17819        }
17820
17821        @Override
17822        public Float get(View object) {
17823            return object.getY();
17824        }
17825    };
17826
17827    /**
17828     * A Property wrapper around the <code>rotation</code> functionality handled by the
17829     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17830     */
17831    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17832        @Override
17833        public void setValue(View object, float value) {
17834            object.setRotation(value);
17835        }
17836
17837        @Override
17838        public Float get(View object) {
17839            return object.getRotation();
17840        }
17841    };
17842
17843    /**
17844     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17845     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17846     */
17847    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17848        @Override
17849        public void setValue(View object, float value) {
17850            object.setRotationX(value);
17851        }
17852
17853        @Override
17854        public Float get(View object) {
17855            return object.getRotationX();
17856        }
17857    };
17858
17859    /**
17860     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17861     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17862     */
17863    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17864        @Override
17865        public void setValue(View object, float value) {
17866            object.setRotationY(value);
17867        }
17868
17869        @Override
17870        public Float get(View object) {
17871            return object.getRotationY();
17872        }
17873    };
17874
17875    /**
17876     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17877     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17878     */
17879    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17880        @Override
17881        public void setValue(View object, float value) {
17882            object.setScaleX(value);
17883        }
17884
17885        @Override
17886        public Float get(View object) {
17887            return object.getScaleX();
17888        }
17889    };
17890
17891    /**
17892     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17893     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17894     */
17895    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17896        @Override
17897        public void setValue(View object, float value) {
17898            object.setScaleY(value);
17899        }
17900
17901        @Override
17902        public Float get(View object) {
17903            return object.getScaleY();
17904        }
17905    };
17906
17907    /**
17908     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17909     * Each MeasureSpec represents a requirement for either the width or the height.
17910     * A MeasureSpec is comprised of a size and a mode. There are three possible
17911     * modes:
17912     * <dl>
17913     * <dt>UNSPECIFIED</dt>
17914     * <dd>
17915     * The parent has not imposed any constraint on the child. It can be whatever size
17916     * it wants.
17917     * </dd>
17918     *
17919     * <dt>EXACTLY</dt>
17920     * <dd>
17921     * The parent has determined an exact size for the child. The child is going to be
17922     * given those bounds regardless of how big it wants to be.
17923     * </dd>
17924     *
17925     * <dt>AT_MOST</dt>
17926     * <dd>
17927     * The child can be as large as it wants up to the specified size.
17928     * </dd>
17929     * </dl>
17930     *
17931     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17932     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17933     */
17934    public static class MeasureSpec {
17935        private static final int MODE_SHIFT = 30;
17936        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17937
17938        /**
17939         * Measure specification mode: The parent has not imposed any constraint
17940         * on the child. It can be whatever size it wants.
17941         */
17942        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17943
17944        /**
17945         * Measure specification mode: The parent has determined an exact size
17946         * for the child. The child is going to be given those bounds regardless
17947         * of how big it wants to be.
17948         */
17949        public static final int EXACTLY     = 1 << MODE_SHIFT;
17950
17951        /**
17952         * Measure specification mode: The child can be as large as it wants up
17953         * to the specified size.
17954         */
17955        public static final int AT_MOST     = 2 << MODE_SHIFT;
17956
17957        /**
17958         * Creates a measure specification based on the supplied size and mode.
17959         *
17960         * The mode must always be one of the following:
17961         * <ul>
17962         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17963         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17964         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17965         * </ul>
17966         *
17967         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17968         * implementation was such that the order of arguments did not matter
17969         * and overflow in either value could impact the resulting MeasureSpec.
17970         * {@link android.widget.RelativeLayout} was affected by this bug.
17971         * Apps targeting API levels greater than 17 will get the fixed, more strict
17972         * behavior.</p>
17973         *
17974         * @param size the size of the measure specification
17975         * @param mode the mode of the measure specification
17976         * @return the measure specification based on size and mode
17977         */
17978        public static int makeMeasureSpec(int size, int mode) {
17979            if (sUseBrokenMakeMeasureSpec) {
17980                return size + mode;
17981            } else {
17982                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17983            }
17984        }
17985
17986        /**
17987         * Extracts the mode from the supplied measure specification.
17988         *
17989         * @param measureSpec the measure specification to extract the mode from
17990         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17991         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17992         *         {@link android.view.View.MeasureSpec#EXACTLY}
17993         */
17994        public static int getMode(int measureSpec) {
17995            return (measureSpec & MODE_MASK);
17996        }
17997
17998        /**
17999         * Extracts the size from the supplied measure specification.
18000         *
18001         * @param measureSpec the measure specification to extract the size from
18002         * @return the size in pixels defined in the supplied measure specification
18003         */
18004        public static int getSize(int measureSpec) {
18005            return (measureSpec & ~MODE_MASK);
18006        }
18007
18008        static int adjust(int measureSpec, int delta) {
18009            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18010        }
18011
18012        /**
18013         * Returns a String representation of the specified measure
18014         * specification.
18015         *
18016         * @param measureSpec the measure specification to convert to a String
18017         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18018         */
18019        public static String toString(int measureSpec) {
18020            int mode = getMode(measureSpec);
18021            int size = getSize(measureSpec);
18022
18023            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18024
18025            if (mode == UNSPECIFIED)
18026                sb.append("UNSPECIFIED ");
18027            else if (mode == EXACTLY)
18028                sb.append("EXACTLY ");
18029            else if (mode == AT_MOST)
18030                sb.append("AT_MOST ");
18031            else
18032                sb.append(mode).append(" ");
18033
18034            sb.append(size);
18035            return sb.toString();
18036        }
18037    }
18038
18039    class CheckForLongPress implements Runnable {
18040
18041        private int mOriginalWindowAttachCount;
18042
18043        public void run() {
18044            if (isPressed() && (mParent != null)
18045                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18046                if (performLongClick()) {
18047                    mHasPerformedLongPress = true;
18048                }
18049            }
18050        }
18051
18052        public void rememberWindowAttachCount() {
18053            mOriginalWindowAttachCount = mWindowAttachCount;
18054        }
18055    }
18056
18057    private final class CheckForTap implements Runnable {
18058        public void run() {
18059            mPrivateFlags &= ~PFLAG_PREPRESSED;
18060            setPressed(true);
18061            checkForLongClick(ViewConfiguration.getTapTimeout());
18062        }
18063    }
18064
18065    private final class PerformClick implements Runnable {
18066        public void run() {
18067            performClick();
18068        }
18069    }
18070
18071    /** @hide */
18072    public void hackTurnOffWindowResizeAnim(boolean off) {
18073        mAttachInfo.mTurnOffWindowResizeAnim = off;
18074    }
18075
18076    /**
18077     * This method returns a ViewPropertyAnimator object, which can be used to animate
18078     * specific properties on this View.
18079     *
18080     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18081     */
18082    public ViewPropertyAnimator animate() {
18083        if (mAnimator == null) {
18084            mAnimator = new ViewPropertyAnimator(this);
18085        }
18086        return mAnimator;
18087    }
18088
18089    /**
18090     * Set the current Scene that this view is in. The current scene is set only
18091     * on the root view of a scene, not for every view in that hierarchy. This
18092     * information is used by Scene to determine whether there is a previous
18093     * scene which should be exited before the new scene is entered.
18094     *
18095     * @param scene The new scene being set on the view
18096     *
18097     * @hide
18098     */
18099    public void setCurrentScene(Scene scene) {
18100        mCurrentScene = scene;
18101    }
18102
18103    /**
18104     * Gets the current {@link Scene} set on this view. A scene is set on a view
18105     * only if that view is the scene root.
18106     *
18107     * @return The current Scene set on this view. A value of null indicates that
18108     * no Scene is current set.
18109     */
18110    public Scene getCurrentScene() {
18111        return mCurrentScene;
18112    }
18113
18114    /**
18115     * Interface definition for a callback to be invoked when a hardware key event is
18116     * dispatched to this view. The callback will be invoked before the key event is
18117     * given to the view. This is only useful for hardware keyboards; a software input
18118     * method has no obligation to trigger this listener.
18119     */
18120    public interface OnKeyListener {
18121        /**
18122         * Called when a hardware key is dispatched to a view. This allows listeners to
18123         * get a chance to respond before the target view.
18124         * <p>Key presses in software keyboards will generally NOT trigger this method,
18125         * although some may elect to do so in some situations. Do not assume a
18126         * software input method has to be key-based; even if it is, it may use key presses
18127         * in a different way than you expect, so there is no way to reliably catch soft
18128         * input key presses.
18129         *
18130         * @param v The view the key has been dispatched to.
18131         * @param keyCode The code for the physical key that was pressed
18132         * @param event The KeyEvent object containing full information about
18133         *        the event.
18134         * @return True if the listener has consumed the event, false otherwise.
18135         */
18136        boolean onKey(View v, int keyCode, KeyEvent event);
18137    }
18138
18139    /**
18140     * Interface definition for a callback to be invoked when a touch event is
18141     * dispatched to this view. The callback will be invoked before the touch
18142     * event is given to the view.
18143     */
18144    public interface OnTouchListener {
18145        /**
18146         * Called when a touch event is dispatched to a view. This allows listeners to
18147         * get a chance to respond before the target view.
18148         *
18149         * @param v The view the touch event has been dispatched to.
18150         * @param event The MotionEvent object containing full information about
18151         *        the event.
18152         * @return True if the listener has consumed the event, false otherwise.
18153         */
18154        boolean onTouch(View v, MotionEvent event);
18155    }
18156
18157    /**
18158     * Interface definition for a callback to be invoked when a hover event is
18159     * dispatched to this view. The callback will be invoked before the hover
18160     * event is given to the view.
18161     */
18162    public interface OnHoverListener {
18163        /**
18164         * Called when a hover event is dispatched to a view. This allows listeners to
18165         * get a chance to respond before the target view.
18166         *
18167         * @param v The view the hover event has been dispatched to.
18168         * @param event The MotionEvent object containing full information about
18169         *        the event.
18170         * @return True if the listener has consumed the event, false otherwise.
18171         */
18172        boolean onHover(View v, MotionEvent event);
18173    }
18174
18175    /**
18176     * Interface definition for a callback to be invoked when a generic motion event is
18177     * dispatched to this view. The callback will be invoked before the generic motion
18178     * event is given to the view.
18179     */
18180    public interface OnGenericMotionListener {
18181        /**
18182         * Called when a generic motion event is dispatched to a view. This allows listeners to
18183         * get a chance to respond before the target view.
18184         *
18185         * @param v The view the generic motion event has been dispatched to.
18186         * @param event The MotionEvent object containing full information about
18187         *        the event.
18188         * @return True if the listener has consumed the event, false otherwise.
18189         */
18190        boolean onGenericMotion(View v, MotionEvent event);
18191    }
18192
18193    /**
18194     * Interface definition for a callback to be invoked when a view has been clicked and held.
18195     */
18196    public interface OnLongClickListener {
18197        /**
18198         * Called when a view has been clicked and held.
18199         *
18200         * @param v The view that was clicked and held.
18201         *
18202         * @return true if the callback consumed the long click, false otherwise.
18203         */
18204        boolean onLongClick(View v);
18205    }
18206
18207    /**
18208     * Interface definition for a callback to be invoked when a drag is being dispatched
18209     * to this view.  The callback will be invoked before the hosting view's own
18210     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18211     * onDrag(event) behavior, it should return 'false' from this callback.
18212     *
18213     * <div class="special reference">
18214     * <h3>Developer Guides</h3>
18215     * <p>For a guide to implementing drag and drop features, read the
18216     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18217     * </div>
18218     */
18219    public interface OnDragListener {
18220        /**
18221         * Called when a drag event is dispatched to a view. This allows listeners
18222         * to get a chance to override base View behavior.
18223         *
18224         * @param v The View that received the drag event.
18225         * @param event The {@link android.view.DragEvent} object for the drag event.
18226         * @return {@code true} if the drag event was handled successfully, or {@code false}
18227         * if the drag event was not handled. Note that {@code false} will trigger the View
18228         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18229         */
18230        boolean onDrag(View v, DragEvent event);
18231    }
18232
18233    /**
18234     * Interface definition for a callback to be invoked when the focus state of
18235     * a view changed.
18236     */
18237    public interface OnFocusChangeListener {
18238        /**
18239         * Called when the focus state of a view has changed.
18240         *
18241         * @param v The view whose state has changed.
18242         * @param hasFocus The new focus state of v.
18243         */
18244        void onFocusChange(View v, boolean hasFocus);
18245    }
18246
18247    /**
18248     * Interface definition for a callback to be invoked when a view is clicked.
18249     */
18250    public interface OnClickListener {
18251        /**
18252         * Called when a view has been clicked.
18253         *
18254         * @param v The view that was clicked.
18255         */
18256        void onClick(View v);
18257    }
18258
18259    /**
18260     * Interface definition for a callback to be invoked when the context menu
18261     * for this view is being built.
18262     */
18263    public interface OnCreateContextMenuListener {
18264        /**
18265         * Called when the context menu for this view is being built. It is not
18266         * safe to hold onto the menu after this method returns.
18267         *
18268         * @param menu The context menu that is being built
18269         * @param v The view for which the context menu is being built
18270         * @param menuInfo Extra information about the item for which the
18271         *            context menu should be shown. This information will vary
18272         *            depending on the class of v.
18273         */
18274        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18275    }
18276
18277    /**
18278     * Interface definition for a callback to be invoked when the status bar changes
18279     * visibility.  This reports <strong>global</strong> changes to the system UI
18280     * state, not what the application is requesting.
18281     *
18282     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18283     */
18284    public interface OnSystemUiVisibilityChangeListener {
18285        /**
18286         * Called when the status bar changes visibility because of a call to
18287         * {@link View#setSystemUiVisibility(int)}.
18288         *
18289         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18290         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18291         * This tells you the <strong>global</strong> state of these UI visibility
18292         * flags, not what your app is currently applying.
18293         */
18294        public void onSystemUiVisibilityChange(int visibility);
18295    }
18296
18297    /**
18298     * Interface definition for a callback to be invoked when this view is attached
18299     * or detached from its window.
18300     */
18301    public interface OnAttachStateChangeListener {
18302        /**
18303         * Called when the view is attached to a window.
18304         * @param v The view that was attached
18305         */
18306        public void onViewAttachedToWindow(View v);
18307        /**
18308         * Called when the view is detached from a window.
18309         * @param v The view that was detached
18310         */
18311        public void onViewDetachedFromWindow(View v);
18312    }
18313
18314    private final class UnsetPressedState implements Runnable {
18315        public void run() {
18316            setPressed(false);
18317        }
18318    }
18319
18320    /**
18321     * Base class for derived classes that want to save and restore their own
18322     * state in {@link android.view.View#onSaveInstanceState()}.
18323     */
18324    public static class BaseSavedState extends AbsSavedState {
18325        /**
18326         * Constructor used when reading from a parcel. Reads the state of the superclass.
18327         *
18328         * @param source
18329         */
18330        public BaseSavedState(Parcel source) {
18331            super(source);
18332        }
18333
18334        /**
18335         * Constructor called by derived classes when creating their SavedState objects
18336         *
18337         * @param superState The state of the superclass of this view
18338         */
18339        public BaseSavedState(Parcelable superState) {
18340            super(superState);
18341        }
18342
18343        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18344                new Parcelable.Creator<BaseSavedState>() {
18345            public BaseSavedState createFromParcel(Parcel in) {
18346                return new BaseSavedState(in);
18347            }
18348
18349            public BaseSavedState[] newArray(int size) {
18350                return new BaseSavedState[size];
18351            }
18352        };
18353    }
18354
18355    /**
18356     * A set of information given to a view when it is attached to its parent
18357     * window.
18358     */
18359    static class AttachInfo {
18360        interface Callbacks {
18361            void playSoundEffect(int effectId);
18362            boolean performHapticFeedback(int effectId, boolean always);
18363        }
18364
18365        /**
18366         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18367         * to a Handler. This class contains the target (View) to invalidate and
18368         * the coordinates of the dirty rectangle.
18369         *
18370         * For performance purposes, this class also implements a pool of up to
18371         * POOL_LIMIT objects that get reused. This reduces memory allocations
18372         * whenever possible.
18373         */
18374        static class InvalidateInfo {
18375            private static final int POOL_LIMIT = 10;
18376
18377            private static final SynchronizedPool<InvalidateInfo> sPool =
18378                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18379
18380            View target;
18381
18382            int left;
18383            int top;
18384            int right;
18385            int bottom;
18386
18387            public static InvalidateInfo obtain() {
18388                InvalidateInfo instance = sPool.acquire();
18389                return (instance != null) ? instance : new InvalidateInfo();
18390            }
18391
18392            public void recycle() {
18393                target = null;
18394                sPool.release(this);
18395            }
18396        }
18397
18398        final IWindowSession mSession;
18399
18400        final IWindow mWindow;
18401
18402        final IBinder mWindowToken;
18403
18404        final Display mDisplay;
18405
18406        final Callbacks mRootCallbacks;
18407
18408        HardwareCanvas mHardwareCanvas;
18409
18410        IWindowId mIWindowId;
18411        WindowId mWindowId;
18412
18413        /**
18414         * The top view of the hierarchy.
18415         */
18416        View mRootView;
18417
18418        IBinder mPanelParentWindowToken;
18419        Surface mSurface;
18420
18421        boolean mHardwareAccelerated;
18422        boolean mHardwareAccelerationRequested;
18423        HardwareRenderer mHardwareRenderer;
18424
18425        boolean mScreenOn;
18426
18427        /**
18428         * Scale factor used by the compatibility mode
18429         */
18430        float mApplicationScale;
18431
18432        /**
18433         * Indicates whether the application is in compatibility mode
18434         */
18435        boolean mScalingRequired;
18436
18437        /**
18438         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18439         */
18440        boolean mTurnOffWindowResizeAnim;
18441
18442        /**
18443         * Left position of this view's window
18444         */
18445        int mWindowLeft;
18446
18447        /**
18448         * Top position of this view's window
18449         */
18450        int mWindowTop;
18451
18452        /**
18453         * Indicates whether views need to use 32-bit drawing caches
18454         */
18455        boolean mUse32BitDrawingCache;
18456
18457        /**
18458         * For windows that are full-screen but using insets to layout inside
18459         * of the screen areas, these are the current insets to appear inside
18460         * the overscan area of the display.
18461         */
18462        final Rect mOverscanInsets = new Rect();
18463
18464        /**
18465         * For windows that are full-screen but using insets to layout inside
18466         * of the screen decorations, these are the current insets for the
18467         * content of the window.
18468         */
18469        final Rect mContentInsets = new Rect();
18470
18471        /**
18472         * For windows that are full-screen but using insets to layout inside
18473         * of the screen decorations, these are the current insets for the
18474         * actual visible parts of the window.
18475         */
18476        final Rect mVisibleInsets = new Rect();
18477
18478        /**
18479         * The internal insets given by this window.  This value is
18480         * supplied by the client (through
18481         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18482         * be given to the window manager when changed to be used in laying
18483         * out windows behind it.
18484         */
18485        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18486                = new ViewTreeObserver.InternalInsetsInfo();
18487
18488        /**
18489         * All views in the window's hierarchy that serve as scroll containers,
18490         * used to determine if the window can be resized or must be panned
18491         * to adjust for a soft input area.
18492         */
18493        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18494
18495        final KeyEvent.DispatcherState mKeyDispatchState
18496                = new KeyEvent.DispatcherState();
18497
18498        /**
18499         * Indicates whether the view's window currently has the focus.
18500         */
18501        boolean mHasWindowFocus;
18502
18503        /**
18504         * The current visibility of the window.
18505         */
18506        int mWindowVisibility;
18507
18508        /**
18509         * Indicates the time at which drawing started to occur.
18510         */
18511        long mDrawingTime;
18512
18513        /**
18514         * Indicates whether or not ignoring the DIRTY_MASK flags.
18515         */
18516        boolean mIgnoreDirtyState;
18517
18518        /**
18519         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18520         * to avoid clearing that flag prematurely.
18521         */
18522        boolean mSetIgnoreDirtyState = false;
18523
18524        /**
18525         * Indicates whether the view's window is currently in touch mode.
18526         */
18527        boolean mInTouchMode;
18528
18529        /**
18530         * Indicates that ViewAncestor should trigger a global layout change
18531         * the next time it performs a traversal
18532         */
18533        boolean mRecomputeGlobalAttributes;
18534
18535        /**
18536         * Always report new attributes at next traversal.
18537         */
18538        boolean mForceReportNewAttributes;
18539
18540        /**
18541         * Set during a traveral if any views want to keep the screen on.
18542         */
18543        boolean mKeepScreenOn;
18544
18545        /**
18546         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18547         */
18548        int mSystemUiVisibility;
18549
18550        /**
18551         * Hack to force certain system UI visibility flags to be cleared.
18552         */
18553        int mDisabledSystemUiVisibility;
18554
18555        /**
18556         * Last global system UI visibility reported by the window manager.
18557         */
18558        int mGlobalSystemUiVisibility;
18559
18560        /**
18561         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18562         * attached.
18563         */
18564        boolean mHasSystemUiListeners;
18565
18566        /**
18567         * Set if the window has requested to extend into the overscan region
18568         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18569         */
18570        boolean mOverscanRequested;
18571
18572        /**
18573         * Set if the visibility of any views has changed.
18574         */
18575        boolean mViewVisibilityChanged;
18576
18577        /**
18578         * Set to true if a view has been scrolled.
18579         */
18580        boolean mViewScrollChanged;
18581
18582        /**
18583         * Global to the view hierarchy used as a temporary for dealing with
18584         * x/y points in the transparent region computations.
18585         */
18586        final int[] mTransparentLocation = new int[2];
18587
18588        /**
18589         * Global to the view hierarchy used as a temporary for dealing with
18590         * x/y points in the ViewGroup.invalidateChild implementation.
18591         */
18592        final int[] mInvalidateChildLocation = new int[2];
18593
18594
18595        /**
18596         * Global to the view hierarchy used as a temporary for dealing with
18597         * x/y location when view is transformed.
18598         */
18599        final float[] mTmpTransformLocation = new float[2];
18600
18601        /**
18602         * The view tree observer used to dispatch global events like
18603         * layout, pre-draw, touch mode change, etc.
18604         */
18605        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18606
18607        /**
18608         * A Canvas used by the view hierarchy to perform bitmap caching.
18609         */
18610        Canvas mCanvas;
18611
18612        /**
18613         * The view root impl.
18614         */
18615        final ViewRootImpl mViewRootImpl;
18616
18617        /**
18618         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18619         * handler can be used to pump events in the UI events queue.
18620         */
18621        final Handler mHandler;
18622
18623        /**
18624         * Temporary for use in computing invalidate rectangles while
18625         * calling up the hierarchy.
18626         */
18627        final Rect mTmpInvalRect = new Rect();
18628
18629        /**
18630         * Temporary for use in computing hit areas with transformed views
18631         */
18632        final RectF mTmpTransformRect = new RectF();
18633
18634        /**
18635         * Temporary for use in transforming invalidation rect
18636         */
18637        final Matrix mTmpMatrix = new Matrix();
18638
18639        /**
18640         * Temporary for use in transforming invalidation rect
18641         */
18642        final Transformation mTmpTransformation = new Transformation();
18643
18644        /**
18645         * Temporary list for use in collecting focusable descendents of a view.
18646         */
18647        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18648
18649        /**
18650         * The id of the window for accessibility purposes.
18651         */
18652        int mAccessibilityWindowId = View.NO_ID;
18653
18654        /**
18655         * Flags related to accessibility processing.
18656         *
18657         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18658         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18659         */
18660        int mAccessibilityFetchFlags;
18661
18662        /**
18663         * The drawable for highlighting accessibility focus.
18664         */
18665        Drawable mAccessibilityFocusDrawable;
18666
18667        /**
18668         * Show where the margins, bounds and layout bounds are for each view.
18669         */
18670        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18671
18672        /**
18673         * Point used to compute visible regions.
18674         */
18675        final Point mPoint = new Point();
18676
18677        /**
18678         * Used to track which View originated a requestLayout() call, used when
18679         * requestLayout() is called during layout.
18680         */
18681        View mViewRequestingLayout;
18682
18683        /**
18684         * Creates a new set of attachment information with the specified
18685         * events handler and thread.
18686         *
18687         * @param handler the events handler the view must use
18688         */
18689        AttachInfo(IWindowSession session, IWindow window, Display display,
18690                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18691            mSession = session;
18692            mWindow = window;
18693            mWindowToken = window.asBinder();
18694            mDisplay = display;
18695            mViewRootImpl = viewRootImpl;
18696            mHandler = handler;
18697            mRootCallbacks = effectPlayer;
18698        }
18699    }
18700
18701    /**
18702     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18703     * is supported. This avoids keeping too many unused fields in most
18704     * instances of View.</p>
18705     */
18706    private static class ScrollabilityCache implements Runnable {
18707
18708        /**
18709         * Scrollbars are not visible
18710         */
18711        public static final int OFF = 0;
18712
18713        /**
18714         * Scrollbars are visible
18715         */
18716        public static final int ON = 1;
18717
18718        /**
18719         * Scrollbars are fading away
18720         */
18721        public static final int FADING = 2;
18722
18723        public boolean fadeScrollBars;
18724
18725        public int fadingEdgeLength;
18726        public int scrollBarDefaultDelayBeforeFade;
18727        public int scrollBarFadeDuration;
18728
18729        public int scrollBarSize;
18730        public ScrollBarDrawable scrollBar;
18731        public float[] interpolatorValues;
18732        public View host;
18733
18734        public final Paint paint;
18735        public final Matrix matrix;
18736        public Shader shader;
18737
18738        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18739
18740        private static final float[] OPAQUE = { 255 };
18741        private static final float[] TRANSPARENT = { 0.0f };
18742
18743        /**
18744         * When fading should start. This time moves into the future every time
18745         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18746         */
18747        public long fadeStartTime;
18748
18749
18750        /**
18751         * The current state of the scrollbars: ON, OFF, or FADING
18752         */
18753        public int state = OFF;
18754
18755        private int mLastColor;
18756
18757        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18758            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18759            scrollBarSize = configuration.getScaledScrollBarSize();
18760            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18761            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18762
18763            paint = new Paint();
18764            matrix = new Matrix();
18765            // use use a height of 1, and then wack the matrix each time we
18766            // actually use it.
18767            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18768            paint.setShader(shader);
18769            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18770
18771            this.host = host;
18772        }
18773
18774        public void setFadeColor(int color) {
18775            if (color != mLastColor) {
18776                mLastColor = color;
18777
18778                if (color != 0) {
18779                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18780                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18781                    paint.setShader(shader);
18782                    // Restore the default transfer mode (src_over)
18783                    paint.setXfermode(null);
18784                } else {
18785                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18786                    paint.setShader(shader);
18787                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18788                }
18789            }
18790        }
18791
18792        public void run() {
18793            long now = AnimationUtils.currentAnimationTimeMillis();
18794            if (now >= fadeStartTime) {
18795
18796                // the animation fades the scrollbars out by changing
18797                // the opacity (alpha) from fully opaque to fully
18798                // transparent
18799                int nextFrame = (int) now;
18800                int framesCount = 0;
18801
18802                Interpolator interpolator = scrollBarInterpolator;
18803
18804                // Start opaque
18805                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18806
18807                // End transparent
18808                nextFrame += scrollBarFadeDuration;
18809                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18810
18811                state = FADING;
18812
18813                // Kick off the fade animation
18814                host.invalidate(true);
18815            }
18816        }
18817    }
18818
18819    /**
18820     * Resuable callback for sending
18821     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18822     */
18823    private class SendViewScrolledAccessibilityEvent implements Runnable {
18824        public volatile boolean mIsPending;
18825
18826        public void run() {
18827            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18828            mIsPending = false;
18829        }
18830    }
18831
18832    /**
18833     * <p>
18834     * This class represents a delegate that can be registered in a {@link View}
18835     * to enhance accessibility support via composition rather via inheritance.
18836     * It is specifically targeted to widget developers that extend basic View
18837     * classes i.e. classes in package android.view, that would like their
18838     * applications to be backwards compatible.
18839     * </p>
18840     * <div class="special reference">
18841     * <h3>Developer Guides</h3>
18842     * <p>For more information about making applications accessible, read the
18843     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18844     * developer guide.</p>
18845     * </div>
18846     * <p>
18847     * A scenario in which a developer would like to use an accessibility delegate
18848     * is overriding a method introduced in a later API version then the minimal API
18849     * version supported by the application. For example, the method
18850     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18851     * in API version 4 when the accessibility APIs were first introduced. If a
18852     * developer would like his application to run on API version 4 devices (assuming
18853     * all other APIs used by the application are version 4 or lower) and take advantage
18854     * of this method, instead of overriding the method which would break the application's
18855     * backwards compatibility, he can override the corresponding method in this
18856     * delegate and register the delegate in the target View if the API version of
18857     * the system is high enough i.e. the API version is same or higher to the API
18858     * version that introduced
18859     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18860     * </p>
18861     * <p>
18862     * Here is an example implementation:
18863     * </p>
18864     * <code><pre><p>
18865     * if (Build.VERSION.SDK_INT >= 14) {
18866     *     // If the API version is equal of higher than the version in
18867     *     // which onInitializeAccessibilityNodeInfo was introduced we
18868     *     // register a delegate with a customized implementation.
18869     *     View view = findViewById(R.id.view_id);
18870     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18871     *         public void onInitializeAccessibilityNodeInfo(View host,
18872     *                 AccessibilityNodeInfo info) {
18873     *             // Let the default implementation populate the info.
18874     *             super.onInitializeAccessibilityNodeInfo(host, info);
18875     *             // Set some other information.
18876     *             info.setEnabled(host.isEnabled());
18877     *         }
18878     *     });
18879     * }
18880     * </code></pre></p>
18881     * <p>
18882     * This delegate contains methods that correspond to the accessibility methods
18883     * in View. If a delegate has been specified the implementation in View hands
18884     * off handling to the corresponding method in this delegate. The default
18885     * implementation the delegate methods behaves exactly as the corresponding
18886     * method in View for the case of no accessibility delegate been set. Hence,
18887     * to customize the behavior of a View method, clients can override only the
18888     * corresponding delegate method without altering the behavior of the rest
18889     * accessibility related methods of the host view.
18890     * </p>
18891     */
18892    public static class AccessibilityDelegate {
18893
18894        /**
18895         * Sends an accessibility event of the given type. If accessibility is not
18896         * enabled this method has no effect.
18897         * <p>
18898         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18899         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18900         * been set.
18901         * </p>
18902         *
18903         * @param host The View hosting the delegate.
18904         * @param eventType The type of the event to send.
18905         *
18906         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18907         */
18908        public void sendAccessibilityEvent(View host, int eventType) {
18909            host.sendAccessibilityEventInternal(eventType);
18910        }
18911
18912        /**
18913         * Performs the specified accessibility action on the view. For
18914         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18915         * <p>
18916         * The default implementation behaves as
18917         * {@link View#performAccessibilityAction(int, Bundle)
18918         *  View#performAccessibilityAction(int, Bundle)} for the case of
18919         *  no accessibility delegate been set.
18920         * </p>
18921         *
18922         * @param action The action to perform.
18923         * @return Whether the action was performed.
18924         *
18925         * @see View#performAccessibilityAction(int, Bundle)
18926         *      View#performAccessibilityAction(int, Bundle)
18927         */
18928        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18929            return host.performAccessibilityActionInternal(action, args);
18930        }
18931
18932        /**
18933         * Sends an accessibility event. This method behaves exactly as
18934         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18935         * empty {@link AccessibilityEvent} and does not perform a check whether
18936         * accessibility is enabled.
18937         * <p>
18938         * The default implementation behaves as
18939         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18940         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18941         * the case of no accessibility delegate been set.
18942         * </p>
18943         *
18944         * @param host The View hosting the delegate.
18945         * @param event The event to send.
18946         *
18947         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18948         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18949         */
18950        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18951            host.sendAccessibilityEventUncheckedInternal(event);
18952        }
18953
18954        /**
18955         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18956         * to its children for adding their text content to the event.
18957         * <p>
18958         * The default implementation behaves as
18959         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18960         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18961         * the case of no accessibility delegate been set.
18962         * </p>
18963         *
18964         * @param host The View hosting the delegate.
18965         * @param event The event.
18966         * @return True if the event population was completed.
18967         *
18968         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18969         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18970         */
18971        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18972            return host.dispatchPopulateAccessibilityEventInternal(event);
18973        }
18974
18975        /**
18976         * Gives a chance to the host View to populate the accessibility event with its
18977         * text content.
18978         * <p>
18979         * The default implementation behaves as
18980         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18981         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18982         * the case of no accessibility delegate been set.
18983         * </p>
18984         *
18985         * @param host The View hosting the delegate.
18986         * @param event The accessibility event which to populate.
18987         *
18988         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18989         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18990         */
18991        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18992            host.onPopulateAccessibilityEventInternal(event);
18993        }
18994
18995        /**
18996         * Initializes an {@link AccessibilityEvent} with information about the
18997         * the host View which is the event source.
18998         * <p>
18999         * The default implementation behaves as
19000         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19001         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19002         * the case of no accessibility delegate been set.
19003         * </p>
19004         *
19005         * @param host The View hosting the delegate.
19006         * @param event The event to initialize.
19007         *
19008         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19009         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19010         */
19011        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19012            host.onInitializeAccessibilityEventInternal(event);
19013        }
19014
19015        /**
19016         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19017         * <p>
19018         * The default implementation behaves as
19019         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19020         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19021         * the case of no accessibility delegate been set.
19022         * </p>
19023         *
19024         * @param host The View hosting the delegate.
19025         * @param info The instance to initialize.
19026         *
19027         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19028         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19029         */
19030        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19031            host.onInitializeAccessibilityNodeInfoInternal(info);
19032        }
19033
19034        /**
19035         * Called when a child of the host View has requested sending an
19036         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19037         * to augment the event.
19038         * <p>
19039         * The default implementation behaves as
19040         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19041         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19042         * the case of no accessibility delegate been set.
19043         * </p>
19044         *
19045         * @param host The View hosting the delegate.
19046         * @param child The child which requests sending the event.
19047         * @param event The event to be sent.
19048         * @return True if the event should be sent
19049         *
19050         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19051         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19052         */
19053        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19054                AccessibilityEvent event) {
19055            return host.onRequestSendAccessibilityEventInternal(child, event);
19056        }
19057
19058        /**
19059         * Gets the provider for managing a virtual view hierarchy rooted at this View
19060         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19061         * that explore the window content.
19062         * <p>
19063         * The default implementation behaves as
19064         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19065         * the case of no accessibility delegate been set.
19066         * </p>
19067         *
19068         * @return The provider.
19069         *
19070         * @see AccessibilityNodeProvider
19071         */
19072        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19073            return null;
19074        }
19075
19076        /**
19077         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19078         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19079         * This method is responsible for obtaining an accessibility node info from a
19080         * pool of reusable instances and calling
19081         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19082         * view to initialize the former.
19083         * <p>
19084         * <strong>Note:</strong> The client is responsible for recycling the obtained
19085         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19086         * creation.
19087         * </p>
19088         * <p>
19089         * The default implementation behaves as
19090         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19091         * the case of no accessibility delegate been set.
19092         * </p>
19093         * @return A populated {@link AccessibilityNodeInfo}.
19094         *
19095         * @see AccessibilityNodeInfo
19096         *
19097         * @hide
19098         */
19099        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19100            return host.createAccessibilityNodeInfoInternal();
19101        }
19102    }
19103
19104    private class MatchIdPredicate implements Predicate<View> {
19105        public int mId;
19106
19107        @Override
19108        public boolean apply(View view) {
19109            return (view.mID == mId);
19110        }
19111    }
19112
19113    private class MatchLabelForPredicate implements Predicate<View> {
19114        private int mLabeledId;
19115
19116        @Override
19117        public boolean apply(View view) {
19118            return (view.mLabelForId == mLabeledId);
19119        }
19120    }
19121
19122    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19123        private boolean mPosted;
19124        private long mLastEventTimeMillis;
19125
19126        public void run() {
19127            mPosted = false;
19128            mLastEventTimeMillis = SystemClock.uptimeMillis();
19129            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19130                AccessibilityEvent event = AccessibilityEvent.obtain();
19131                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19132                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
19133                sendAccessibilityEventUnchecked(event);
19134            }
19135        }
19136
19137        public void runOrPost() {
19138            if (mPosted) {
19139                return;
19140            }
19141            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19142            final long minEventIntevalMillis =
19143                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19144            if (timeSinceLastMillis >= minEventIntevalMillis) {
19145                removeCallbacks(this);
19146                run();
19147            } else {
19148                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19149                mPosted = true;
19150            }
19151        }
19152    }
19153
19154    /**
19155     * Dump all private flags in readable format, useful for documentation and
19156     * sanity checking.
19157     */
19158    private static void dumpFlags() {
19159        final HashMap<String, String> found = Maps.newHashMap();
19160        try {
19161            for (Field field : View.class.getDeclaredFields()) {
19162                final int modifiers = field.getModifiers();
19163                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19164                    if (field.getType().equals(int.class)) {
19165                        final int value = field.getInt(null);
19166                        dumpFlag(found, field.getName(), value);
19167                    } else if (field.getType().equals(int[].class)) {
19168                        final int[] values = (int[]) field.get(null);
19169                        for (int i = 0; i < values.length; i++) {
19170                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19171                        }
19172                    }
19173                }
19174            }
19175        } catch (IllegalAccessException e) {
19176            throw new RuntimeException(e);
19177        }
19178
19179        final ArrayList<String> keys = Lists.newArrayList();
19180        keys.addAll(found.keySet());
19181        Collections.sort(keys);
19182        for (String key : keys) {
19183            Log.d(VIEW_LOG_TAG, found.get(key));
19184        }
19185    }
19186
19187    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19188        // Sort flags by prefix, then by bits, always keeping unique keys
19189        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19190        final int prefix = name.indexOf('_');
19191        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19192        final String output = bits + " " + name;
19193        found.put(key, output);
19194    }
19195}
19196