View.java revision 1487466dc2ce14cccf0ff2bd2f824238aaa0044e
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.SuperNotCalledException;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.AccessibilityIterators.TextSegmentIterator;
64import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
65import android.view.AccessibilityIterators.WordTextSegmentIterator;
66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
67import android.view.accessibility.AccessibilityEvent;
68import android.view.accessibility.AccessibilityEventSource;
69import android.view.accessibility.AccessibilityManager;
70import android.view.accessibility.AccessibilityNodeInfo;
71import android.view.accessibility.AccessibilityNodeProvider;
72import android.view.animation.Animation;
73import android.view.animation.AnimationUtils;
74import android.view.animation.Transformation;
75import android.view.inputmethod.EditorInfo;
76import android.view.inputmethod.InputConnection;
77import android.view.inputmethod.InputMethodManager;
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    // for mPrivateFlags:
1579    /** {@hide} */
1580    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1581    /** {@hide} */
1582    static final int PFLAG_FOCUSED                     = 0x00000002;
1583    /** {@hide} */
1584    static final int PFLAG_SELECTED                    = 0x00000004;
1585    /** {@hide} */
1586    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1587    /** {@hide} */
1588    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1589    /** {@hide} */
1590    static final int PFLAG_DRAWN                       = 0x00000020;
1591    /**
1592     * When this flag is set, this view is running an animation on behalf of its
1593     * children and should therefore not cancel invalidate requests, even if they
1594     * lie outside of this view's bounds.
1595     *
1596     * {@hide}
1597     */
1598    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1599    /** {@hide} */
1600    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1601    /** {@hide} */
1602    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1603    /** {@hide} */
1604    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1605    /** {@hide} */
1606    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1607    /** {@hide} */
1608    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1609    /** {@hide} */
1610    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1611    /** {@hide} */
1612    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1613
1614    private static final int PFLAG_PRESSED             = 0x00004000;
1615
1616    /** {@hide} */
1617    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1618    /**
1619     * Flag used to indicate that this view should be drawn once more (and only once
1620     * more) after its animation has completed.
1621     * {@hide}
1622     */
1623    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1624
1625    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1626
1627    /**
1628     * Indicates that the View returned true when onSetAlpha() was called and that
1629     * the alpha must be restored.
1630     * {@hide}
1631     */
1632    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1633
1634    /**
1635     * Set by {@link #setScrollContainer(boolean)}.
1636     */
1637    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1638
1639    /**
1640     * Set by {@link #setScrollContainer(boolean)}.
1641     */
1642    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1643
1644    /**
1645     * View flag indicating whether this view was invalidated (fully or partially.)
1646     *
1647     * @hide
1648     */
1649    static final int PFLAG_DIRTY                       = 0x00200000;
1650
1651    /**
1652     * View flag indicating whether this view was invalidated by an opaque
1653     * invalidate request.
1654     *
1655     * @hide
1656     */
1657    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1658
1659    /**
1660     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1661     *
1662     * @hide
1663     */
1664    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1665
1666    /**
1667     * Indicates whether the background is opaque.
1668     *
1669     * @hide
1670     */
1671    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1672
1673    /**
1674     * Indicates whether the scrollbars are opaque.
1675     *
1676     * @hide
1677     */
1678    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1679
1680    /**
1681     * Indicates whether the view is opaque.
1682     *
1683     * @hide
1684     */
1685    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1686
1687    /**
1688     * Indicates a prepressed state;
1689     * the short time between ACTION_DOWN and recognizing
1690     * a 'real' press. Prepressed is used to recognize quick taps
1691     * even when they are shorter than ViewConfiguration.getTapTimeout().
1692     *
1693     * @hide
1694     */
1695    private static final int PFLAG_PREPRESSED          = 0x02000000;
1696
1697    /**
1698     * Indicates whether the view is temporarily detached.
1699     *
1700     * @hide
1701     */
1702    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1703
1704    /**
1705     * Indicates that we should awaken scroll bars once attached
1706     *
1707     * @hide
1708     */
1709    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1710
1711    /**
1712     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1713     * @hide
1714     */
1715    private static final int PFLAG_HOVERED             = 0x10000000;
1716
1717    /**
1718     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1719     * for transform operations
1720     *
1721     * @hide
1722     */
1723    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1724
1725    /** {@hide} */
1726    static final int PFLAG_ACTIVATED                   = 0x40000000;
1727
1728    /**
1729     * Indicates that this view was specifically invalidated, not just dirtied because some
1730     * child view was invalidated. The flag is used to determine when we need to recreate
1731     * a view's display list (as opposed to just returning a reference to its existing
1732     * display list).
1733     *
1734     * @hide
1735     */
1736    static final int PFLAG_INVALIDATED                 = 0x80000000;
1737
1738    /**
1739     * Masks for mPrivateFlags2, as generated by dumpFlags():
1740     *
1741     * -------|-------|-------|-------|
1742     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1743     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1744     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1745     *                               1  PFLAG2_DRAG_HOVERED
1746     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1747     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1748     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1749     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1750     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1751     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1752     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1753     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1754     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1755     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1756     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1757     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1758     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1759     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1760     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1761     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1762     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1763     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1764     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1765     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1766     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1767     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1768     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1769     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1770     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1771     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1772     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1773     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1774     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1775     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1776     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1777     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1778     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1779     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1780     *   1                              PFLAG2_PADDING_RESOLVED
1781     * -------|-------|-------|-------|
1782     */
1783
1784    /**
1785     * Indicates that this view has reported that it can accept the current drag's content.
1786     * Cleared when the drag operation concludes.
1787     * @hide
1788     */
1789    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1790
1791    /**
1792     * Indicates that this view is currently directly under the drag location in a
1793     * drag-and-drop operation involving content that it can accept.  Cleared when
1794     * the drag exits the view, or when the drag operation concludes.
1795     * @hide
1796     */
1797    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1798
1799    /**
1800     * Horizontal layout direction of this view is from Left to Right.
1801     * Use with {@link #setLayoutDirection}.
1802     */
1803    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1804
1805    /**
1806     * Horizontal layout direction of this view is from Right to Left.
1807     * Use with {@link #setLayoutDirection}.
1808     */
1809    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1810
1811    /**
1812     * Horizontal layout direction of this view is inherited from its parent.
1813     * Use with {@link #setLayoutDirection}.
1814     */
1815    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1816
1817    /**
1818     * Horizontal layout direction of this view is from deduced from the default language
1819     * script for the locale. Use with {@link #setLayoutDirection}.
1820     */
1821    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1822
1823    /**
1824     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1825     * @hide
1826     */
1827    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1828
1829    /**
1830     * Mask for use with private flags indicating bits used for horizontal layout direction.
1831     * @hide
1832     */
1833    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1834
1835    /**
1836     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1837     * right-to-left direction.
1838     * @hide
1839     */
1840    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1841
1842    /**
1843     * Indicates whether the view horizontal layout direction has been resolved.
1844     * @hide
1845     */
1846    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1847
1848    /**
1849     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1850     * @hide
1851     */
1852    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1853            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1854
1855    /*
1856     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1857     * flag value.
1858     * @hide
1859     */
1860    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1861            LAYOUT_DIRECTION_LTR,
1862            LAYOUT_DIRECTION_RTL,
1863            LAYOUT_DIRECTION_INHERIT,
1864            LAYOUT_DIRECTION_LOCALE
1865    };
1866
1867    /**
1868     * Default horizontal layout direction.
1869     */
1870    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1871
1872    /**
1873     * Default horizontal layout direction.
1874     * @hide
1875     */
1876    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1877
1878    /**
1879     * Indicates that the view is tracking some sort of transient state
1880     * that the app should not need to be aware of, but that the framework
1881     * should take special care to preserve.
1882     *
1883     * @hide
1884     */
1885    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1886
1887    /**
1888     * Text direction is inherited thru {@link ViewGroup}
1889     */
1890    public static final int TEXT_DIRECTION_INHERIT = 0;
1891
1892    /**
1893     * Text direction is using "first strong algorithm". The first strong directional character
1894     * determines the paragraph direction. If there is no strong directional character, the
1895     * paragraph direction is the view's resolved layout direction.
1896     */
1897    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1898
1899    /**
1900     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1901     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1902     * If there are neither, the paragraph direction is the view's resolved layout direction.
1903     */
1904    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1905
1906    /**
1907     * Text direction is forced to LTR.
1908     */
1909    public static final int TEXT_DIRECTION_LTR = 3;
1910
1911    /**
1912     * Text direction is forced to RTL.
1913     */
1914    public static final int TEXT_DIRECTION_RTL = 4;
1915
1916    /**
1917     * Text direction is coming from the system Locale.
1918     */
1919    public static final int TEXT_DIRECTION_LOCALE = 5;
1920
1921    /**
1922     * Default text direction is inherited
1923     */
1924    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1925
1926    /**
1927     * Default resolved text direction
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1931
1932    /**
1933     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1934     * @hide
1935     */
1936    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1937
1938    /**
1939     * Mask for use with private flags indicating bits used for text direction.
1940     * @hide
1941     */
1942    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1943            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Array of text direction flags for mapping attribute "textDirection" to correct
1947     * flag value.
1948     * @hide
1949     */
1950    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1951            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1957    };
1958
1959    /**
1960     * Indicates whether the view text direction has been resolved.
1961     * @hide
1962     */
1963    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1964            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1965
1966    /**
1967     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1968     * @hide
1969     */
1970    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1971
1972    /**
1973     * Mask for use with private flags indicating bits used for resolved text direction.
1974     * @hide
1975     */
1976    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1977            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1978
1979    /**
1980     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1981     * @hide
1982     */
1983    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1984            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1985
1986    /*
1987     * Default text alignment. The text alignment of this View is inherited from its parent.
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1991
1992    /**
1993     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1994     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     */
1998    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1999
2000    /**
2001     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2006
2007    /**
2008     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2009     *
2010     * Use with {@link #setTextAlignment(int)}
2011     */
2012    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2013
2014    /**
2015     * Center the paragraph, e.g. ALIGN_CENTER.
2016     *
2017     * Use with {@link #setTextAlignment(int)}
2018     */
2019    public static final int TEXT_ALIGNMENT_CENTER = 4;
2020
2021    /**
2022     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2023     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2024     *
2025     * Use with {@link #setTextAlignment(int)}
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2028
2029    /**
2030     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2031     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2032     *
2033     * Use with {@link #setTextAlignment(int)}
2034     */
2035    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2036
2037    /**
2038     * Default text alignment is inherited
2039     */
2040    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2041
2042    /**
2043     * Default resolved text alignment
2044     * @hide
2045     */
2046    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2047
2048    /**
2049      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2050      * @hide
2051      */
2052    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2053
2054    /**
2055      * Mask for use with private flags indicating bits used for text alignment.
2056      * @hide
2057      */
2058    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2059
2060    /**
2061     * Array of text direction flags for mapping attribute "textAlignment" to correct
2062     * flag value.
2063     * @hide
2064     */
2065    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2066            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2073    };
2074
2075    /**
2076     * Indicates whether the view text alignment has been resolved.
2077     * @hide
2078     */
2079    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2080
2081    /**
2082     * Bit shift to get the resolved text alignment.
2083     * @hide
2084     */
2085    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2086
2087    /**
2088     * Mask for use with private flags indicating bits used for text alignment.
2089     * @hide
2090     */
2091    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2092            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2093
2094    /**
2095     * Indicates whether if the view text alignment has been resolved to gravity
2096     */
2097    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2098            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2099
2100    // Accessiblity constants for mPrivateFlags2
2101
2102    /**
2103     * Shift for the bits in {@link #mPrivateFlags2} related to the
2104     * "importantForAccessibility" attribute.
2105     */
2106    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2107
2108    /**
2109     * Automatically determine whether a view is important for accessibility.
2110     */
2111    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2112
2113    /**
2114     * The view is important for accessibility.
2115     */
2116    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2117
2118    /**
2119     * The view is not important for accessibility.
2120     */
2121    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2122
2123    /**
2124     * The default whether the view is important for accessibility.
2125     */
2126    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2127
2128    /**
2129     * Mask for obtainig the bits which specify how to determine
2130     * whether a view is important for accessibility.
2131     */
2132    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2133        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2134        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2135
2136    /**
2137     * Flag indicating whether a view has accessibility focus.
2138     */
2139    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2140
2141    /**
2142     * Flag whether the accessibility state of the subtree rooted at this view changed.
2143     */
2144    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2145
2146    /**
2147     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2148     * is used to check whether later changes to the view's transform should invalidate the
2149     * view to force the quickReject test to run again.
2150     */
2151    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2152
2153    /**
2154     * Flag indicating that start/end padding has been resolved into left/right padding
2155     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2156     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2157     * during measurement. In some special cases this is required such as when an adapter-based
2158     * view measures prospective children without attaching them to a window.
2159     */
2160    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2161
2162    /**
2163     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2164     */
2165    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2166
2167    /**
2168     * Group of bits indicating that RTL properties resolution is done.
2169     */
2170    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2171            PFLAG2_TEXT_DIRECTION_RESOLVED |
2172            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2173            PFLAG2_PADDING_RESOLVED |
2174            PFLAG2_DRAWABLE_RESOLVED;
2175
2176    // There are a couple of flags left in mPrivateFlags2
2177
2178    /* End of masks for mPrivateFlags2 */
2179
2180    /* Masks for mPrivateFlags3 */
2181
2182    /**
2183     * Flag indicating that view has a transform animation set on it. This is used to track whether
2184     * an animation is cleared between successive frames, in order to tell the associated
2185     * DisplayList to clear its animation matrix.
2186     */
2187    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2188
2189    /**
2190     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2191     * animation is cleared between successive frames, in order to tell the associated
2192     * DisplayList to restore its alpha value.
2193     */
2194    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2195
2196    /**
2197     * Flag indicating that the view has been through at least one layout since it
2198     * was last attached to a window.
2199     */
2200    static final int PFLAG3_IS_LAID_OUT = 0x4;
2201
2202    /**
2203     * Flag indicating that a call to measure() was skipped and should be done
2204     * instead when layout() is invoked.
2205     */
2206    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2207
2208    /**
2209     * Flag indicating that an overridden method correctly  called down to
2210     * the superclass implementation as required by the API spec.
2211     */
2212    static final int PFLAG3_CALLED_SUPER = 0x10;
2213
2214
2215    /* End of masks for mPrivateFlags3 */
2216
2217    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2218
2219    /**
2220     * Always allow a user to over-scroll this view, provided it is a
2221     * view that can scroll.
2222     *
2223     * @see #getOverScrollMode()
2224     * @see #setOverScrollMode(int)
2225     */
2226    public static final int OVER_SCROLL_ALWAYS = 0;
2227
2228    /**
2229     * Allow a user to over-scroll this view only if the content is large
2230     * enough to meaningfully scroll, provided it is a view that can scroll.
2231     *
2232     * @see #getOverScrollMode()
2233     * @see #setOverScrollMode(int)
2234     */
2235    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2236
2237    /**
2238     * Never allow a user to over-scroll this view.
2239     *
2240     * @see #getOverScrollMode()
2241     * @see #setOverScrollMode(int)
2242     */
2243    public static final int OVER_SCROLL_NEVER = 2;
2244
2245    /**
2246     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2247     * requested the system UI (status bar) to be visible (the default).
2248     *
2249     * @see #setSystemUiVisibility(int)
2250     */
2251    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2252
2253    /**
2254     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2255     * system UI to enter an unobtrusive "low profile" mode.
2256     *
2257     * <p>This is for use in games, book readers, video players, or any other
2258     * "immersive" application where the usual system chrome is deemed too distracting.
2259     *
2260     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2261     *
2262     * @see #setSystemUiVisibility(int)
2263     */
2264    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2265
2266    /**
2267     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2268     * system navigation be temporarily hidden.
2269     *
2270     * <p>This is an even less obtrusive state than that called for by
2271     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2272     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2273     * those to disappear. This is useful (in conjunction with the
2274     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2275     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2276     * window flags) for displaying content using every last pixel on the display.
2277     *
2278     * <p>There is a limitation: because navigation controls are so important, the least user
2279     * interaction will cause them to reappear immediately.  When this happens, both
2280     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2281     * so that both elements reappear at the same time.
2282     *
2283     * @see #setSystemUiVisibility(int)
2284     */
2285    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2286
2287    /**
2288     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2289     * into the normal fullscreen mode so that its content can take over the screen
2290     * while still allowing the user to interact with the application.
2291     *
2292     * <p>This has the same visual effect as
2293     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2294     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2295     * meaning that non-critical screen decorations (such as the status bar) will be
2296     * hidden while the user is in the View's window, focusing the experience on
2297     * that content.  Unlike the window flag, if you are using ActionBar in
2298     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2299     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2300     * hide the action bar.
2301     *
2302     * <p>This approach to going fullscreen is best used over the window flag when
2303     * it is a transient state -- that is, the application does this at certain
2304     * points in its user interaction where it wants to allow the user to focus
2305     * on content, but not as a continuous state.  For situations where the application
2306     * would like to simply stay full screen the entire time (such as a game that
2307     * wants to take over the screen), the
2308     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2309     * is usually a better approach.  The state set here will be removed by the system
2310     * in various situations (such as the user moving to another application) like
2311     * the other system UI states.
2312     *
2313     * <p>When using this flag, the application should provide some easy facility
2314     * for the user to go out of it.  A common example would be in an e-book
2315     * reader, where tapping on the screen brings back whatever screen and UI
2316     * decorations that had been hidden while the user was immersed in reading
2317     * the book.
2318     *
2319     * @see #setSystemUiVisibility(int)
2320     */
2321    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2322
2323    /**
2324     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2325     * flags, we would like a stable view of the content insets given to
2326     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2327     * will always represent the worst case that the application can expect
2328     * as a continuous state.  In the stock Android UI this is the space for
2329     * the system bar, nav bar, and status bar, but not more transient elements
2330     * such as an input method.
2331     *
2332     * The stable layout your UI sees is based on the system UI modes you can
2333     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2334     * then you will get a stable layout for changes of the
2335     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2336     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2337     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2338     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2339     * with a stable layout.  (Note that you should avoid using
2340     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2341     *
2342     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2343     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2344     * then a hidden status bar will be considered a "stable" state for purposes
2345     * here.  This allows your UI to continually hide the status bar, while still
2346     * using the system UI flags to hide the action bar while still retaining
2347     * a stable layout.  Note that changing the window fullscreen flag will never
2348     * provide a stable layout for a clean transition.
2349     *
2350     * <p>If you are using ActionBar in
2351     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2352     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2353     * insets it adds to those given to the application.
2354     */
2355    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2356
2357    /**
2358     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2359     * to be layed out as if it has requested
2360     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2361     * allows it to avoid artifacts when switching in and out of that mode, at
2362     * the expense that some of its user interface may be covered by screen
2363     * decorations when they are shown.  You can perform layout of your inner
2364     * UI elements to account for the navigation system UI through the
2365     * {@link #fitSystemWindows(Rect)} method.
2366     */
2367    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2368
2369    /**
2370     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2371     * to be layed out as if it has requested
2372     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2373     * allows it to avoid artifacts when switching in and out of that mode, at
2374     * the expense that some of its user interface may be covered by screen
2375     * decorations when they are shown.  You can perform layout of your inner
2376     * UI elements to account for non-fullscreen system UI through the
2377     * {@link #fitSystemWindows(Rect)} method.
2378     */
2379    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2380
2381    /**
2382     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2383     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2384     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2385     * experience while also hiding the system bars.  If this flag is not set,
2386     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2387     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2388     * if the user swipes from the top of the screen.
2389     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2390     * system gestures, such as swiping from the top of the screen.  These transient system bars
2391     * will overlay app’s content, may have some degree of transparency, and will automatically
2392     * hide after a short timeout.
2393     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2394     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2395     * with one or both of those flags.</p>
2396     */
2397    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2398
2399    /**
2400     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2401     * transparency.
2402     *
2403     * <p>The transparency request may be denied if the bar is in another mode with a specific
2404     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2405     */
2406    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2407
2408    /**
2409     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2410     * transparency.
2411     *
2412     * <p>The transparency request may be denied if the bar is in another mode with a specific
2413     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2414     */
2415    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2416
2417    /**
2418     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2419     */
2420    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2421
2422    /**
2423     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2424     */
2425    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2426
2427    /**
2428     * @hide
2429     *
2430     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2431     * out of the public fields to keep the undefined bits out of the developer's way.
2432     *
2433     * Flag to make the status bar not expandable.  Unless you also
2434     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2435     */
2436    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2437
2438    /**
2439     * @hide
2440     *
2441     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2442     * out of the public fields to keep the undefined bits out of the developer's way.
2443     *
2444     * Flag to hide notification icons and scrolling ticker text.
2445     */
2446    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2447
2448    /**
2449     * @hide
2450     *
2451     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2452     * out of the public fields to keep the undefined bits out of the developer's way.
2453     *
2454     * Flag to disable incoming notification alerts.  This will not block
2455     * icons, but it will block sound, vibrating and other visual or aural notifications.
2456     */
2457    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2458
2459    /**
2460     * @hide
2461     *
2462     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2463     * out of the public fields to keep the undefined bits out of the developer's way.
2464     *
2465     * Flag to hide only the scrolling ticker.  Note that
2466     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2467     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2468     */
2469    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2470
2471    /**
2472     * @hide
2473     *
2474     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2475     * out of the public fields to keep the undefined bits out of the developer's way.
2476     *
2477     * Flag to hide the center system info area.
2478     */
2479    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2480
2481    /**
2482     * @hide
2483     *
2484     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2485     * out of the public fields to keep the undefined bits out of the developer's way.
2486     *
2487     * Flag to hide only the home button.  Don't use this
2488     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2489     */
2490    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2491
2492    /**
2493     * @hide
2494     *
2495     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2496     * out of the public fields to keep the undefined bits out of the developer's way.
2497     *
2498     * Flag to hide only the back button. Don't use this
2499     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2500     */
2501    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2502
2503    /**
2504     * @hide
2505     *
2506     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2507     * out of the public fields to keep the undefined bits out of the developer's way.
2508     *
2509     * Flag to hide only the clock.  You might use this if your activity has
2510     * its own clock making the status bar's clock redundant.
2511     */
2512    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2513
2514    /**
2515     * @hide
2516     *
2517     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2518     * out of the public fields to keep the undefined bits out of the developer's way.
2519     *
2520     * Flag to hide only the recent apps button. Don't use this
2521     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2522     */
2523    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2524
2525    /**
2526     * @hide
2527     *
2528     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2529     * out of the public fields to keep the undefined bits out of the developer's way.
2530     *
2531     * Flag to disable the global search gesture. Don't use this
2532     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2533     */
2534    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2535
2536    /**
2537     * @hide
2538     *
2539     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2540     * out of the public fields to keep the undefined bits out of the developer's way.
2541     *
2542     * Flag to specify that the status bar is displayed in transient mode.
2543     */
2544    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2545
2546    /**
2547     * @hide
2548     *
2549     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2550     * out of the public fields to keep the undefined bits out of the developer's way.
2551     *
2552     * Flag to specify that the navigation bar is displayed in transient mode.
2553     */
2554    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2555
2556    /**
2557     * @hide
2558     *
2559     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2560     * out of the public fields to keep the undefined bits out of the developer's way.
2561     *
2562     * Flag to specify that the hidden status bar would like to be shown.
2563     */
2564    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2565
2566    /**
2567     * @hide
2568     *
2569     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2570     * out of the public fields to keep the undefined bits out of the developer's way.
2571     *
2572     * Flag to specify that the hidden navigation bar would like to be shown.
2573     */
2574    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2575
2576    /**
2577     * @hide
2578     */
2579    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2580
2581    /**
2582     * These are the system UI flags that can be cleared by events outside
2583     * of an application.  Currently this is just the ability to tap on the
2584     * screen while hiding the navigation bar to have it return.
2585     * @hide
2586     */
2587    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2588            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2589            | SYSTEM_UI_FLAG_FULLSCREEN;
2590
2591    /**
2592     * Flags that can impact the layout in relation to system UI.
2593     */
2594    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2595            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2596            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2597
2598    /**
2599     * Find views that render the specified text.
2600     *
2601     * @see #findViewsWithText(ArrayList, CharSequence, int)
2602     */
2603    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2604
2605    /**
2606     * Find find views that contain the specified content description.
2607     *
2608     * @see #findViewsWithText(ArrayList, CharSequence, int)
2609     */
2610    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2611
2612    /**
2613     * Find views that contain {@link AccessibilityNodeProvider}. Such
2614     * a View is a root of virtual view hierarchy and may contain the searched
2615     * text. If this flag is set Views with providers are automatically
2616     * added and it is a responsibility of the client to call the APIs of
2617     * the provider to determine whether the virtual tree rooted at this View
2618     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2619     * represeting the virtual views with this text.
2620     *
2621     * @see #findViewsWithText(ArrayList, CharSequence, int)
2622     *
2623     * @hide
2624     */
2625    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2626
2627    /**
2628     * The undefined cursor position.
2629     *
2630     * @hide
2631     */
2632    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2633
2634    /**
2635     * Indicates that the screen has changed state and is now off.
2636     *
2637     * @see #onScreenStateChanged(int)
2638     */
2639    public static final int SCREEN_STATE_OFF = 0x0;
2640
2641    /**
2642     * Indicates that the screen has changed state and is now on.
2643     *
2644     * @see #onScreenStateChanged(int)
2645     */
2646    public static final int SCREEN_STATE_ON = 0x1;
2647
2648    /**
2649     * Controls the over-scroll mode for this view.
2650     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2651     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2652     * and {@link #OVER_SCROLL_NEVER}.
2653     */
2654    private int mOverScrollMode;
2655
2656    /**
2657     * The parent this view is attached to.
2658     * {@hide}
2659     *
2660     * @see #getParent()
2661     */
2662    protected ViewParent mParent;
2663
2664    /**
2665     * {@hide}
2666     */
2667    AttachInfo mAttachInfo;
2668
2669    /**
2670     * {@hide}
2671     */
2672    @ViewDebug.ExportedProperty(flagMapping = {
2673        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2674                name = "FORCE_LAYOUT"),
2675        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2676                name = "LAYOUT_REQUIRED"),
2677        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2678            name = "DRAWING_CACHE_INVALID", outputIf = false),
2679        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2680        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2681        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2682        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2683    })
2684    int mPrivateFlags;
2685    int mPrivateFlags2;
2686    int mPrivateFlags3;
2687
2688    /**
2689     * This view's request for the visibility of the status bar.
2690     * @hide
2691     */
2692    @ViewDebug.ExportedProperty(flagMapping = {
2693        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2694                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2695                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2696        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2697                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2698                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2699        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2700                                equals = SYSTEM_UI_FLAG_VISIBLE,
2701                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2702    })
2703    int mSystemUiVisibility;
2704
2705    /**
2706     * Reference count for transient state.
2707     * @see #setHasTransientState(boolean)
2708     */
2709    int mTransientStateCount = 0;
2710
2711    /**
2712     * Count of how many windows this view has been attached to.
2713     */
2714    int mWindowAttachCount;
2715
2716    /**
2717     * The layout parameters associated with this view and used by the parent
2718     * {@link android.view.ViewGroup} to determine how this view should be
2719     * laid out.
2720     * {@hide}
2721     */
2722    protected ViewGroup.LayoutParams mLayoutParams;
2723
2724    /**
2725     * The view flags hold various views states.
2726     * {@hide}
2727     */
2728    @ViewDebug.ExportedProperty
2729    int mViewFlags;
2730
2731    static class TransformationInfo {
2732        /**
2733         * The transform matrix for the View. This transform is calculated internally
2734         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2735         * is used by default. Do *not* use this variable directly; instead call
2736         * getMatrix(), which will automatically recalculate the matrix if necessary
2737         * to get the correct matrix based on the latest rotation and scale properties.
2738         */
2739        private final Matrix mMatrix = new Matrix();
2740
2741        /**
2742         * The transform matrix for the View. This transform is calculated internally
2743         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2744         * is used by default. Do *not* use this variable directly; instead call
2745         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2746         * to get the correct matrix based on the latest rotation and scale properties.
2747         */
2748        private Matrix mInverseMatrix;
2749
2750        /**
2751         * An internal variable that tracks whether we need to recalculate the
2752         * transform matrix, based on whether the rotation or scaleX/Y properties
2753         * have changed since the matrix was last calculated.
2754         */
2755        boolean mMatrixDirty = false;
2756
2757        /**
2758         * An internal variable that tracks whether we need to recalculate the
2759         * transform matrix, based on whether the rotation or scaleX/Y properties
2760         * have changed since the matrix was last calculated.
2761         */
2762        private boolean mInverseMatrixDirty = true;
2763
2764        /**
2765         * A variable that tracks whether we need to recalculate the
2766         * transform matrix, based on whether the rotation or scaleX/Y properties
2767         * have changed since the matrix was last calculated. This variable
2768         * is only valid after a call to updateMatrix() or to a function that
2769         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2770         */
2771        private boolean mMatrixIsIdentity = true;
2772
2773        /**
2774         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2775         */
2776        private Camera mCamera = null;
2777
2778        /**
2779         * This matrix is used when computing the matrix for 3D rotations.
2780         */
2781        private Matrix matrix3D = null;
2782
2783        /**
2784         * These prev values are used to recalculate a centered pivot point when necessary. The
2785         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2786         * set), so thes values are only used then as well.
2787         */
2788        private int mPrevWidth = -1;
2789        private int mPrevHeight = -1;
2790
2791        /**
2792         * The degrees rotation around the vertical axis through the pivot point.
2793         */
2794        @ViewDebug.ExportedProperty
2795        float mRotationY = 0f;
2796
2797        /**
2798         * The degrees rotation around the horizontal axis through the pivot point.
2799         */
2800        @ViewDebug.ExportedProperty
2801        float mRotationX = 0f;
2802
2803        /**
2804         * The degrees rotation around the pivot point.
2805         */
2806        @ViewDebug.ExportedProperty
2807        float mRotation = 0f;
2808
2809        /**
2810         * The amount of translation of the object away from its left property (post-layout).
2811         */
2812        @ViewDebug.ExportedProperty
2813        float mTranslationX = 0f;
2814
2815        /**
2816         * The amount of translation of the object away from its top property (post-layout).
2817         */
2818        @ViewDebug.ExportedProperty
2819        float mTranslationY = 0f;
2820
2821        /**
2822         * The amount of scale in the x direction around the pivot point. A
2823         * value of 1 means no scaling is applied.
2824         */
2825        @ViewDebug.ExportedProperty
2826        float mScaleX = 1f;
2827
2828        /**
2829         * The amount of scale in the y direction around the pivot point. A
2830         * value of 1 means no scaling is applied.
2831         */
2832        @ViewDebug.ExportedProperty
2833        float mScaleY = 1f;
2834
2835        /**
2836         * The x location of the point around which the view is rotated and scaled.
2837         */
2838        @ViewDebug.ExportedProperty
2839        float mPivotX = 0f;
2840
2841        /**
2842         * The y location of the point around which the view is rotated and scaled.
2843         */
2844        @ViewDebug.ExportedProperty
2845        float mPivotY = 0f;
2846
2847        /**
2848         * The opacity of the View. This is a value from 0 to 1, where 0 means
2849         * completely transparent and 1 means completely opaque.
2850         */
2851        @ViewDebug.ExportedProperty
2852        float mAlpha = 1f;
2853    }
2854
2855    TransformationInfo mTransformationInfo;
2856
2857    /**
2858     * Current clip bounds. to which all drawing of this view are constrained.
2859     */
2860    private Rect mClipBounds = null;
2861
2862    private boolean mLastIsOpaque;
2863
2864    /**
2865     * Convenience value to check for float values that are close enough to zero to be considered
2866     * zero.
2867     */
2868    private static final float NONZERO_EPSILON = .001f;
2869
2870    /**
2871     * The distance in pixels from the left edge of this view's parent
2872     * to the left edge of this view.
2873     * {@hide}
2874     */
2875    @ViewDebug.ExportedProperty(category = "layout")
2876    protected int mLeft;
2877    /**
2878     * The distance in pixels from the left edge of this view's parent
2879     * to the right edge of this view.
2880     * {@hide}
2881     */
2882    @ViewDebug.ExportedProperty(category = "layout")
2883    protected int mRight;
2884    /**
2885     * The distance in pixels from the top edge of this view's parent
2886     * to the top edge of this view.
2887     * {@hide}
2888     */
2889    @ViewDebug.ExportedProperty(category = "layout")
2890    protected int mTop;
2891    /**
2892     * The distance in pixels from the top edge of this view's parent
2893     * to the bottom edge of this view.
2894     * {@hide}
2895     */
2896    @ViewDebug.ExportedProperty(category = "layout")
2897    protected int mBottom;
2898
2899    /**
2900     * The offset, in pixels, by which the content of this view is scrolled
2901     * horizontally.
2902     * {@hide}
2903     */
2904    @ViewDebug.ExportedProperty(category = "scrolling")
2905    protected int mScrollX;
2906    /**
2907     * The offset, in pixels, by which the content of this view is scrolled
2908     * vertically.
2909     * {@hide}
2910     */
2911    @ViewDebug.ExportedProperty(category = "scrolling")
2912    protected int mScrollY;
2913
2914    /**
2915     * The left padding in pixels, that is the distance in pixels between the
2916     * left edge of this view and the left edge of its content.
2917     * {@hide}
2918     */
2919    @ViewDebug.ExportedProperty(category = "padding")
2920    protected int mPaddingLeft = 0;
2921    /**
2922     * The right padding in pixels, that is the distance in pixels between the
2923     * right edge of this view and the right edge of its content.
2924     * {@hide}
2925     */
2926    @ViewDebug.ExportedProperty(category = "padding")
2927    protected int mPaddingRight = 0;
2928    /**
2929     * The top padding in pixels, that is the distance in pixels between the
2930     * top edge of this view and the top edge of its content.
2931     * {@hide}
2932     */
2933    @ViewDebug.ExportedProperty(category = "padding")
2934    protected int mPaddingTop;
2935    /**
2936     * The bottom padding in pixels, that is the distance in pixels between the
2937     * bottom edge of this view and the bottom edge of its content.
2938     * {@hide}
2939     */
2940    @ViewDebug.ExportedProperty(category = "padding")
2941    protected int mPaddingBottom;
2942
2943    /**
2944     * The layout insets in pixels, that is the distance in pixels between the
2945     * visible edges of this view its bounds.
2946     */
2947    private Insets mLayoutInsets;
2948
2949    /**
2950     * Briefly describes the view and is primarily used for accessibility support.
2951     */
2952    private CharSequence mContentDescription;
2953
2954    /**
2955     * Specifies the id of a view for which this view serves as a label for
2956     * accessibility purposes.
2957     */
2958    private int mLabelForId = View.NO_ID;
2959
2960    /**
2961     * Predicate for matching labeled view id with its label for
2962     * accessibility purposes.
2963     */
2964    private MatchLabelForPredicate mMatchLabelForPredicate;
2965
2966    /**
2967     * Predicate for matching a view by its id.
2968     */
2969    private MatchIdPredicate mMatchIdPredicate;
2970
2971    /**
2972     * Cache the paddingRight set by the user to append to the scrollbar's size.
2973     *
2974     * @hide
2975     */
2976    @ViewDebug.ExportedProperty(category = "padding")
2977    protected int mUserPaddingRight;
2978
2979    /**
2980     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2981     *
2982     * @hide
2983     */
2984    @ViewDebug.ExportedProperty(category = "padding")
2985    protected int mUserPaddingBottom;
2986
2987    /**
2988     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2989     *
2990     * @hide
2991     */
2992    @ViewDebug.ExportedProperty(category = "padding")
2993    protected int mUserPaddingLeft;
2994
2995    /**
2996     * Cache the paddingStart set by the user to append to the scrollbar's size.
2997     *
2998     */
2999    @ViewDebug.ExportedProperty(category = "padding")
3000    int mUserPaddingStart;
3001
3002    /**
3003     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3004     *
3005     */
3006    @ViewDebug.ExportedProperty(category = "padding")
3007    int mUserPaddingEnd;
3008
3009    /**
3010     * Cache initial left padding.
3011     *
3012     * @hide
3013     */
3014    int mUserPaddingLeftInitial;
3015
3016    /**
3017     * Cache initial right padding.
3018     *
3019     * @hide
3020     */
3021    int mUserPaddingRightInitial;
3022
3023    /**
3024     * Default undefined padding
3025     */
3026    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3027
3028    /**
3029     * @hide
3030     */
3031    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3032    /**
3033     * @hide
3034     */
3035    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3036
3037    private LongSparseLongArray mMeasureCache;
3038
3039    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3040    private Drawable mBackground;
3041
3042    private int mBackgroundResource;
3043    private boolean mBackgroundSizeChanged;
3044
3045    static class ListenerInfo {
3046        /**
3047         * Listener used to dispatch focus change events.
3048         * This field should be made private, so it is hidden from the SDK.
3049         * {@hide}
3050         */
3051        protected OnFocusChangeListener mOnFocusChangeListener;
3052
3053        /**
3054         * Listeners for layout change events.
3055         */
3056        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3057
3058        /**
3059         * Listeners for attach events.
3060         */
3061        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3062
3063        /**
3064         * Listener used to dispatch click events.
3065         * This field should be made private, so it is hidden from the SDK.
3066         * {@hide}
3067         */
3068        public OnClickListener mOnClickListener;
3069
3070        /**
3071         * Listener used to dispatch long click events.
3072         * This field should be made private, so it is hidden from the SDK.
3073         * {@hide}
3074         */
3075        protected OnLongClickListener mOnLongClickListener;
3076
3077        /**
3078         * Listener used to build the context menu.
3079         * This field should be made private, so it is hidden from the SDK.
3080         * {@hide}
3081         */
3082        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3083
3084        private OnKeyListener mOnKeyListener;
3085
3086        private OnTouchListener mOnTouchListener;
3087
3088        private OnHoverListener mOnHoverListener;
3089
3090        private OnGenericMotionListener mOnGenericMotionListener;
3091
3092        private OnDragListener mOnDragListener;
3093
3094        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3095    }
3096
3097    ListenerInfo mListenerInfo;
3098
3099    /**
3100     * The application environment this view lives in.
3101     * This field should be made private, so it is hidden from the SDK.
3102     * {@hide}
3103     */
3104    protected Context mContext;
3105
3106    private final Resources mResources;
3107
3108    private ScrollabilityCache mScrollCache;
3109
3110    private int[] mDrawableState = null;
3111
3112    /**
3113     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3114     * the user may specify which view to go to next.
3115     */
3116    private int mNextFocusLeftId = View.NO_ID;
3117
3118    /**
3119     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3120     * the user may specify which view to go to next.
3121     */
3122    private int mNextFocusRightId = View.NO_ID;
3123
3124    /**
3125     * When this view has focus and the next focus is {@link #FOCUS_UP},
3126     * the user may specify which view to go to next.
3127     */
3128    private int mNextFocusUpId = View.NO_ID;
3129
3130    /**
3131     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3132     * the user may specify which view to go to next.
3133     */
3134    private int mNextFocusDownId = View.NO_ID;
3135
3136    /**
3137     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3138     * the user may specify which view to go to next.
3139     */
3140    int mNextFocusForwardId = View.NO_ID;
3141
3142    private CheckForLongPress mPendingCheckForLongPress;
3143    private CheckForTap mPendingCheckForTap = null;
3144    private PerformClick mPerformClick;
3145    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3146
3147    private UnsetPressedState mUnsetPressedState;
3148
3149    /**
3150     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3151     * up event while a long press is invoked as soon as the long press duration is reached, so
3152     * a long press could be performed before the tap is checked, in which case the tap's action
3153     * should not be invoked.
3154     */
3155    private boolean mHasPerformedLongPress;
3156
3157    /**
3158     * The minimum height of the view. We'll try our best to have the height
3159     * of this view to at least this amount.
3160     */
3161    @ViewDebug.ExportedProperty(category = "measurement")
3162    private int mMinHeight;
3163
3164    /**
3165     * The minimum width of the view. We'll try our best to have the width
3166     * of this view to at least this amount.
3167     */
3168    @ViewDebug.ExportedProperty(category = "measurement")
3169    private int mMinWidth;
3170
3171    /**
3172     * The delegate to handle touch events that are physically in this view
3173     * but should be handled by another view.
3174     */
3175    private TouchDelegate mTouchDelegate = null;
3176
3177    /**
3178     * Solid color to use as a background when creating the drawing cache. Enables
3179     * the cache to use 16 bit bitmaps instead of 32 bit.
3180     */
3181    private int mDrawingCacheBackgroundColor = 0;
3182
3183    /**
3184     * Special tree observer used when mAttachInfo is null.
3185     */
3186    private ViewTreeObserver mFloatingTreeObserver;
3187
3188    /**
3189     * Cache the touch slop from the context that created the view.
3190     */
3191    private int mTouchSlop;
3192
3193    /**
3194     * Object that handles automatic animation of view properties.
3195     */
3196    private ViewPropertyAnimator mAnimator = null;
3197
3198    /**
3199     * Flag indicating that a drag can cross window boundaries.  When
3200     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3201     * with this flag set, all visible applications will be able to participate
3202     * in the drag operation and receive the dragged content.
3203     *
3204     * @hide
3205     */
3206    public static final int DRAG_FLAG_GLOBAL = 1;
3207
3208    /**
3209     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3210     */
3211    private float mVerticalScrollFactor;
3212
3213    /**
3214     * Position of the vertical scroll bar.
3215     */
3216    private int mVerticalScrollbarPosition;
3217
3218    /**
3219     * Position the scroll bar at the default position as determined by the system.
3220     */
3221    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3222
3223    /**
3224     * Position the scroll bar along the left edge.
3225     */
3226    public static final int SCROLLBAR_POSITION_LEFT = 1;
3227
3228    /**
3229     * Position the scroll bar along the right edge.
3230     */
3231    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3232
3233    /**
3234     * Indicates that the view does not have a layer.
3235     *
3236     * @see #getLayerType()
3237     * @see #setLayerType(int, android.graphics.Paint)
3238     * @see #LAYER_TYPE_SOFTWARE
3239     * @see #LAYER_TYPE_HARDWARE
3240     */
3241    public static final int LAYER_TYPE_NONE = 0;
3242
3243    /**
3244     * <p>Indicates that the view has a software layer. A software layer is backed
3245     * by a bitmap and causes the view to be rendered using Android's software
3246     * rendering pipeline, even if hardware acceleration is enabled.</p>
3247     *
3248     * <p>Software layers have various usages:</p>
3249     * <p>When the application is not using hardware acceleration, a software layer
3250     * is useful to apply a specific color filter and/or blending mode and/or
3251     * translucency to a view and all its children.</p>
3252     * <p>When the application is using hardware acceleration, a software layer
3253     * is useful to render drawing primitives not supported by the hardware
3254     * accelerated pipeline. It can also be used to cache a complex view tree
3255     * into a texture and reduce the complexity of drawing operations. For instance,
3256     * when animating a complex view tree with a translation, a software layer can
3257     * be used to render the view tree only once.</p>
3258     * <p>Software layers should be avoided when the affected view tree updates
3259     * often. Every update will require to re-render the software layer, which can
3260     * potentially be slow (particularly when hardware acceleration is turned on
3261     * since the layer will have to be uploaded into a hardware texture after every
3262     * update.)</p>
3263     *
3264     * @see #getLayerType()
3265     * @see #setLayerType(int, android.graphics.Paint)
3266     * @see #LAYER_TYPE_NONE
3267     * @see #LAYER_TYPE_HARDWARE
3268     */
3269    public static final int LAYER_TYPE_SOFTWARE = 1;
3270
3271    /**
3272     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3273     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3274     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3275     * rendering pipeline, but only if hardware acceleration is turned on for the
3276     * view hierarchy. When hardware acceleration is turned off, hardware layers
3277     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3278     *
3279     * <p>A hardware layer is useful to apply a specific color filter and/or
3280     * blending mode and/or translucency to a view and all its children.</p>
3281     * <p>A hardware layer can be used to cache a complex view tree into a
3282     * texture and reduce the complexity of drawing operations. For instance,
3283     * when animating a complex view tree with a translation, a hardware layer can
3284     * be used to render the view tree only once.</p>
3285     * <p>A hardware layer can also be used to increase the rendering quality when
3286     * rotation transformations are applied on a view. It can also be used to
3287     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3288     *
3289     * @see #getLayerType()
3290     * @see #setLayerType(int, android.graphics.Paint)
3291     * @see #LAYER_TYPE_NONE
3292     * @see #LAYER_TYPE_SOFTWARE
3293     */
3294    public static final int LAYER_TYPE_HARDWARE = 2;
3295
3296    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3297            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3298            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3299            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3300    })
3301    int mLayerType = LAYER_TYPE_NONE;
3302    Paint mLayerPaint;
3303    Rect mLocalDirtyRect;
3304    private HardwareLayer mHardwareLayer;
3305
3306    /**
3307     * Set to true when drawing cache is enabled and cannot be created.
3308     *
3309     * @hide
3310     */
3311    public boolean mCachingFailed;
3312    private Bitmap mDrawingCache;
3313    private Bitmap mUnscaledDrawingCache;
3314
3315    DisplayList mDisplayList;
3316
3317    /**
3318     * Set to true when the view is sending hover accessibility events because it
3319     * is the innermost hovered view.
3320     */
3321    private boolean mSendingHoverAccessibilityEvents;
3322
3323    /**
3324     * Delegate for injecting accessibility functionality.
3325     */
3326    AccessibilityDelegate mAccessibilityDelegate;
3327
3328    /**
3329     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3330     * and add/remove objects to/from the overlay directly through the Overlay methods.
3331     */
3332    ViewOverlay mOverlay;
3333
3334    /**
3335     * Consistency verifier for debugging purposes.
3336     * @hide
3337     */
3338    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3339            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3340                    new InputEventConsistencyVerifier(this, 0) : null;
3341
3342    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3343
3344    /**
3345     * Simple constructor to use when creating a view from code.
3346     *
3347     * @param context The Context the view is running in, through which it can
3348     *        access the current theme, resources, etc.
3349     */
3350    public View(Context context) {
3351        mContext = context;
3352        mResources = context != null ? context.getResources() : null;
3353        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3354        // Set some flags defaults
3355        mPrivateFlags2 =
3356                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3357                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3358                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3359                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3360                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3361                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3362        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3363        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3364        mUserPaddingStart = UNDEFINED_PADDING;
3365        mUserPaddingEnd = UNDEFINED_PADDING;
3366
3367        if (!sUseBrokenMakeMeasureSpec && context != null &&
3368                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3369            // Older apps may need this compatibility hack for measurement.
3370            sUseBrokenMakeMeasureSpec = true;
3371        }
3372    }
3373
3374    /**
3375     * Constructor that is called when inflating a view from XML. This is called
3376     * when a view is being constructed from an XML file, supplying attributes
3377     * that were specified in the XML file. This version uses a default style of
3378     * 0, so the only attribute values applied are those in the Context's Theme
3379     * and the given AttributeSet.
3380     *
3381     * <p>
3382     * The method onFinishInflate() will be called after all children have been
3383     * added.
3384     *
3385     * @param context The Context the view is running in, through which it can
3386     *        access the current theme, resources, etc.
3387     * @param attrs The attributes of the XML tag that is inflating the view.
3388     * @see #View(Context, AttributeSet, int)
3389     */
3390    public View(Context context, AttributeSet attrs) {
3391        this(context, attrs, 0);
3392    }
3393
3394    /**
3395     * Perform inflation from XML and apply a class-specific base style. This
3396     * constructor of View allows subclasses to use their own base style when
3397     * they are inflating. For example, a Button class's constructor would call
3398     * this version of the super class constructor and supply
3399     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3400     * the theme's button style to modify all of the base view attributes (in
3401     * particular its background) as well as the Button class's attributes.
3402     *
3403     * @param context The Context the view is running in, through which it can
3404     *        access the current theme, resources, etc.
3405     * @param attrs The attributes of the XML tag that is inflating the view.
3406     * @param defStyleAttr An attribute in the current theme that contains a
3407     *        reference to a style resource to apply to this view. If 0, no
3408     *        default style will be applied.
3409     * @see #View(Context, AttributeSet)
3410     */
3411    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3412        this(context);
3413
3414        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3415                defStyleAttr, 0);
3416
3417        Drawable background = null;
3418
3419        int leftPadding = -1;
3420        int topPadding = -1;
3421        int rightPadding = -1;
3422        int bottomPadding = -1;
3423        int startPadding = UNDEFINED_PADDING;
3424        int endPadding = UNDEFINED_PADDING;
3425
3426        int padding = -1;
3427
3428        int viewFlagValues = 0;
3429        int viewFlagMasks = 0;
3430
3431        boolean setScrollContainer = false;
3432
3433        int x = 0;
3434        int y = 0;
3435
3436        float tx = 0;
3437        float ty = 0;
3438        float rotation = 0;
3439        float rotationX = 0;
3440        float rotationY = 0;
3441        float sx = 1f;
3442        float sy = 1f;
3443        boolean transformSet = false;
3444
3445        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3446        int overScrollMode = mOverScrollMode;
3447        boolean initializeScrollbars = false;
3448
3449        boolean leftPaddingDefined = false;
3450        boolean rightPaddingDefined = false;
3451        boolean startPaddingDefined = false;
3452        boolean endPaddingDefined = false;
3453
3454        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3455
3456        final int N = a.getIndexCount();
3457        for (int i = 0; i < N; i++) {
3458            int attr = a.getIndex(i);
3459            switch (attr) {
3460                case com.android.internal.R.styleable.View_background:
3461                    background = a.getDrawable(attr);
3462                    break;
3463                case com.android.internal.R.styleable.View_padding:
3464                    padding = a.getDimensionPixelSize(attr, -1);
3465                    mUserPaddingLeftInitial = padding;
3466                    mUserPaddingRightInitial = padding;
3467                    leftPaddingDefined = true;
3468                    rightPaddingDefined = true;
3469                    break;
3470                 case com.android.internal.R.styleable.View_paddingLeft:
3471                    leftPadding = a.getDimensionPixelSize(attr, -1);
3472                    mUserPaddingLeftInitial = leftPadding;
3473                    leftPaddingDefined = true;
3474                    break;
3475                case com.android.internal.R.styleable.View_paddingTop:
3476                    topPadding = a.getDimensionPixelSize(attr, -1);
3477                    break;
3478                case com.android.internal.R.styleable.View_paddingRight:
3479                    rightPadding = a.getDimensionPixelSize(attr, -1);
3480                    mUserPaddingRightInitial = rightPadding;
3481                    rightPaddingDefined = true;
3482                    break;
3483                case com.android.internal.R.styleable.View_paddingBottom:
3484                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3485                    break;
3486                case com.android.internal.R.styleable.View_paddingStart:
3487                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3488                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3489                    break;
3490                case com.android.internal.R.styleable.View_paddingEnd:
3491                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3492                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3493                    break;
3494                case com.android.internal.R.styleable.View_scrollX:
3495                    x = a.getDimensionPixelOffset(attr, 0);
3496                    break;
3497                case com.android.internal.R.styleable.View_scrollY:
3498                    y = a.getDimensionPixelOffset(attr, 0);
3499                    break;
3500                case com.android.internal.R.styleable.View_alpha:
3501                    setAlpha(a.getFloat(attr, 1f));
3502                    break;
3503                case com.android.internal.R.styleable.View_transformPivotX:
3504                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3505                    break;
3506                case com.android.internal.R.styleable.View_transformPivotY:
3507                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3508                    break;
3509                case com.android.internal.R.styleable.View_translationX:
3510                    tx = a.getDimensionPixelOffset(attr, 0);
3511                    transformSet = true;
3512                    break;
3513                case com.android.internal.R.styleable.View_translationY:
3514                    ty = a.getDimensionPixelOffset(attr, 0);
3515                    transformSet = true;
3516                    break;
3517                case com.android.internal.R.styleable.View_rotation:
3518                    rotation = a.getFloat(attr, 0);
3519                    transformSet = true;
3520                    break;
3521                case com.android.internal.R.styleable.View_rotationX:
3522                    rotationX = a.getFloat(attr, 0);
3523                    transformSet = true;
3524                    break;
3525                case com.android.internal.R.styleable.View_rotationY:
3526                    rotationY = a.getFloat(attr, 0);
3527                    transformSet = true;
3528                    break;
3529                case com.android.internal.R.styleable.View_scaleX:
3530                    sx = a.getFloat(attr, 1f);
3531                    transformSet = true;
3532                    break;
3533                case com.android.internal.R.styleable.View_scaleY:
3534                    sy = a.getFloat(attr, 1f);
3535                    transformSet = true;
3536                    break;
3537                case com.android.internal.R.styleable.View_id:
3538                    mID = a.getResourceId(attr, NO_ID);
3539                    break;
3540                case com.android.internal.R.styleable.View_tag:
3541                    mTag = a.getText(attr);
3542                    break;
3543                case com.android.internal.R.styleable.View_fitsSystemWindows:
3544                    if (a.getBoolean(attr, false)) {
3545                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3546                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3547                    }
3548                    break;
3549                case com.android.internal.R.styleable.View_focusable:
3550                    if (a.getBoolean(attr, false)) {
3551                        viewFlagValues |= FOCUSABLE;
3552                        viewFlagMasks |= FOCUSABLE_MASK;
3553                    }
3554                    break;
3555                case com.android.internal.R.styleable.View_focusableInTouchMode:
3556                    if (a.getBoolean(attr, false)) {
3557                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3558                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3559                    }
3560                    break;
3561                case com.android.internal.R.styleable.View_clickable:
3562                    if (a.getBoolean(attr, false)) {
3563                        viewFlagValues |= CLICKABLE;
3564                        viewFlagMasks |= CLICKABLE;
3565                    }
3566                    break;
3567                case com.android.internal.R.styleable.View_longClickable:
3568                    if (a.getBoolean(attr, false)) {
3569                        viewFlagValues |= LONG_CLICKABLE;
3570                        viewFlagMasks |= LONG_CLICKABLE;
3571                    }
3572                    break;
3573                case com.android.internal.R.styleable.View_saveEnabled:
3574                    if (!a.getBoolean(attr, true)) {
3575                        viewFlagValues |= SAVE_DISABLED;
3576                        viewFlagMasks |= SAVE_DISABLED_MASK;
3577                    }
3578                    break;
3579                case com.android.internal.R.styleable.View_duplicateParentState:
3580                    if (a.getBoolean(attr, false)) {
3581                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3582                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3583                    }
3584                    break;
3585                case com.android.internal.R.styleable.View_visibility:
3586                    final int visibility = a.getInt(attr, 0);
3587                    if (visibility != 0) {
3588                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3589                        viewFlagMasks |= VISIBILITY_MASK;
3590                    }
3591                    break;
3592                case com.android.internal.R.styleable.View_layoutDirection:
3593                    // Clear any layout direction flags (included resolved bits) already set
3594                    mPrivateFlags2 &=
3595                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3596                    // Set the layout direction flags depending on the value of the attribute
3597                    final int layoutDirection = a.getInt(attr, -1);
3598                    final int value = (layoutDirection != -1) ?
3599                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3600                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3601                    break;
3602                case com.android.internal.R.styleable.View_drawingCacheQuality:
3603                    final int cacheQuality = a.getInt(attr, 0);
3604                    if (cacheQuality != 0) {
3605                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3606                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3607                    }
3608                    break;
3609                case com.android.internal.R.styleable.View_contentDescription:
3610                    setContentDescription(a.getString(attr));
3611                    break;
3612                case com.android.internal.R.styleable.View_labelFor:
3613                    setLabelFor(a.getResourceId(attr, NO_ID));
3614                    break;
3615                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3616                    if (!a.getBoolean(attr, true)) {
3617                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3618                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3619                    }
3620                    break;
3621                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3622                    if (!a.getBoolean(attr, true)) {
3623                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3624                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3625                    }
3626                    break;
3627                case R.styleable.View_scrollbars:
3628                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3629                    if (scrollbars != SCROLLBARS_NONE) {
3630                        viewFlagValues |= scrollbars;
3631                        viewFlagMasks |= SCROLLBARS_MASK;
3632                        initializeScrollbars = true;
3633                    }
3634                    break;
3635                //noinspection deprecation
3636                case R.styleable.View_fadingEdge:
3637                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3638                        // Ignore the attribute starting with ICS
3639                        break;
3640                    }
3641                    // With builds < ICS, fall through and apply fading edges
3642                case R.styleable.View_requiresFadingEdge:
3643                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3644                    if (fadingEdge != FADING_EDGE_NONE) {
3645                        viewFlagValues |= fadingEdge;
3646                        viewFlagMasks |= FADING_EDGE_MASK;
3647                        initializeFadingEdge(a);
3648                    }
3649                    break;
3650                case R.styleable.View_scrollbarStyle:
3651                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3652                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3653                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3654                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3655                    }
3656                    break;
3657                case R.styleable.View_isScrollContainer:
3658                    setScrollContainer = true;
3659                    if (a.getBoolean(attr, false)) {
3660                        setScrollContainer(true);
3661                    }
3662                    break;
3663                case com.android.internal.R.styleable.View_keepScreenOn:
3664                    if (a.getBoolean(attr, false)) {
3665                        viewFlagValues |= KEEP_SCREEN_ON;
3666                        viewFlagMasks |= KEEP_SCREEN_ON;
3667                    }
3668                    break;
3669                case R.styleable.View_filterTouchesWhenObscured:
3670                    if (a.getBoolean(attr, false)) {
3671                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3672                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3673                    }
3674                    break;
3675                case R.styleable.View_nextFocusLeft:
3676                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3677                    break;
3678                case R.styleable.View_nextFocusRight:
3679                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3680                    break;
3681                case R.styleable.View_nextFocusUp:
3682                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3683                    break;
3684                case R.styleable.View_nextFocusDown:
3685                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3686                    break;
3687                case R.styleable.View_nextFocusForward:
3688                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3689                    break;
3690                case R.styleable.View_minWidth:
3691                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3692                    break;
3693                case R.styleable.View_minHeight:
3694                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3695                    break;
3696                case R.styleable.View_onClick:
3697                    if (context.isRestricted()) {
3698                        throw new IllegalStateException("The android:onClick attribute cannot "
3699                                + "be used within a restricted context");
3700                    }
3701
3702                    final String handlerName = a.getString(attr);
3703                    if (handlerName != null) {
3704                        setOnClickListener(new OnClickListener() {
3705                            private Method mHandler;
3706
3707                            public void onClick(View v) {
3708                                if (mHandler == null) {
3709                                    try {
3710                                        mHandler = getContext().getClass().getMethod(handlerName,
3711                                                View.class);
3712                                    } catch (NoSuchMethodException e) {
3713                                        int id = getId();
3714                                        String idText = id == NO_ID ? "" : " with id '"
3715                                                + getContext().getResources().getResourceEntryName(
3716                                                    id) + "'";
3717                                        throw new IllegalStateException("Could not find a method " +
3718                                                handlerName + "(View) in the activity "
3719                                                + getContext().getClass() + " for onClick handler"
3720                                                + " on view " + View.this.getClass() + idText, e);
3721                                    }
3722                                }
3723
3724                                try {
3725                                    mHandler.invoke(getContext(), View.this);
3726                                } catch (IllegalAccessException e) {
3727                                    throw new IllegalStateException("Could not execute non "
3728                                            + "public method of the activity", e);
3729                                } catch (InvocationTargetException e) {
3730                                    throw new IllegalStateException("Could not execute "
3731                                            + "method of the activity", e);
3732                                }
3733                            }
3734                        });
3735                    }
3736                    break;
3737                case R.styleable.View_overScrollMode:
3738                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3739                    break;
3740                case R.styleable.View_verticalScrollbarPosition:
3741                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3742                    break;
3743                case R.styleable.View_layerType:
3744                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3745                    break;
3746                case R.styleable.View_textDirection:
3747                    // Clear any text direction flag already set
3748                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3749                    // Set the text direction flags depending on the value of the attribute
3750                    final int textDirection = a.getInt(attr, -1);
3751                    if (textDirection != -1) {
3752                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3753                    }
3754                    break;
3755                case R.styleable.View_textAlignment:
3756                    // Clear any text alignment flag already set
3757                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3758                    // Set the text alignment flag depending on the value of the attribute
3759                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3760                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3761                    break;
3762                case R.styleable.View_importantForAccessibility:
3763                    setImportantForAccessibility(a.getInt(attr,
3764                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3765                    break;
3766            }
3767        }
3768
3769        setOverScrollMode(overScrollMode);
3770
3771        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3772        // the resolved layout direction). Those cached values will be used later during padding
3773        // resolution.
3774        mUserPaddingStart = startPadding;
3775        mUserPaddingEnd = endPadding;
3776
3777        if (background != null) {
3778            setBackground(background);
3779        }
3780
3781        if (padding >= 0) {
3782            leftPadding = padding;
3783            topPadding = padding;
3784            rightPadding = padding;
3785            bottomPadding = padding;
3786            mUserPaddingLeftInitial = padding;
3787            mUserPaddingRightInitial = padding;
3788        }
3789
3790        if (isRtlCompatibilityMode()) {
3791            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3792            // left / right padding are used if defined (meaning here nothing to do). If they are not
3793            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3794            // start / end and resolve them as left / right (layout direction is not taken into account).
3795            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3796            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3797            // defined.
3798            if (!leftPaddingDefined && startPaddingDefined) {
3799                leftPadding = startPadding;
3800            }
3801            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3802            if (!rightPaddingDefined && endPaddingDefined) {
3803                rightPadding = endPadding;
3804            }
3805            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3806        } else {
3807            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3808            // values defined. Otherwise, left /right values are used.
3809            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3810            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3811            // defined.
3812            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3813
3814            if (leftPaddingDefined && !hasRelativePadding) {
3815                mUserPaddingLeftInitial = leftPadding;
3816            }
3817            if (rightPaddingDefined && !hasRelativePadding) {
3818                mUserPaddingRightInitial = rightPadding;
3819            }
3820        }
3821
3822        internalSetPadding(
3823                mUserPaddingLeftInitial,
3824                topPadding >= 0 ? topPadding : mPaddingTop,
3825                mUserPaddingRightInitial,
3826                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3827
3828        if (viewFlagMasks != 0) {
3829            setFlags(viewFlagValues, viewFlagMasks);
3830        }
3831
3832        if (initializeScrollbars) {
3833            initializeScrollbars(a);
3834        }
3835
3836        a.recycle();
3837
3838        // Needs to be called after mViewFlags is set
3839        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3840            recomputePadding();
3841        }
3842
3843        if (x != 0 || y != 0) {
3844            scrollTo(x, y);
3845        }
3846
3847        if (transformSet) {
3848            setTranslationX(tx);
3849            setTranslationY(ty);
3850            setRotation(rotation);
3851            setRotationX(rotationX);
3852            setRotationY(rotationY);
3853            setScaleX(sx);
3854            setScaleY(sy);
3855        }
3856
3857        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3858            setScrollContainer(true);
3859        }
3860
3861        computeOpaqueFlags();
3862    }
3863
3864    /**
3865     * Non-public constructor for use in testing
3866     */
3867    View() {
3868        mResources = null;
3869    }
3870
3871    public String toString() {
3872        StringBuilder out = new StringBuilder(128);
3873        out.append(getClass().getName());
3874        out.append('{');
3875        out.append(Integer.toHexString(System.identityHashCode(this)));
3876        out.append(' ');
3877        switch (mViewFlags&VISIBILITY_MASK) {
3878            case VISIBLE: out.append('V'); break;
3879            case INVISIBLE: out.append('I'); break;
3880            case GONE: out.append('G'); break;
3881            default: out.append('.'); break;
3882        }
3883        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3884        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3885        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3886        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3887        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3888        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3889        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3890        out.append(' ');
3891        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3892        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3893        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3894        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3895            out.append('p');
3896        } else {
3897            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3898        }
3899        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3900        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3901        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3902        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3903        out.append(' ');
3904        out.append(mLeft);
3905        out.append(',');
3906        out.append(mTop);
3907        out.append('-');
3908        out.append(mRight);
3909        out.append(',');
3910        out.append(mBottom);
3911        final int id = getId();
3912        if (id != NO_ID) {
3913            out.append(" #");
3914            out.append(Integer.toHexString(id));
3915            final Resources r = mResources;
3916            if (id != 0 && r != null) {
3917                try {
3918                    String pkgname;
3919                    switch (id&0xff000000) {
3920                        case 0x7f000000:
3921                            pkgname="app";
3922                            break;
3923                        case 0x01000000:
3924                            pkgname="android";
3925                            break;
3926                        default:
3927                            pkgname = r.getResourcePackageName(id);
3928                            break;
3929                    }
3930                    String typename = r.getResourceTypeName(id);
3931                    String entryname = r.getResourceEntryName(id);
3932                    out.append(" ");
3933                    out.append(pkgname);
3934                    out.append(":");
3935                    out.append(typename);
3936                    out.append("/");
3937                    out.append(entryname);
3938                } catch (Resources.NotFoundException e) {
3939                }
3940            }
3941        }
3942        out.append("}");
3943        return out.toString();
3944    }
3945
3946    /**
3947     * <p>
3948     * Initializes the fading edges from a given set of styled attributes. This
3949     * method should be called by subclasses that need fading edges and when an
3950     * instance of these subclasses is created programmatically rather than
3951     * being inflated from XML. This method is automatically called when the XML
3952     * is inflated.
3953     * </p>
3954     *
3955     * @param a the styled attributes set to initialize the fading edges from
3956     */
3957    protected void initializeFadingEdge(TypedArray a) {
3958        initScrollCache();
3959
3960        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3961                R.styleable.View_fadingEdgeLength,
3962                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3963    }
3964
3965    /**
3966     * Returns the size of the vertical faded edges used to indicate that more
3967     * content in this view is visible.
3968     *
3969     * @return The size in pixels of the vertical faded edge or 0 if vertical
3970     *         faded edges are not enabled for this view.
3971     * @attr ref android.R.styleable#View_fadingEdgeLength
3972     */
3973    public int getVerticalFadingEdgeLength() {
3974        if (isVerticalFadingEdgeEnabled()) {
3975            ScrollabilityCache cache = mScrollCache;
3976            if (cache != null) {
3977                return cache.fadingEdgeLength;
3978            }
3979        }
3980        return 0;
3981    }
3982
3983    /**
3984     * Set the size of the faded edge used to indicate that more content in this
3985     * view is available.  Will not change whether the fading edge is enabled; use
3986     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3987     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3988     * for the vertical or horizontal fading edges.
3989     *
3990     * @param length The size in pixels of the faded edge used to indicate that more
3991     *        content in this view is visible.
3992     */
3993    public void setFadingEdgeLength(int length) {
3994        initScrollCache();
3995        mScrollCache.fadingEdgeLength = length;
3996    }
3997
3998    /**
3999     * Returns the size of the horizontal faded edges used to indicate that more
4000     * content in this view is visible.
4001     *
4002     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4003     *         faded edges are not enabled for this view.
4004     * @attr ref android.R.styleable#View_fadingEdgeLength
4005     */
4006    public int getHorizontalFadingEdgeLength() {
4007        if (isHorizontalFadingEdgeEnabled()) {
4008            ScrollabilityCache cache = mScrollCache;
4009            if (cache != null) {
4010                return cache.fadingEdgeLength;
4011            }
4012        }
4013        return 0;
4014    }
4015
4016    /**
4017     * Returns the width of the vertical scrollbar.
4018     *
4019     * @return The width in pixels of the vertical scrollbar or 0 if there
4020     *         is no vertical scrollbar.
4021     */
4022    public int getVerticalScrollbarWidth() {
4023        ScrollabilityCache cache = mScrollCache;
4024        if (cache != null) {
4025            ScrollBarDrawable scrollBar = cache.scrollBar;
4026            if (scrollBar != null) {
4027                int size = scrollBar.getSize(true);
4028                if (size <= 0) {
4029                    size = cache.scrollBarSize;
4030                }
4031                return size;
4032            }
4033            return 0;
4034        }
4035        return 0;
4036    }
4037
4038    /**
4039     * Returns the height of the horizontal scrollbar.
4040     *
4041     * @return The height in pixels of the horizontal scrollbar or 0 if
4042     *         there is no horizontal scrollbar.
4043     */
4044    protected int getHorizontalScrollbarHeight() {
4045        ScrollabilityCache cache = mScrollCache;
4046        if (cache != null) {
4047            ScrollBarDrawable scrollBar = cache.scrollBar;
4048            if (scrollBar != null) {
4049                int size = scrollBar.getSize(false);
4050                if (size <= 0) {
4051                    size = cache.scrollBarSize;
4052                }
4053                return size;
4054            }
4055            return 0;
4056        }
4057        return 0;
4058    }
4059
4060    /**
4061     * <p>
4062     * Initializes the scrollbars from a given set of styled attributes. This
4063     * method should be called by subclasses that need scrollbars and when an
4064     * instance of these subclasses is created programmatically rather than
4065     * being inflated from XML. This method is automatically called when the XML
4066     * is inflated.
4067     * </p>
4068     *
4069     * @param a the styled attributes set to initialize the scrollbars from
4070     */
4071    protected void initializeScrollbars(TypedArray a) {
4072        initScrollCache();
4073
4074        final ScrollabilityCache scrollabilityCache = mScrollCache;
4075
4076        if (scrollabilityCache.scrollBar == null) {
4077            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4078        }
4079
4080        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4081
4082        if (!fadeScrollbars) {
4083            scrollabilityCache.state = ScrollabilityCache.ON;
4084        }
4085        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4086
4087
4088        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4089                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4090                        .getScrollBarFadeDuration());
4091        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4092                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4093                ViewConfiguration.getScrollDefaultDelay());
4094
4095
4096        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4097                com.android.internal.R.styleable.View_scrollbarSize,
4098                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4099
4100        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4101        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4102
4103        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4104        if (thumb != null) {
4105            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4106        }
4107
4108        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4109                false);
4110        if (alwaysDraw) {
4111            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4112        }
4113
4114        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4115        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4116
4117        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4118        if (thumb != null) {
4119            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4120        }
4121
4122        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4123                false);
4124        if (alwaysDraw) {
4125            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4126        }
4127
4128        // Apply layout direction to the new Drawables if needed
4129        final int layoutDirection = getLayoutDirection();
4130        if (track != null) {
4131            track.setLayoutDirection(layoutDirection);
4132        }
4133        if (thumb != null) {
4134            thumb.setLayoutDirection(layoutDirection);
4135        }
4136
4137        // Re-apply user/background padding so that scrollbar(s) get added
4138        resolvePadding();
4139    }
4140
4141    /**
4142     * <p>
4143     * Initalizes the scrollability cache if necessary.
4144     * </p>
4145     */
4146    private void initScrollCache() {
4147        if (mScrollCache == null) {
4148            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4149        }
4150    }
4151
4152    private ScrollabilityCache getScrollCache() {
4153        initScrollCache();
4154        return mScrollCache;
4155    }
4156
4157    /**
4158     * Set the position of the vertical scroll bar. Should be one of
4159     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4160     * {@link #SCROLLBAR_POSITION_RIGHT}.
4161     *
4162     * @param position Where the vertical scroll bar should be positioned.
4163     */
4164    public void setVerticalScrollbarPosition(int position) {
4165        if (mVerticalScrollbarPosition != position) {
4166            mVerticalScrollbarPosition = position;
4167            computeOpaqueFlags();
4168            resolvePadding();
4169        }
4170    }
4171
4172    /**
4173     * @return The position where the vertical scroll bar will show, if applicable.
4174     * @see #setVerticalScrollbarPosition(int)
4175     */
4176    public int getVerticalScrollbarPosition() {
4177        return mVerticalScrollbarPosition;
4178    }
4179
4180    ListenerInfo getListenerInfo() {
4181        if (mListenerInfo != null) {
4182            return mListenerInfo;
4183        }
4184        mListenerInfo = new ListenerInfo();
4185        return mListenerInfo;
4186    }
4187
4188    /**
4189     * Register a callback to be invoked when focus of this view changed.
4190     *
4191     * @param l The callback that will run.
4192     */
4193    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4194        getListenerInfo().mOnFocusChangeListener = l;
4195    }
4196
4197    /**
4198     * Add a listener that will be called when the bounds of the view change due to
4199     * layout processing.
4200     *
4201     * @param listener The listener that will be called when layout bounds change.
4202     */
4203    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4204        ListenerInfo li = getListenerInfo();
4205        if (li.mOnLayoutChangeListeners == null) {
4206            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4207        }
4208        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4209            li.mOnLayoutChangeListeners.add(listener);
4210        }
4211    }
4212
4213    /**
4214     * Remove a listener for layout changes.
4215     *
4216     * @param listener The listener for layout bounds change.
4217     */
4218    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4219        ListenerInfo li = mListenerInfo;
4220        if (li == null || li.mOnLayoutChangeListeners == null) {
4221            return;
4222        }
4223        li.mOnLayoutChangeListeners.remove(listener);
4224    }
4225
4226    /**
4227     * Add a listener for attach state changes.
4228     *
4229     * This listener will be called whenever this view is attached or detached
4230     * from a window. Remove the listener using
4231     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4232     *
4233     * @param listener Listener to attach
4234     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4235     */
4236    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4237        ListenerInfo li = getListenerInfo();
4238        if (li.mOnAttachStateChangeListeners == null) {
4239            li.mOnAttachStateChangeListeners
4240                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4241        }
4242        li.mOnAttachStateChangeListeners.add(listener);
4243    }
4244
4245    /**
4246     * Remove a listener for attach state changes. The listener will receive no further
4247     * notification of window attach/detach events.
4248     *
4249     * @param listener Listener to remove
4250     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4251     */
4252    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4253        ListenerInfo li = mListenerInfo;
4254        if (li == null || li.mOnAttachStateChangeListeners == null) {
4255            return;
4256        }
4257        li.mOnAttachStateChangeListeners.remove(listener);
4258    }
4259
4260    /**
4261     * Returns the focus-change callback registered for this view.
4262     *
4263     * @return The callback, or null if one is not registered.
4264     */
4265    public OnFocusChangeListener getOnFocusChangeListener() {
4266        ListenerInfo li = mListenerInfo;
4267        return li != null ? li.mOnFocusChangeListener : null;
4268    }
4269
4270    /**
4271     * Register a callback to be invoked when this view is clicked. If this view is not
4272     * clickable, it becomes clickable.
4273     *
4274     * @param l The callback that will run
4275     *
4276     * @see #setClickable(boolean)
4277     */
4278    public void setOnClickListener(OnClickListener l) {
4279        if (!isClickable()) {
4280            setClickable(true);
4281        }
4282        getListenerInfo().mOnClickListener = l;
4283    }
4284
4285    /**
4286     * Return whether this view has an attached OnClickListener.  Returns
4287     * true if there is a listener, false if there is none.
4288     */
4289    public boolean hasOnClickListeners() {
4290        ListenerInfo li = mListenerInfo;
4291        return (li != null && li.mOnClickListener != null);
4292    }
4293
4294    /**
4295     * Register a callback to be invoked when this view is clicked and held. If this view is not
4296     * long clickable, it becomes long clickable.
4297     *
4298     * @param l The callback that will run
4299     *
4300     * @see #setLongClickable(boolean)
4301     */
4302    public void setOnLongClickListener(OnLongClickListener l) {
4303        if (!isLongClickable()) {
4304            setLongClickable(true);
4305        }
4306        getListenerInfo().mOnLongClickListener = l;
4307    }
4308
4309    /**
4310     * Register a callback to be invoked when the context menu for this view is
4311     * being built. If this view is not long clickable, it becomes long clickable.
4312     *
4313     * @param l The callback that will run
4314     *
4315     */
4316    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4317        if (!isLongClickable()) {
4318            setLongClickable(true);
4319        }
4320        getListenerInfo().mOnCreateContextMenuListener = l;
4321    }
4322
4323    /**
4324     * Call this view's OnClickListener, if it is defined.  Performs all normal
4325     * actions associated with clicking: reporting accessibility event, playing
4326     * a sound, etc.
4327     *
4328     * @return True there was an assigned OnClickListener that was called, false
4329     *         otherwise is returned.
4330     */
4331    public boolean performClick() {
4332        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4333
4334        ListenerInfo li = mListenerInfo;
4335        if (li != null && li.mOnClickListener != null) {
4336            playSoundEffect(SoundEffectConstants.CLICK);
4337            li.mOnClickListener.onClick(this);
4338            return true;
4339        }
4340
4341        return false;
4342    }
4343
4344    /**
4345     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4346     * this only calls the listener, and does not do any associated clicking
4347     * actions like reporting an accessibility event.
4348     *
4349     * @return True there was an assigned OnClickListener that was called, false
4350     *         otherwise is returned.
4351     */
4352    public boolean callOnClick() {
4353        ListenerInfo li = mListenerInfo;
4354        if (li != null && li.mOnClickListener != null) {
4355            li.mOnClickListener.onClick(this);
4356            return true;
4357        }
4358        return false;
4359    }
4360
4361    /**
4362     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4363     * OnLongClickListener did not consume the event.
4364     *
4365     * @return True if one of the above receivers consumed the event, false otherwise.
4366     */
4367    public boolean performLongClick() {
4368        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4369
4370        boolean handled = false;
4371        ListenerInfo li = mListenerInfo;
4372        if (li != null && li.mOnLongClickListener != null) {
4373            handled = li.mOnLongClickListener.onLongClick(View.this);
4374        }
4375        if (!handled) {
4376            handled = showContextMenu();
4377        }
4378        if (handled) {
4379            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4380        }
4381        return handled;
4382    }
4383
4384    /**
4385     * Performs button-related actions during a touch down event.
4386     *
4387     * @param event The event.
4388     * @return True if the down was consumed.
4389     *
4390     * @hide
4391     */
4392    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4393        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4394            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4395                return true;
4396            }
4397        }
4398        return false;
4399    }
4400
4401    /**
4402     * Bring up the context menu for this view.
4403     *
4404     * @return Whether a context menu was displayed.
4405     */
4406    public boolean showContextMenu() {
4407        return getParent().showContextMenuForChild(this);
4408    }
4409
4410    /**
4411     * Bring up the context menu for this view, referring to the item under the specified point.
4412     *
4413     * @param x The referenced x coordinate.
4414     * @param y The referenced y coordinate.
4415     * @param metaState The keyboard modifiers that were pressed.
4416     * @return Whether a context menu was displayed.
4417     *
4418     * @hide
4419     */
4420    public boolean showContextMenu(float x, float y, int metaState) {
4421        return showContextMenu();
4422    }
4423
4424    /**
4425     * Start an action mode.
4426     *
4427     * @param callback Callback that will control the lifecycle of the action mode
4428     * @return The new action mode if it is started, null otherwise
4429     *
4430     * @see ActionMode
4431     */
4432    public ActionMode startActionMode(ActionMode.Callback callback) {
4433        ViewParent parent = getParent();
4434        if (parent == null) return null;
4435        return parent.startActionModeForChild(this, callback);
4436    }
4437
4438    /**
4439     * Register a callback to be invoked when a hardware key is pressed in this view.
4440     * Key presses in software input methods will generally not trigger the methods of
4441     * this listener.
4442     * @param l the key listener to attach to this view
4443     */
4444    public void setOnKeyListener(OnKeyListener l) {
4445        getListenerInfo().mOnKeyListener = l;
4446    }
4447
4448    /**
4449     * Register a callback to be invoked when a touch event is sent to this view.
4450     * @param l the touch listener to attach to this view
4451     */
4452    public void setOnTouchListener(OnTouchListener l) {
4453        getListenerInfo().mOnTouchListener = l;
4454    }
4455
4456    /**
4457     * Register a callback to be invoked when a generic motion event is sent to this view.
4458     * @param l the generic motion listener to attach to this view
4459     */
4460    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4461        getListenerInfo().mOnGenericMotionListener = l;
4462    }
4463
4464    /**
4465     * Register a callback to be invoked when a hover event is sent to this view.
4466     * @param l the hover listener to attach to this view
4467     */
4468    public void setOnHoverListener(OnHoverListener l) {
4469        getListenerInfo().mOnHoverListener = l;
4470    }
4471
4472    /**
4473     * Register a drag event listener callback object for this View. The parameter is
4474     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4475     * View, the system calls the
4476     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4477     * @param l An implementation of {@link android.view.View.OnDragListener}.
4478     */
4479    public void setOnDragListener(OnDragListener l) {
4480        getListenerInfo().mOnDragListener = l;
4481    }
4482
4483    /**
4484     * Give this view focus. This will cause
4485     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4486     *
4487     * Note: this does not check whether this {@link View} should get focus, it just
4488     * gives it focus no matter what.  It should only be called internally by framework
4489     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4490     *
4491     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4492     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4493     *        focus moved when requestFocus() is called. It may not always
4494     *        apply, in which case use the default View.FOCUS_DOWN.
4495     * @param previouslyFocusedRect The rectangle of the view that had focus
4496     *        prior in this View's coordinate system.
4497     */
4498    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4499        if (DBG) {
4500            System.out.println(this + " requestFocus()");
4501        }
4502
4503        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4504            mPrivateFlags |= PFLAG_FOCUSED;
4505
4506            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4507
4508            if (mParent != null) {
4509                mParent.requestChildFocus(this, this);
4510            }
4511
4512            if (mAttachInfo != null) {
4513                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4514            }
4515
4516            onFocusChanged(true, direction, previouslyFocusedRect);
4517            refreshDrawableState();
4518        }
4519    }
4520
4521    /**
4522     * Request that a rectangle of this view be visible on the screen,
4523     * scrolling if necessary just enough.
4524     *
4525     * <p>A View should call this if it maintains some notion of which part
4526     * of its content is interesting.  For example, a text editing view
4527     * should call this when its cursor moves.
4528     *
4529     * @param rectangle The rectangle.
4530     * @return Whether any parent scrolled.
4531     */
4532    public boolean requestRectangleOnScreen(Rect rectangle) {
4533        return requestRectangleOnScreen(rectangle, false);
4534    }
4535
4536    /**
4537     * Request that a rectangle of this view be visible on the screen,
4538     * scrolling if necessary just enough.
4539     *
4540     * <p>A View should call this if it maintains some notion of which part
4541     * of its content is interesting.  For example, a text editing view
4542     * should call this when its cursor moves.
4543     *
4544     * <p>When <code>immediate</code> is set to true, scrolling will not be
4545     * animated.
4546     *
4547     * @param rectangle The rectangle.
4548     * @param immediate True to forbid animated scrolling, false otherwise
4549     * @return Whether any parent scrolled.
4550     */
4551    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4552        if (mParent == null) {
4553            return false;
4554        }
4555
4556        View child = this;
4557
4558        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4559        position.set(rectangle);
4560
4561        ViewParent parent = mParent;
4562        boolean scrolled = false;
4563        while (parent != null) {
4564            rectangle.set((int) position.left, (int) position.top,
4565                    (int) position.right, (int) position.bottom);
4566
4567            scrolled |= parent.requestChildRectangleOnScreen(child,
4568                    rectangle, immediate);
4569
4570            if (!child.hasIdentityMatrix()) {
4571                child.getMatrix().mapRect(position);
4572            }
4573
4574            position.offset(child.mLeft, child.mTop);
4575
4576            if (!(parent instanceof View)) {
4577                break;
4578            }
4579
4580            View parentView = (View) parent;
4581
4582            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4583
4584            child = parentView;
4585            parent = child.getParent();
4586        }
4587
4588        return scrolled;
4589    }
4590
4591    /**
4592     * Called when this view wants to give up focus. If focus is cleared
4593     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4594     * <p>
4595     * <strong>Note:</strong> When a View clears focus the framework is trying
4596     * to give focus to the first focusable View from the top. Hence, if this
4597     * View is the first from the top that can take focus, then all callbacks
4598     * related to clearing focus will be invoked after wich the framework will
4599     * give focus to this view.
4600     * </p>
4601     */
4602    public void clearFocus() {
4603        if (DBG) {
4604            System.out.println(this + " clearFocus()");
4605        }
4606
4607        clearFocusInternal(true, true);
4608    }
4609
4610    /**
4611     * Clears focus from the view, optionally propagating the change up through
4612     * the parent hierarchy and requesting that the root view place new focus.
4613     *
4614     * @param propagate whether to propagate the change up through the parent
4615     *            hierarchy
4616     * @param refocus when propagate is true, specifies whether to request the
4617     *            root view place new focus
4618     */
4619    void clearFocusInternal(boolean propagate, boolean refocus) {
4620        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4621            mPrivateFlags &= ~PFLAG_FOCUSED;
4622
4623            if (propagate && mParent != null) {
4624                mParent.clearChildFocus(this);
4625            }
4626
4627            onFocusChanged(false, 0, null);
4628
4629            refreshDrawableState();
4630
4631            if (propagate && (!refocus || !rootViewRequestFocus())) {
4632                notifyGlobalFocusCleared(this);
4633            }
4634        }
4635    }
4636
4637    void notifyGlobalFocusCleared(View oldFocus) {
4638        if (oldFocus != null && mAttachInfo != null) {
4639            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4640        }
4641    }
4642
4643    boolean rootViewRequestFocus() {
4644        final View root = getRootView();
4645        return root != null && root.requestFocus();
4646    }
4647
4648    /**
4649     * Called internally by the view system when a new view is getting focus.
4650     * This is what clears the old focus.
4651     * <p>
4652     * <b>NOTE:</b> The parent view's focused child must be updated manually
4653     * after calling this method. Otherwise, the view hierarchy may be left in
4654     * an inconstent state.
4655     */
4656    void unFocus() {
4657        if (DBG) {
4658            System.out.println(this + " unFocus()");
4659        }
4660
4661        clearFocusInternal(false, false);
4662    }
4663
4664    /**
4665     * Returns true if this view has focus iteself, or is the ancestor of the
4666     * view that has focus.
4667     *
4668     * @return True if this view has or contains focus, false otherwise.
4669     */
4670    @ViewDebug.ExportedProperty(category = "focus")
4671    public boolean hasFocus() {
4672        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4673    }
4674
4675    /**
4676     * Returns true if this view is focusable or if it contains a reachable View
4677     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4678     * is a View whose parents do not block descendants focus.
4679     *
4680     * Only {@link #VISIBLE} views are considered focusable.
4681     *
4682     * @return True if the view is focusable or if the view contains a focusable
4683     *         View, false otherwise.
4684     *
4685     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4686     */
4687    public boolean hasFocusable() {
4688        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4689    }
4690
4691    /**
4692     * Called by the view system when the focus state of this view changes.
4693     * When the focus change event is caused by directional navigation, direction
4694     * and previouslyFocusedRect provide insight into where the focus is coming from.
4695     * When overriding, be sure to call up through to the super class so that
4696     * the standard focus handling will occur.
4697     *
4698     * @param gainFocus True if the View has focus; false otherwise.
4699     * @param direction The direction focus has moved when requestFocus()
4700     *                  is called to give this view focus. Values are
4701     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4702     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4703     *                  It may not always apply, in which case use the default.
4704     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4705     *        system, of the previously focused view.  If applicable, this will be
4706     *        passed in as finer grained information about where the focus is coming
4707     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4708     */
4709    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4710        if (gainFocus) {
4711            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4712        } else {
4713            notifyViewAccessibilityStateChangedIfNeeded();
4714        }
4715
4716        InputMethodManager imm = InputMethodManager.peekInstance();
4717        if (!gainFocus) {
4718            if (isPressed()) {
4719                setPressed(false);
4720            }
4721            if (imm != null && mAttachInfo != null
4722                    && mAttachInfo.mHasWindowFocus) {
4723                imm.focusOut(this);
4724            }
4725            onFocusLost();
4726        } else if (imm != null && mAttachInfo != null
4727                && mAttachInfo.mHasWindowFocus) {
4728            imm.focusIn(this);
4729        }
4730
4731        invalidate(true);
4732        ListenerInfo li = mListenerInfo;
4733        if (li != null && li.mOnFocusChangeListener != null) {
4734            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4735        }
4736
4737        if (mAttachInfo != null) {
4738            mAttachInfo.mKeyDispatchState.reset(this);
4739        }
4740    }
4741
4742    /**
4743     * Sends an accessibility event of the given type. If accessibility is
4744     * not enabled this method has no effect. The default implementation calls
4745     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4746     * to populate information about the event source (this View), then calls
4747     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4748     * populate the text content of the event source including its descendants,
4749     * and last calls
4750     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4751     * on its parent to resuest sending of the event to interested parties.
4752     * <p>
4753     * If an {@link AccessibilityDelegate} has been specified via calling
4754     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4755     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4756     * responsible for handling this call.
4757     * </p>
4758     *
4759     * @param eventType The type of the event to send, as defined by several types from
4760     * {@link android.view.accessibility.AccessibilityEvent}, such as
4761     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4762     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4763     *
4764     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4765     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4766     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4767     * @see AccessibilityDelegate
4768     */
4769    public void sendAccessibilityEvent(int eventType) {
4770        // Excluded views do not send accessibility events.
4771        if (!includeForAccessibility()) {
4772            return;
4773        }
4774        if (mAccessibilityDelegate != null) {
4775            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4776        } else {
4777            sendAccessibilityEventInternal(eventType);
4778        }
4779    }
4780
4781    /**
4782     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4783     * {@link AccessibilityEvent} to make an announcement which is related to some
4784     * sort of a context change for which none of the events representing UI transitions
4785     * is a good fit. For example, announcing a new page in a book. If accessibility
4786     * is not enabled this method does nothing.
4787     *
4788     * @param text The announcement text.
4789     */
4790    public void announceForAccessibility(CharSequence text) {
4791        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4792            AccessibilityEvent event = AccessibilityEvent.obtain(
4793                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4794            onInitializeAccessibilityEvent(event);
4795            event.getText().add(text);
4796            event.setContentDescription(null);
4797            mParent.requestSendAccessibilityEvent(this, event);
4798        }
4799    }
4800
4801    /**
4802     * @see #sendAccessibilityEvent(int)
4803     *
4804     * Note: Called from the default {@link AccessibilityDelegate}.
4805     */
4806    void sendAccessibilityEventInternal(int eventType) {
4807        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4808            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4809        }
4810    }
4811
4812    /**
4813     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4814     * takes as an argument an empty {@link AccessibilityEvent} and does not
4815     * perform a check whether accessibility is enabled.
4816     * <p>
4817     * If an {@link AccessibilityDelegate} has been specified via calling
4818     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4819     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4820     * is responsible for handling this call.
4821     * </p>
4822     *
4823     * @param event The event to send.
4824     *
4825     * @see #sendAccessibilityEvent(int)
4826     */
4827    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4828        if (mAccessibilityDelegate != null) {
4829            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4830        } else {
4831            sendAccessibilityEventUncheckedInternal(event);
4832        }
4833    }
4834
4835    /**
4836     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4837     *
4838     * Note: Called from the default {@link AccessibilityDelegate}.
4839     */
4840    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4841        if (!isShown()) {
4842            return;
4843        }
4844        onInitializeAccessibilityEvent(event);
4845        // Only a subset of accessibility events populates text content.
4846        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4847            dispatchPopulateAccessibilityEvent(event);
4848        }
4849        // In the beginning we called #isShown(), so we know that getParent() is not null.
4850        getParent().requestSendAccessibilityEvent(this, event);
4851    }
4852
4853    /**
4854     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4855     * to its children for adding their text content to the event. Note that the
4856     * event text is populated in a separate dispatch path since we add to the
4857     * event not only the text of the source but also the text of all its descendants.
4858     * A typical implementation will call
4859     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4860     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4861     * on each child. Override this method if custom population of the event text
4862     * content is required.
4863     * <p>
4864     * If an {@link AccessibilityDelegate} has been specified via calling
4865     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4866     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4867     * is responsible for handling this call.
4868     * </p>
4869     * <p>
4870     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4871     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4872     * </p>
4873     *
4874     * @param event The event.
4875     *
4876     * @return True if the event population was completed.
4877     */
4878    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4879        if (mAccessibilityDelegate != null) {
4880            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4881        } else {
4882            return dispatchPopulateAccessibilityEventInternal(event);
4883        }
4884    }
4885
4886    /**
4887     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4888     *
4889     * Note: Called from the default {@link AccessibilityDelegate}.
4890     */
4891    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4892        onPopulateAccessibilityEvent(event);
4893        return false;
4894    }
4895
4896    /**
4897     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4898     * giving a chance to this View to populate the accessibility event with its
4899     * text content. While this method is free to modify event
4900     * attributes other than text content, doing so should normally be performed in
4901     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4902     * <p>
4903     * Example: Adding formatted date string to an accessibility event in addition
4904     *          to the text added by the super implementation:
4905     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4906     *     super.onPopulateAccessibilityEvent(event);
4907     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4908     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4909     *         mCurrentDate.getTimeInMillis(), flags);
4910     *     event.getText().add(selectedDateUtterance);
4911     * }</pre>
4912     * <p>
4913     * If an {@link AccessibilityDelegate} has been specified via calling
4914     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4915     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4916     * is responsible for handling this call.
4917     * </p>
4918     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4919     * information to the event, in case the default implementation has basic information to add.
4920     * </p>
4921     *
4922     * @param event The accessibility event which to populate.
4923     *
4924     * @see #sendAccessibilityEvent(int)
4925     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4926     */
4927    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4928        if (mAccessibilityDelegate != null) {
4929            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4930        } else {
4931            onPopulateAccessibilityEventInternal(event);
4932        }
4933    }
4934
4935    /**
4936     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4937     *
4938     * Note: Called from the default {@link AccessibilityDelegate}.
4939     */
4940    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4941    }
4942
4943    /**
4944     * Initializes an {@link AccessibilityEvent} with information about
4945     * this View which is the event source. In other words, the source of
4946     * an accessibility event is the view whose state change triggered firing
4947     * the event.
4948     * <p>
4949     * Example: Setting the password property of an event in addition
4950     *          to properties set by the super implementation:
4951     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4952     *     super.onInitializeAccessibilityEvent(event);
4953     *     event.setPassword(true);
4954     * }</pre>
4955     * <p>
4956     * If an {@link AccessibilityDelegate} has been specified via calling
4957     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4958     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4959     * is responsible for handling this call.
4960     * </p>
4961     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4962     * information to the event, in case the default implementation has basic information to add.
4963     * </p>
4964     * @param event The event to initialize.
4965     *
4966     * @see #sendAccessibilityEvent(int)
4967     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4968     */
4969    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4970        if (mAccessibilityDelegate != null) {
4971            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4972        } else {
4973            onInitializeAccessibilityEventInternal(event);
4974        }
4975    }
4976
4977    /**
4978     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4979     *
4980     * Note: Called from the default {@link AccessibilityDelegate}.
4981     */
4982    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4983        event.setSource(this);
4984        event.setClassName(View.class.getName());
4985        event.setPackageName(getContext().getPackageName());
4986        event.setEnabled(isEnabled());
4987        event.setContentDescription(mContentDescription);
4988
4989        switch (event.getEventType()) {
4990            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4991                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4992                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4993                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4994                event.setItemCount(focusablesTempList.size());
4995                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4996                if (mAttachInfo != null) {
4997                    focusablesTempList.clear();
4998                }
4999            } break;
5000            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5001                CharSequence text = getIterableTextForAccessibility();
5002                if (text != null && text.length() > 0) {
5003                    event.setFromIndex(getAccessibilitySelectionStart());
5004                    event.setToIndex(getAccessibilitySelectionEnd());
5005                    event.setItemCount(text.length());
5006                }
5007            } break;
5008        }
5009    }
5010
5011    /**
5012     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5013     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5014     * This method is responsible for obtaining an accessibility node info from a
5015     * pool of reusable instances and calling
5016     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5017     * initialize the former.
5018     * <p>
5019     * Note: The client is responsible for recycling the obtained instance by calling
5020     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5021     * </p>
5022     *
5023     * @return A populated {@link AccessibilityNodeInfo}.
5024     *
5025     * @see AccessibilityNodeInfo
5026     */
5027    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5028        if (mAccessibilityDelegate != null) {
5029            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5030        } else {
5031            return createAccessibilityNodeInfoInternal();
5032        }
5033    }
5034
5035    /**
5036     * @see #createAccessibilityNodeInfo()
5037     */
5038    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5039        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5040        if (provider != null) {
5041            return provider.createAccessibilityNodeInfo(View.NO_ID);
5042        } else {
5043            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5044            onInitializeAccessibilityNodeInfo(info);
5045            return info;
5046        }
5047    }
5048
5049    /**
5050     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5051     * The base implementation sets:
5052     * <ul>
5053     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5054     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5055     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5056     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5057     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5058     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5059     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5060     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5061     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5062     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5063     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5064     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5065     * </ul>
5066     * <p>
5067     * Subclasses should override this method, call the super implementation,
5068     * and set additional attributes.
5069     * </p>
5070     * <p>
5071     * If an {@link AccessibilityDelegate} has been specified via calling
5072     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5073     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5074     * is responsible for handling this call.
5075     * </p>
5076     *
5077     * @param info The instance to initialize.
5078     */
5079    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5080        if (mAccessibilityDelegate != null) {
5081            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5082        } else {
5083            onInitializeAccessibilityNodeInfoInternal(info);
5084        }
5085    }
5086
5087    /**
5088     * Gets the location of this view in screen coordintates.
5089     *
5090     * @param outRect The output location
5091     */
5092    void getBoundsOnScreen(Rect outRect) {
5093        if (mAttachInfo == null) {
5094            return;
5095        }
5096
5097        RectF position = mAttachInfo.mTmpTransformRect;
5098        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5099
5100        if (!hasIdentityMatrix()) {
5101            getMatrix().mapRect(position);
5102        }
5103
5104        position.offset(mLeft, mTop);
5105
5106        ViewParent parent = mParent;
5107        while (parent instanceof View) {
5108            View parentView = (View) parent;
5109
5110            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5111
5112            if (!parentView.hasIdentityMatrix()) {
5113                parentView.getMatrix().mapRect(position);
5114            }
5115
5116            position.offset(parentView.mLeft, parentView.mTop);
5117
5118            parent = parentView.mParent;
5119        }
5120
5121        if (parent instanceof ViewRootImpl) {
5122            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5123            position.offset(0, -viewRootImpl.mCurScrollY);
5124        }
5125
5126        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5127
5128        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5129                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5130    }
5131
5132    /**
5133     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5134     *
5135     * Note: Called from the default {@link AccessibilityDelegate}.
5136     */
5137    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5138        Rect bounds = mAttachInfo.mTmpInvalRect;
5139
5140        getDrawingRect(bounds);
5141        info.setBoundsInParent(bounds);
5142
5143        getBoundsOnScreen(bounds);
5144        info.setBoundsInScreen(bounds);
5145
5146        ViewParent parent = getParentForAccessibility();
5147        if (parent instanceof View) {
5148            info.setParent((View) parent);
5149        }
5150
5151        if (mID != View.NO_ID) {
5152            View rootView = getRootView();
5153            if (rootView == null) {
5154                rootView = this;
5155            }
5156            View label = rootView.findLabelForView(this, mID);
5157            if (label != null) {
5158                info.setLabeledBy(label);
5159            }
5160
5161            if ((mAttachInfo.mAccessibilityFetchFlags
5162                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5163                    && Resources.resourceHasPackage(mID)) {
5164                try {
5165                    String viewId = getResources().getResourceName(mID);
5166                    info.setViewIdResourceName(viewId);
5167                } catch (Resources.NotFoundException nfe) {
5168                    /* ignore */
5169                }
5170            }
5171        }
5172
5173        if (mLabelForId != View.NO_ID) {
5174            View rootView = getRootView();
5175            if (rootView == null) {
5176                rootView = this;
5177            }
5178            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5179            if (labeled != null) {
5180                info.setLabelFor(labeled);
5181            }
5182        }
5183
5184        info.setVisibleToUser(isVisibleToUser());
5185
5186        info.setPackageName(mContext.getPackageName());
5187        info.setClassName(View.class.getName());
5188        info.setContentDescription(getContentDescription());
5189
5190        info.setEnabled(isEnabled());
5191        info.setClickable(isClickable());
5192        info.setFocusable(isFocusable());
5193        info.setFocused(isFocused());
5194        info.setAccessibilityFocused(isAccessibilityFocused());
5195        info.setSelected(isSelected());
5196        info.setLongClickable(isLongClickable());
5197
5198        // TODO: These make sense only if we are in an AdapterView but all
5199        // views can be selected. Maybe from accessibility perspective
5200        // we should report as selectable view in an AdapterView.
5201        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5202        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5203
5204        if (isFocusable()) {
5205            if (isFocused()) {
5206                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5207            } else {
5208                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5209            }
5210        }
5211
5212        if (!isAccessibilityFocused()) {
5213            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5214        } else {
5215            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5216        }
5217
5218        if (isClickable() && isEnabled()) {
5219            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5220        }
5221
5222        if (isLongClickable() && isEnabled()) {
5223            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5224        }
5225
5226        CharSequence text = getIterableTextForAccessibility();
5227        if (text != null && text.length() > 0) {
5228            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5229
5230            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5231            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5232            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5233            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5234                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5235                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5236        }
5237    }
5238
5239    private View findLabelForView(View view, int labeledId) {
5240        if (mMatchLabelForPredicate == null) {
5241            mMatchLabelForPredicate = new MatchLabelForPredicate();
5242        }
5243        mMatchLabelForPredicate.mLabeledId = labeledId;
5244        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5245    }
5246
5247    /**
5248     * Computes whether this view is visible to the user. Such a view is
5249     * attached, visible, all its predecessors are visible, it is not clipped
5250     * entirely by its predecessors, and has an alpha greater than zero.
5251     *
5252     * @return Whether the view is visible on the screen.
5253     *
5254     * @hide
5255     */
5256    protected boolean isVisibleToUser() {
5257        return isVisibleToUser(null);
5258    }
5259
5260    /**
5261     * Computes whether the given portion of this view is visible to the user.
5262     * Such a view is attached, visible, all its predecessors are visible,
5263     * has an alpha greater than zero, and the specified portion is not
5264     * clipped entirely by its predecessors.
5265     *
5266     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5267     *                    <code>null</code>, and the entire view will be tested in this case.
5268     *                    When <code>true</code> is returned by the function, the actual visible
5269     *                    region will be stored in this parameter; that is, if boundInView is fully
5270     *                    contained within the view, no modification will be made, otherwise regions
5271     *                    outside of the visible area of the view will be clipped.
5272     *
5273     * @return Whether the specified portion of the view is visible on the screen.
5274     *
5275     * @hide
5276     */
5277    protected boolean isVisibleToUser(Rect boundInView) {
5278        if (mAttachInfo != null) {
5279            // Attached to invisible window means this view is not visible.
5280            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5281                return false;
5282            }
5283            // An invisible predecessor or one with alpha zero means
5284            // that this view is not visible to the user.
5285            Object current = this;
5286            while (current instanceof View) {
5287                View view = (View) current;
5288                // We have attach info so this view is attached and there is no
5289                // need to check whether we reach to ViewRootImpl on the way up.
5290                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5291                    return false;
5292                }
5293                current = view.mParent;
5294            }
5295            // Check if the view is entirely covered by its predecessors.
5296            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5297            Point offset = mAttachInfo.mPoint;
5298            if (!getGlobalVisibleRect(visibleRect, offset)) {
5299                return false;
5300            }
5301            // Check if the visible portion intersects the rectangle of interest.
5302            if (boundInView != null) {
5303                visibleRect.offset(-offset.x, -offset.y);
5304                return boundInView.intersect(visibleRect);
5305            }
5306            return true;
5307        }
5308        return false;
5309    }
5310
5311    /**
5312     * Returns the delegate for implementing accessibility support via
5313     * composition. For more details see {@link AccessibilityDelegate}.
5314     *
5315     * @return The delegate, or null if none set.
5316     *
5317     * @hide
5318     */
5319    public AccessibilityDelegate getAccessibilityDelegate() {
5320        return mAccessibilityDelegate;
5321    }
5322
5323    /**
5324     * Sets a delegate for implementing accessibility support via composition as
5325     * opposed to inheritance. The delegate's primary use is for implementing
5326     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5327     *
5328     * @param delegate The delegate instance.
5329     *
5330     * @see AccessibilityDelegate
5331     */
5332    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5333        mAccessibilityDelegate = delegate;
5334    }
5335
5336    /**
5337     * Gets the provider for managing a virtual view hierarchy rooted at this View
5338     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5339     * that explore the window content.
5340     * <p>
5341     * If this method returns an instance, this instance is responsible for managing
5342     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5343     * View including the one representing the View itself. Similarly the returned
5344     * instance is responsible for performing accessibility actions on any virtual
5345     * view or the root view itself.
5346     * </p>
5347     * <p>
5348     * If an {@link AccessibilityDelegate} has been specified via calling
5349     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5350     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5351     * is responsible for handling this call.
5352     * </p>
5353     *
5354     * @return The provider.
5355     *
5356     * @see AccessibilityNodeProvider
5357     */
5358    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5359        if (mAccessibilityDelegate != null) {
5360            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5361        } else {
5362            return null;
5363        }
5364    }
5365
5366    /**
5367     * Gets the unique identifier of this view on the screen for accessibility purposes.
5368     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5369     *
5370     * @return The view accessibility id.
5371     *
5372     * @hide
5373     */
5374    public int getAccessibilityViewId() {
5375        if (mAccessibilityViewId == NO_ID) {
5376            mAccessibilityViewId = sNextAccessibilityViewId++;
5377        }
5378        return mAccessibilityViewId;
5379    }
5380
5381    /**
5382     * Gets the unique identifier of the window in which this View reseides.
5383     *
5384     * @return The window accessibility id.
5385     *
5386     * @hide
5387     */
5388    public int getAccessibilityWindowId() {
5389        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5390    }
5391
5392    /**
5393     * Gets the {@link View} description. It briefly describes the view and is
5394     * primarily used for accessibility support. Set this property to enable
5395     * better accessibility support for your application. This is especially
5396     * true for views that do not have textual representation (For example,
5397     * ImageButton).
5398     *
5399     * @return The content description.
5400     *
5401     * @attr ref android.R.styleable#View_contentDescription
5402     */
5403    @ViewDebug.ExportedProperty(category = "accessibility")
5404    public CharSequence getContentDescription() {
5405        return mContentDescription;
5406    }
5407
5408    /**
5409     * Sets the {@link View} description. It briefly describes the view and is
5410     * primarily used for accessibility support. Set this property to enable
5411     * better accessibility support for your application. This is especially
5412     * true for views that do not have textual representation (For example,
5413     * ImageButton).
5414     *
5415     * @param contentDescription The content description.
5416     *
5417     * @attr ref android.R.styleable#View_contentDescription
5418     */
5419    @RemotableViewMethod
5420    public void setContentDescription(CharSequence contentDescription) {
5421        if (mContentDescription == null) {
5422            if (contentDescription == null) {
5423                return;
5424            }
5425        } else if (mContentDescription.equals(contentDescription)) {
5426            return;
5427        }
5428        mContentDescription = contentDescription;
5429        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5430        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5431            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5432            notifySubtreeAccessibilityStateChangedIfNeeded();
5433        } else {
5434            notifyViewAccessibilityStateChangedIfNeeded();
5435        }
5436    }
5437
5438    /**
5439     * Gets the id of a view for which this view serves as a label for
5440     * accessibility purposes.
5441     *
5442     * @return The labeled view id.
5443     */
5444    @ViewDebug.ExportedProperty(category = "accessibility")
5445    public int getLabelFor() {
5446        return mLabelForId;
5447    }
5448
5449    /**
5450     * Sets the id of a view for which this view serves as a label for
5451     * accessibility purposes.
5452     *
5453     * @param id The labeled view id.
5454     */
5455    @RemotableViewMethod
5456    public void setLabelFor(int id) {
5457        mLabelForId = id;
5458        if (mLabelForId != View.NO_ID
5459                && mID == View.NO_ID) {
5460            mID = generateViewId();
5461        }
5462    }
5463
5464    /**
5465     * Invoked whenever this view loses focus, either by losing window focus or by losing
5466     * focus within its window. This method can be used to clear any state tied to the
5467     * focus. For instance, if a button is held pressed with the trackball and the window
5468     * loses focus, this method can be used to cancel the press.
5469     *
5470     * Subclasses of View overriding this method should always call super.onFocusLost().
5471     *
5472     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5473     * @see #onWindowFocusChanged(boolean)
5474     *
5475     * @hide pending API council approval
5476     */
5477    protected void onFocusLost() {
5478        resetPressedState();
5479    }
5480
5481    private void resetPressedState() {
5482        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5483            return;
5484        }
5485
5486        if (isPressed()) {
5487            setPressed(false);
5488
5489            if (!mHasPerformedLongPress) {
5490                removeLongPressCallback();
5491            }
5492        }
5493    }
5494
5495    /**
5496     * Returns true if this view has focus
5497     *
5498     * @return True if this view has focus, false otherwise.
5499     */
5500    @ViewDebug.ExportedProperty(category = "focus")
5501    public boolean isFocused() {
5502        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5503    }
5504
5505    /**
5506     * Find the view in the hierarchy rooted at this view that currently has
5507     * focus.
5508     *
5509     * @return The view that currently has focus, or null if no focused view can
5510     *         be found.
5511     */
5512    public View findFocus() {
5513        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5514    }
5515
5516    /**
5517     * Indicates whether this view is one of the set of scrollable containers in
5518     * its window.
5519     *
5520     * @return whether this view is one of the set of scrollable containers in
5521     * its window
5522     *
5523     * @attr ref android.R.styleable#View_isScrollContainer
5524     */
5525    public boolean isScrollContainer() {
5526        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5527    }
5528
5529    /**
5530     * Change whether this view is one of the set of scrollable containers in
5531     * its window.  This will be used to determine whether the window can
5532     * resize or must pan when a soft input area is open -- scrollable
5533     * containers allow the window to use resize mode since the container
5534     * will appropriately shrink.
5535     *
5536     * @attr ref android.R.styleable#View_isScrollContainer
5537     */
5538    public void setScrollContainer(boolean isScrollContainer) {
5539        if (isScrollContainer) {
5540            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5541                mAttachInfo.mScrollContainers.add(this);
5542                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5543            }
5544            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5545        } else {
5546            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5547                mAttachInfo.mScrollContainers.remove(this);
5548            }
5549            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5550        }
5551    }
5552
5553    /**
5554     * Returns the quality of the drawing cache.
5555     *
5556     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5557     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5558     *
5559     * @see #setDrawingCacheQuality(int)
5560     * @see #setDrawingCacheEnabled(boolean)
5561     * @see #isDrawingCacheEnabled()
5562     *
5563     * @attr ref android.R.styleable#View_drawingCacheQuality
5564     */
5565    public int getDrawingCacheQuality() {
5566        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5567    }
5568
5569    /**
5570     * Set the drawing cache quality of this view. This value is used only when the
5571     * drawing cache is enabled
5572     *
5573     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5574     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5575     *
5576     * @see #getDrawingCacheQuality()
5577     * @see #setDrawingCacheEnabled(boolean)
5578     * @see #isDrawingCacheEnabled()
5579     *
5580     * @attr ref android.R.styleable#View_drawingCacheQuality
5581     */
5582    public void setDrawingCacheQuality(int quality) {
5583        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5584    }
5585
5586    /**
5587     * Returns whether the screen should remain on, corresponding to the current
5588     * value of {@link #KEEP_SCREEN_ON}.
5589     *
5590     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5591     *
5592     * @see #setKeepScreenOn(boolean)
5593     *
5594     * @attr ref android.R.styleable#View_keepScreenOn
5595     */
5596    public boolean getKeepScreenOn() {
5597        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5598    }
5599
5600    /**
5601     * Controls whether the screen should remain on, modifying the
5602     * value of {@link #KEEP_SCREEN_ON}.
5603     *
5604     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5605     *
5606     * @see #getKeepScreenOn()
5607     *
5608     * @attr ref android.R.styleable#View_keepScreenOn
5609     */
5610    public void setKeepScreenOn(boolean keepScreenOn) {
5611        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5612    }
5613
5614    /**
5615     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5616     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5617     *
5618     * @attr ref android.R.styleable#View_nextFocusLeft
5619     */
5620    public int getNextFocusLeftId() {
5621        return mNextFocusLeftId;
5622    }
5623
5624    /**
5625     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5626     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5627     * decide automatically.
5628     *
5629     * @attr ref android.R.styleable#View_nextFocusLeft
5630     */
5631    public void setNextFocusLeftId(int nextFocusLeftId) {
5632        mNextFocusLeftId = nextFocusLeftId;
5633    }
5634
5635    /**
5636     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5637     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5638     *
5639     * @attr ref android.R.styleable#View_nextFocusRight
5640     */
5641    public int getNextFocusRightId() {
5642        return mNextFocusRightId;
5643    }
5644
5645    /**
5646     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5647     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5648     * decide automatically.
5649     *
5650     * @attr ref android.R.styleable#View_nextFocusRight
5651     */
5652    public void setNextFocusRightId(int nextFocusRightId) {
5653        mNextFocusRightId = nextFocusRightId;
5654    }
5655
5656    /**
5657     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5658     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5659     *
5660     * @attr ref android.R.styleable#View_nextFocusUp
5661     */
5662    public int getNextFocusUpId() {
5663        return mNextFocusUpId;
5664    }
5665
5666    /**
5667     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5668     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5669     * decide automatically.
5670     *
5671     * @attr ref android.R.styleable#View_nextFocusUp
5672     */
5673    public void setNextFocusUpId(int nextFocusUpId) {
5674        mNextFocusUpId = nextFocusUpId;
5675    }
5676
5677    /**
5678     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5679     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5680     *
5681     * @attr ref android.R.styleable#View_nextFocusDown
5682     */
5683    public int getNextFocusDownId() {
5684        return mNextFocusDownId;
5685    }
5686
5687    /**
5688     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5689     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5690     * decide automatically.
5691     *
5692     * @attr ref android.R.styleable#View_nextFocusDown
5693     */
5694    public void setNextFocusDownId(int nextFocusDownId) {
5695        mNextFocusDownId = nextFocusDownId;
5696    }
5697
5698    /**
5699     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5700     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5701     *
5702     * @attr ref android.R.styleable#View_nextFocusForward
5703     */
5704    public int getNextFocusForwardId() {
5705        return mNextFocusForwardId;
5706    }
5707
5708    /**
5709     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5710     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5711     * decide automatically.
5712     *
5713     * @attr ref android.R.styleable#View_nextFocusForward
5714     */
5715    public void setNextFocusForwardId(int nextFocusForwardId) {
5716        mNextFocusForwardId = nextFocusForwardId;
5717    }
5718
5719    /**
5720     * Returns the visibility of this view and all of its ancestors
5721     *
5722     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5723     */
5724    public boolean isShown() {
5725        View current = this;
5726        //noinspection ConstantConditions
5727        do {
5728            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5729                return false;
5730            }
5731            ViewParent parent = current.mParent;
5732            if (parent == null) {
5733                return false; // We are not attached to the view root
5734            }
5735            if (!(parent instanceof View)) {
5736                return true;
5737            }
5738            current = (View) parent;
5739        } while (current != null);
5740
5741        return false;
5742    }
5743
5744    /**
5745     * Called by the view hierarchy when the content insets for a window have
5746     * changed, to allow it to adjust its content to fit within those windows.
5747     * The content insets tell you the space that the status bar, input method,
5748     * and other system windows infringe on the application's window.
5749     *
5750     * <p>You do not normally need to deal with this function, since the default
5751     * window decoration given to applications takes care of applying it to the
5752     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5753     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5754     * and your content can be placed under those system elements.  You can then
5755     * use this method within your view hierarchy if you have parts of your UI
5756     * which you would like to ensure are not being covered.
5757     *
5758     * <p>The default implementation of this method simply applies the content
5759     * insets to the view's padding, consuming that content (modifying the
5760     * insets to be 0), and returning true.  This behavior is off by default, but can
5761     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5762     *
5763     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5764     * insets object is propagated down the hierarchy, so any changes made to it will
5765     * be seen by all following views (including potentially ones above in
5766     * the hierarchy since this is a depth-first traversal).  The first view
5767     * that returns true will abort the entire traversal.
5768     *
5769     * <p>The default implementation works well for a situation where it is
5770     * used with a container that covers the entire window, allowing it to
5771     * apply the appropriate insets to its content on all edges.  If you need
5772     * a more complicated layout (such as two different views fitting system
5773     * windows, one on the top of the window, and one on the bottom),
5774     * you can override the method and handle the insets however you would like.
5775     * Note that the insets provided by the framework are always relative to the
5776     * far edges of the window, not accounting for the location of the called view
5777     * within that window.  (In fact when this method is called you do not yet know
5778     * where the layout will place the view, as it is done before layout happens.)
5779     *
5780     * <p>Note: unlike many View methods, there is no dispatch phase to this
5781     * call.  If you are overriding it in a ViewGroup and want to allow the
5782     * call to continue to your children, you must be sure to call the super
5783     * implementation.
5784     *
5785     * <p>Here is a sample layout that makes use of fitting system windows
5786     * to have controls for a video view placed inside of the window decorations
5787     * that it hides and shows.  This can be used with code like the second
5788     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5789     *
5790     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5791     *
5792     * @param insets Current content insets of the window.  Prior to
5793     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5794     * the insets or else you and Android will be unhappy.
5795     *
5796     * @return {@code true} if this view applied the insets and it should not
5797     * continue propagating further down the hierarchy, {@code false} otherwise.
5798     * @see #getFitsSystemWindows()
5799     * @see #setFitsSystemWindows(boolean)
5800     * @see #setSystemUiVisibility(int)
5801     */
5802    protected boolean fitSystemWindows(Rect insets) {
5803        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5804            mUserPaddingStart = UNDEFINED_PADDING;
5805            mUserPaddingEnd = UNDEFINED_PADDING;
5806            Rect localInsets = sThreadLocal.get();
5807            if (localInsets == null) {
5808                localInsets = new Rect();
5809                sThreadLocal.set(localInsets);
5810            }
5811            boolean res = computeFitSystemWindows(insets, localInsets);
5812            internalSetPadding(localInsets.left, localInsets.top,
5813                    localInsets.right, localInsets.bottom);
5814            return res;
5815        }
5816        return false;
5817    }
5818
5819    /**
5820     * @hide Compute the insets that should be consumed by this view and the ones
5821     * that should propagate to those under it.
5822     */
5823    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5824        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5825                || mAttachInfo == null
5826                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5827                        && !mAttachInfo.mOverscanRequested)) {
5828            outLocalInsets.set(inoutInsets);
5829            inoutInsets.set(0, 0, 0, 0);
5830            return true;
5831        } else {
5832            // The application wants to take care of fitting system window for
5833            // the content...  however we still need to take care of any overscan here.
5834            final Rect overscan = mAttachInfo.mOverscanInsets;
5835            outLocalInsets.set(overscan);
5836            inoutInsets.left -= overscan.left;
5837            inoutInsets.top -= overscan.top;
5838            inoutInsets.right -= overscan.right;
5839            inoutInsets.bottom -= overscan.bottom;
5840            return false;
5841        }
5842    }
5843
5844    /**
5845     * Sets whether or not this view should account for system screen decorations
5846     * such as the status bar and inset its content; that is, controlling whether
5847     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5848     * executed.  See that method for more details.
5849     *
5850     * <p>Note that if you are providing your own implementation of
5851     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5852     * flag to true -- your implementation will be overriding the default
5853     * implementation that checks this flag.
5854     *
5855     * @param fitSystemWindows If true, then the default implementation of
5856     * {@link #fitSystemWindows(Rect)} will be executed.
5857     *
5858     * @attr ref android.R.styleable#View_fitsSystemWindows
5859     * @see #getFitsSystemWindows()
5860     * @see #fitSystemWindows(Rect)
5861     * @see #setSystemUiVisibility(int)
5862     */
5863    public void setFitsSystemWindows(boolean fitSystemWindows) {
5864        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5865    }
5866
5867    /**
5868     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5869     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5870     * will be executed.
5871     *
5872     * @return {@code true} if the default implementation of
5873     * {@link #fitSystemWindows(Rect)} will be executed.
5874     *
5875     * @attr ref android.R.styleable#View_fitsSystemWindows
5876     * @see #setFitsSystemWindows(boolean)
5877     * @see #fitSystemWindows(Rect)
5878     * @see #setSystemUiVisibility(int)
5879     */
5880    public boolean getFitsSystemWindows() {
5881        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5882    }
5883
5884    /** @hide */
5885    public boolean fitsSystemWindows() {
5886        return getFitsSystemWindows();
5887    }
5888
5889    /**
5890     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5891     */
5892    public void requestFitSystemWindows() {
5893        if (mParent != null) {
5894            mParent.requestFitSystemWindows();
5895        }
5896    }
5897
5898    /**
5899     * For use by PhoneWindow to make its own system window fitting optional.
5900     * @hide
5901     */
5902    public void makeOptionalFitsSystemWindows() {
5903        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5904    }
5905
5906    /**
5907     * Returns the visibility status for this view.
5908     *
5909     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5910     * @attr ref android.R.styleable#View_visibility
5911     */
5912    @ViewDebug.ExportedProperty(mapping = {
5913        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5914        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5915        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5916    })
5917    public int getVisibility() {
5918        return mViewFlags & VISIBILITY_MASK;
5919    }
5920
5921    /**
5922     * Set the enabled state of this view.
5923     *
5924     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5925     * @attr ref android.R.styleable#View_visibility
5926     */
5927    @RemotableViewMethod
5928    public void setVisibility(int visibility) {
5929        setFlags(visibility, VISIBILITY_MASK);
5930        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5931    }
5932
5933    /**
5934     * Returns the enabled status for this view. The interpretation of the
5935     * enabled state varies by subclass.
5936     *
5937     * @return True if this view is enabled, false otherwise.
5938     */
5939    @ViewDebug.ExportedProperty
5940    public boolean isEnabled() {
5941        return (mViewFlags & ENABLED_MASK) == ENABLED;
5942    }
5943
5944    /**
5945     * Set the enabled state of this view. The interpretation of the enabled
5946     * state varies by subclass.
5947     *
5948     * @param enabled True if this view is enabled, false otherwise.
5949     */
5950    @RemotableViewMethod
5951    public void setEnabled(boolean enabled) {
5952        if (enabled == isEnabled()) return;
5953
5954        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5955
5956        /*
5957         * The View most likely has to change its appearance, so refresh
5958         * the drawable state.
5959         */
5960        refreshDrawableState();
5961
5962        // Invalidate too, since the default behavior for views is to be
5963        // be drawn at 50% alpha rather than to change the drawable.
5964        invalidate(true);
5965
5966        if (!enabled) {
5967            cancelPendingInputEvents();
5968        }
5969    }
5970
5971    /**
5972     * Set whether this view can receive the focus.
5973     *
5974     * Setting this to false will also ensure that this view is not focusable
5975     * in touch mode.
5976     *
5977     * @param focusable If true, this view can receive the focus.
5978     *
5979     * @see #setFocusableInTouchMode(boolean)
5980     * @attr ref android.R.styleable#View_focusable
5981     */
5982    public void setFocusable(boolean focusable) {
5983        if (!focusable) {
5984            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5985        }
5986        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5987    }
5988
5989    /**
5990     * Set whether this view can receive focus while in touch mode.
5991     *
5992     * Setting this to true will also ensure that this view is focusable.
5993     *
5994     * @param focusableInTouchMode If true, this view can receive the focus while
5995     *   in touch mode.
5996     *
5997     * @see #setFocusable(boolean)
5998     * @attr ref android.R.styleable#View_focusableInTouchMode
5999     */
6000    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6001        // Focusable in touch mode should always be set before the focusable flag
6002        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6003        // which, in touch mode, will not successfully request focus on this view
6004        // because the focusable in touch mode flag is not set
6005        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6006        if (focusableInTouchMode) {
6007            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6008        }
6009    }
6010
6011    /**
6012     * Set whether this view should have sound effects enabled for events such as
6013     * clicking and touching.
6014     *
6015     * <p>You may wish to disable sound effects for a view if you already play sounds,
6016     * for instance, a dial key that plays dtmf tones.
6017     *
6018     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6019     * @see #isSoundEffectsEnabled()
6020     * @see #playSoundEffect(int)
6021     * @attr ref android.R.styleable#View_soundEffectsEnabled
6022     */
6023    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6024        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6025    }
6026
6027    /**
6028     * @return whether this view should have sound effects enabled for events such as
6029     *     clicking and touching.
6030     *
6031     * @see #setSoundEffectsEnabled(boolean)
6032     * @see #playSoundEffect(int)
6033     * @attr ref android.R.styleable#View_soundEffectsEnabled
6034     */
6035    @ViewDebug.ExportedProperty
6036    public boolean isSoundEffectsEnabled() {
6037        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6038    }
6039
6040    /**
6041     * Set whether this view should have haptic feedback for events such as
6042     * long presses.
6043     *
6044     * <p>You may wish to disable haptic feedback if your view already controls
6045     * its own haptic feedback.
6046     *
6047     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6048     * @see #isHapticFeedbackEnabled()
6049     * @see #performHapticFeedback(int)
6050     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6051     */
6052    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6053        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6054    }
6055
6056    /**
6057     * @return whether this view should have haptic feedback enabled for events
6058     * long presses.
6059     *
6060     * @see #setHapticFeedbackEnabled(boolean)
6061     * @see #performHapticFeedback(int)
6062     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6063     */
6064    @ViewDebug.ExportedProperty
6065    public boolean isHapticFeedbackEnabled() {
6066        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6067    }
6068
6069    /**
6070     * Returns the layout direction for this view.
6071     *
6072     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6073     *   {@link #LAYOUT_DIRECTION_RTL},
6074     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6075     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6076     *
6077     * @attr ref android.R.styleable#View_layoutDirection
6078     *
6079     * @hide
6080     */
6081    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6082        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6083        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6084        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6085        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6086    })
6087    public int getRawLayoutDirection() {
6088        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6089    }
6090
6091    /**
6092     * Set the layout direction for this view. This will propagate a reset of layout direction
6093     * resolution to the view's children and resolve layout direction for this view.
6094     *
6095     * @param layoutDirection the layout direction to set. Should be one of:
6096     *
6097     * {@link #LAYOUT_DIRECTION_LTR},
6098     * {@link #LAYOUT_DIRECTION_RTL},
6099     * {@link #LAYOUT_DIRECTION_INHERIT},
6100     * {@link #LAYOUT_DIRECTION_LOCALE}.
6101     *
6102     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6103     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6104     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6105     *
6106     * @attr ref android.R.styleable#View_layoutDirection
6107     */
6108    @RemotableViewMethod
6109    public void setLayoutDirection(int layoutDirection) {
6110        if (getRawLayoutDirection() != layoutDirection) {
6111            // Reset the current layout direction and the resolved one
6112            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6113            resetRtlProperties();
6114            // Set the new layout direction (filtered)
6115            mPrivateFlags2 |=
6116                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6117            // We need to resolve all RTL properties as they all depend on layout direction
6118            resolveRtlPropertiesIfNeeded();
6119            requestLayout();
6120            invalidate(true);
6121        }
6122    }
6123
6124    /**
6125     * Returns the resolved layout direction for this view.
6126     *
6127     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6128     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6129     *
6130     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6131     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6132     *
6133     * @attr ref android.R.styleable#View_layoutDirection
6134     */
6135    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6136        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6137        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6138    })
6139    public int getLayoutDirection() {
6140        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6141        if (targetSdkVersion < JELLY_BEAN_MR1) {
6142            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6143            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6144        }
6145        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6146                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6147    }
6148
6149    /**
6150     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6151     * layout attribute and/or the inherited value from the parent
6152     *
6153     * @return true if the layout is right-to-left.
6154     *
6155     * @hide
6156     */
6157    @ViewDebug.ExportedProperty(category = "layout")
6158    public boolean isLayoutRtl() {
6159        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6160    }
6161
6162    /**
6163     * Indicates whether the view is currently tracking transient state that the
6164     * app should not need to concern itself with saving and restoring, but that
6165     * the framework should take special note to preserve when possible.
6166     *
6167     * <p>A view with transient state cannot be trivially rebound from an external
6168     * data source, such as an adapter binding item views in a list. This may be
6169     * because the view is performing an animation, tracking user selection
6170     * of content, or similar.</p>
6171     *
6172     * @return true if the view has transient state
6173     */
6174    @ViewDebug.ExportedProperty(category = "layout")
6175    public boolean hasTransientState() {
6176        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6177    }
6178
6179    /**
6180     * Set whether this view is currently tracking transient state that the
6181     * framework should attempt to preserve when possible. This flag is reference counted,
6182     * so every call to setHasTransientState(true) should be paired with a later call
6183     * to setHasTransientState(false).
6184     *
6185     * <p>A view with transient state cannot be trivially rebound from an external
6186     * data source, such as an adapter binding item views in a list. This may be
6187     * because the view is performing an animation, tracking user selection
6188     * of content, or similar.</p>
6189     *
6190     * @param hasTransientState true if this view has transient state
6191     */
6192    public void setHasTransientState(boolean hasTransientState) {
6193        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6194                mTransientStateCount - 1;
6195        if (mTransientStateCount < 0) {
6196            mTransientStateCount = 0;
6197            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6198                    "unmatched pair of setHasTransientState calls");
6199        } else if ((hasTransientState && mTransientStateCount == 1) ||
6200                (!hasTransientState && mTransientStateCount == 0)) {
6201            // update flag if we've just incremented up from 0 or decremented down to 0
6202            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6203                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6204            if (mParent != null) {
6205                try {
6206                    mParent.childHasTransientStateChanged(this, hasTransientState);
6207                } catch (AbstractMethodError e) {
6208                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6209                            " does not fully implement ViewParent", e);
6210                }
6211            }
6212        }
6213    }
6214
6215    /**
6216     * Returns true if this view is currently attached to a window.
6217     */
6218    public boolean isAttachedToWindow() {
6219        return mAttachInfo != null;
6220    }
6221
6222    /**
6223     * Returns true if this view has been through at least one layout since it
6224     * was last attached to or detached from a window.
6225     */
6226    public boolean isLaidOut() {
6227        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6228    }
6229
6230    /**
6231     * If this view doesn't do any drawing on its own, set this flag to
6232     * allow further optimizations. By default, this flag is not set on
6233     * View, but could be set on some View subclasses such as ViewGroup.
6234     *
6235     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6236     * you should clear this flag.
6237     *
6238     * @param willNotDraw whether or not this View draw on its own
6239     */
6240    public void setWillNotDraw(boolean willNotDraw) {
6241        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6242    }
6243
6244    /**
6245     * Returns whether or not this View draws on its own.
6246     *
6247     * @return true if this view has nothing to draw, false otherwise
6248     */
6249    @ViewDebug.ExportedProperty(category = "drawing")
6250    public boolean willNotDraw() {
6251        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6252    }
6253
6254    /**
6255     * When a View's drawing cache is enabled, drawing is redirected to an
6256     * offscreen bitmap. Some views, like an ImageView, must be able to
6257     * bypass this mechanism if they already draw a single bitmap, to avoid
6258     * unnecessary usage of the memory.
6259     *
6260     * @param willNotCacheDrawing true if this view does not cache its
6261     *        drawing, false otherwise
6262     */
6263    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6264        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6265    }
6266
6267    /**
6268     * Returns whether or not this View can cache its drawing or not.
6269     *
6270     * @return true if this view does not cache its drawing, false otherwise
6271     */
6272    @ViewDebug.ExportedProperty(category = "drawing")
6273    public boolean willNotCacheDrawing() {
6274        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6275    }
6276
6277    /**
6278     * Indicates whether this view reacts to click events or not.
6279     *
6280     * @return true if the view is clickable, false otherwise
6281     *
6282     * @see #setClickable(boolean)
6283     * @attr ref android.R.styleable#View_clickable
6284     */
6285    @ViewDebug.ExportedProperty
6286    public boolean isClickable() {
6287        return (mViewFlags & CLICKABLE) == CLICKABLE;
6288    }
6289
6290    /**
6291     * Enables or disables click events for this view. When a view
6292     * is clickable it will change its state to "pressed" on every click.
6293     * Subclasses should set the view clickable to visually react to
6294     * user's clicks.
6295     *
6296     * @param clickable true to make the view clickable, false otherwise
6297     *
6298     * @see #isClickable()
6299     * @attr ref android.R.styleable#View_clickable
6300     */
6301    public void setClickable(boolean clickable) {
6302        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6303    }
6304
6305    /**
6306     * Indicates whether this view reacts to long click events or not.
6307     *
6308     * @return true if the view is long clickable, false otherwise
6309     *
6310     * @see #setLongClickable(boolean)
6311     * @attr ref android.R.styleable#View_longClickable
6312     */
6313    public boolean isLongClickable() {
6314        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6315    }
6316
6317    /**
6318     * Enables or disables long click events for this view. When a view is long
6319     * clickable it reacts to the user holding down the button for a longer
6320     * duration than a tap. This event can either launch the listener or a
6321     * context menu.
6322     *
6323     * @param longClickable true to make the view long clickable, false otherwise
6324     * @see #isLongClickable()
6325     * @attr ref android.R.styleable#View_longClickable
6326     */
6327    public void setLongClickable(boolean longClickable) {
6328        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6329    }
6330
6331    /**
6332     * Sets the pressed state for this view.
6333     *
6334     * @see #isClickable()
6335     * @see #setClickable(boolean)
6336     *
6337     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6338     *        the View's internal state from a previously set "pressed" state.
6339     */
6340    public void setPressed(boolean pressed) {
6341        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6342
6343        if (pressed) {
6344            mPrivateFlags |= PFLAG_PRESSED;
6345        } else {
6346            mPrivateFlags &= ~PFLAG_PRESSED;
6347        }
6348
6349        if (needsRefresh) {
6350            refreshDrawableState();
6351        }
6352        dispatchSetPressed(pressed);
6353    }
6354
6355    /**
6356     * Dispatch setPressed to all of this View's children.
6357     *
6358     * @see #setPressed(boolean)
6359     *
6360     * @param pressed The new pressed state
6361     */
6362    protected void dispatchSetPressed(boolean pressed) {
6363    }
6364
6365    /**
6366     * Indicates whether the view is currently in pressed state. Unless
6367     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6368     * the pressed state.
6369     *
6370     * @see #setPressed(boolean)
6371     * @see #isClickable()
6372     * @see #setClickable(boolean)
6373     *
6374     * @return true if the view is currently pressed, false otherwise
6375     */
6376    public boolean isPressed() {
6377        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6378    }
6379
6380    /**
6381     * Indicates whether this view will save its state (that is,
6382     * whether its {@link #onSaveInstanceState} method will be called).
6383     *
6384     * @return Returns true if the view state saving is enabled, else false.
6385     *
6386     * @see #setSaveEnabled(boolean)
6387     * @attr ref android.R.styleable#View_saveEnabled
6388     */
6389    public boolean isSaveEnabled() {
6390        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6391    }
6392
6393    /**
6394     * Controls whether the saving of this view's state is
6395     * enabled (that is, whether its {@link #onSaveInstanceState} method
6396     * will be called).  Note that even if freezing is enabled, the
6397     * view still must have an id assigned to it (via {@link #setId(int)})
6398     * for its state to be saved.  This flag can only disable the
6399     * saving of this view; any child views may still have their state saved.
6400     *
6401     * @param enabled Set to false to <em>disable</em> state saving, or true
6402     * (the default) to allow it.
6403     *
6404     * @see #isSaveEnabled()
6405     * @see #setId(int)
6406     * @see #onSaveInstanceState()
6407     * @attr ref android.R.styleable#View_saveEnabled
6408     */
6409    public void setSaveEnabled(boolean enabled) {
6410        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6411    }
6412
6413    /**
6414     * Gets whether the framework should discard touches when the view's
6415     * window is obscured by another visible window.
6416     * Refer to the {@link View} security documentation for more details.
6417     *
6418     * @return True if touch filtering is enabled.
6419     *
6420     * @see #setFilterTouchesWhenObscured(boolean)
6421     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6422     */
6423    @ViewDebug.ExportedProperty
6424    public boolean getFilterTouchesWhenObscured() {
6425        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6426    }
6427
6428    /**
6429     * Sets whether the framework should discard touches when the view's
6430     * window is obscured by another visible window.
6431     * Refer to the {@link View} security documentation for more details.
6432     *
6433     * @param enabled True if touch filtering should be enabled.
6434     *
6435     * @see #getFilterTouchesWhenObscured
6436     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6437     */
6438    public void setFilterTouchesWhenObscured(boolean enabled) {
6439        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6440                FILTER_TOUCHES_WHEN_OBSCURED);
6441    }
6442
6443    /**
6444     * Indicates whether the entire hierarchy under this view will save its
6445     * state when a state saving traversal occurs from its parent.  The default
6446     * is true; if false, these views will not be saved unless
6447     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6448     *
6449     * @return Returns true if the view state saving from parent is enabled, else false.
6450     *
6451     * @see #setSaveFromParentEnabled(boolean)
6452     */
6453    public boolean isSaveFromParentEnabled() {
6454        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6455    }
6456
6457    /**
6458     * Controls whether the entire hierarchy under this view will save its
6459     * state when a state saving traversal occurs from its parent.  The default
6460     * is true; if false, these views will not be saved unless
6461     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6462     *
6463     * @param enabled Set to false to <em>disable</em> state saving, or true
6464     * (the default) to allow it.
6465     *
6466     * @see #isSaveFromParentEnabled()
6467     * @see #setId(int)
6468     * @see #onSaveInstanceState()
6469     */
6470    public void setSaveFromParentEnabled(boolean enabled) {
6471        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6472    }
6473
6474
6475    /**
6476     * Returns whether this View is able to take focus.
6477     *
6478     * @return True if this view can take focus, or false otherwise.
6479     * @attr ref android.R.styleable#View_focusable
6480     */
6481    @ViewDebug.ExportedProperty(category = "focus")
6482    public final boolean isFocusable() {
6483        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6484    }
6485
6486    /**
6487     * When a view is focusable, it may not want to take focus when in touch mode.
6488     * For example, a button would like focus when the user is navigating via a D-pad
6489     * so that the user can click on it, but once the user starts touching the screen,
6490     * the button shouldn't take focus
6491     * @return Whether the view is focusable in touch mode.
6492     * @attr ref android.R.styleable#View_focusableInTouchMode
6493     */
6494    @ViewDebug.ExportedProperty
6495    public final boolean isFocusableInTouchMode() {
6496        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6497    }
6498
6499    /**
6500     * Find the nearest view in the specified direction that can take focus.
6501     * This does not actually give focus to that view.
6502     *
6503     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6504     *
6505     * @return The nearest focusable in the specified direction, or null if none
6506     *         can be found.
6507     */
6508    public View focusSearch(int direction) {
6509        if (mParent != null) {
6510            return mParent.focusSearch(this, direction);
6511        } else {
6512            return null;
6513        }
6514    }
6515
6516    /**
6517     * This method is the last chance for the focused view and its ancestors to
6518     * respond to an arrow key. This is called when the focused view did not
6519     * consume the key internally, nor could the view system find a new view in
6520     * the requested direction to give focus to.
6521     *
6522     * @param focused The currently focused view.
6523     * @param direction The direction focus wants to move. One of FOCUS_UP,
6524     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6525     * @return True if the this view consumed this unhandled move.
6526     */
6527    public boolean dispatchUnhandledMove(View focused, int direction) {
6528        return false;
6529    }
6530
6531    /**
6532     * If a user manually specified the next view id for a particular direction,
6533     * use the root to look up the view.
6534     * @param root The root view of the hierarchy containing this view.
6535     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6536     * or FOCUS_BACKWARD.
6537     * @return The user specified next view, or null if there is none.
6538     */
6539    View findUserSetNextFocus(View root, int direction) {
6540        switch (direction) {
6541            case FOCUS_LEFT:
6542                if (mNextFocusLeftId == View.NO_ID) return null;
6543                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6544            case FOCUS_RIGHT:
6545                if (mNextFocusRightId == View.NO_ID) return null;
6546                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6547            case FOCUS_UP:
6548                if (mNextFocusUpId == View.NO_ID) return null;
6549                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6550            case FOCUS_DOWN:
6551                if (mNextFocusDownId == View.NO_ID) return null;
6552                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6553            case FOCUS_FORWARD:
6554                if (mNextFocusForwardId == View.NO_ID) return null;
6555                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6556            case FOCUS_BACKWARD: {
6557                if (mID == View.NO_ID) return null;
6558                final int id = mID;
6559                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6560                    @Override
6561                    public boolean apply(View t) {
6562                        return t.mNextFocusForwardId == id;
6563                    }
6564                });
6565            }
6566        }
6567        return null;
6568    }
6569
6570    private View findViewInsideOutShouldExist(View root, int id) {
6571        if (mMatchIdPredicate == null) {
6572            mMatchIdPredicate = new MatchIdPredicate();
6573        }
6574        mMatchIdPredicate.mId = id;
6575        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6576        if (result == null) {
6577            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6578        }
6579        return result;
6580    }
6581
6582    /**
6583     * Find and return all focusable views that are descendants of this view,
6584     * possibly including this view if it is focusable itself.
6585     *
6586     * @param direction The direction of the focus
6587     * @return A list of focusable views
6588     */
6589    public ArrayList<View> getFocusables(int direction) {
6590        ArrayList<View> result = new ArrayList<View>(24);
6591        addFocusables(result, direction);
6592        return result;
6593    }
6594
6595    /**
6596     * Add any focusable views that are descendants of this view (possibly
6597     * including this view if it is focusable itself) to views.  If we are in touch mode,
6598     * only add views that are also focusable in touch mode.
6599     *
6600     * @param views Focusable views found so far
6601     * @param direction The direction of the focus
6602     */
6603    public void addFocusables(ArrayList<View> views, int direction) {
6604        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6605    }
6606
6607    /**
6608     * Adds any focusable views that are descendants of this view (possibly
6609     * including this view if it is focusable itself) to views. This method
6610     * adds all focusable views regardless if we are in touch mode or
6611     * only views focusable in touch mode if we are in touch mode or
6612     * only views that can take accessibility focus if accessibility is enabeld
6613     * depending on the focusable mode paramater.
6614     *
6615     * @param views Focusable views found so far or null if all we are interested is
6616     *        the number of focusables.
6617     * @param direction The direction of the focus.
6618     * @param focusableMode The type of focusables to be added.
6619     *
6620     * @see #FOCUSABLES_ALL
6621     * @see #FOCUSABLES_TOUCH_MODE
6622     */
6623    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6624        if (views == null) {
6625            return;
6626        }
6627        if (!isFocusable()) {
6628            return;
6629        }
6630        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6631                && isInTouchMode() && !isFocusableInTouchMode()) {
6632            return;
6633        }
6634        views.add(this);
6635    }
6636
6637    /**
6638     * Finds the Views that contain given text. The containment is case insensitive.
6639     * The search is performed by either the text that the View renders or the content
6640     * description that describes the view for accessibility purposes and the view does
6641     * not render or both. Clients can specify how the search is to be performed via
6642     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6643     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6644     *
6645     * @param outViews The output list of matching Views.
6646     * @param searched The text to match against.
6647     *
6648     * @see #FIND_VIEWS_WITH_TEXT
6649     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6650     * @see #setContentDescription(CharSequence)
6651     */
6652    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6653        if (getAccessibilityNodeProvider() != null) {
6654            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6655                outViews.add(this);
6656            }
6657        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6658                && (searched != null && searched.length() > 0)
6659                && (mContentDescription != null && mContentDescription.length() > 0)) {
6660            String searchedLowerCase = searched.toString().toLowerCase();
6661            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6662            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6663                outViews.add(this);
6664            }
6665        }
6666    }
6667
6668    /**
6669     * Find and return all touchable views that are descendants of this view,
6670     * possibly including this view if it is touchable itself.
6671     *
6672     * @return A list of touchable views
6673     */
6674    public ArrayList<View> getTouchables() {
6675        ArrayList<View> result = new ArrayList<View>();
6676        addTouchables(result);
6677        return result;
6678    }
6679
6680    /**
6681     * Add any touchable views that are descendants of this view (possibly
6682     * including this view if it is touchable itself) to views.
6683     *
6684     * @param views Touchable views found so far
6685     */
6686    public void addTouchables(ArrayList<View> views) {
6687        final int viewFlags = mViewFlags;
6688
6689        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6690                && (viewFlags & ENABLED_MASK) == ENABLED) {
6691            views.add(this);
6692        }
6693    }
6694
6695    /**
6696     * Returns whether this View is accessibility focused.
6697     *
6698     * @return True if this View is accessibility focused.
6699     * @hide
6700     */
6701    public boolean isAccessibilityFocused() {
6702        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6703    }
6704
6705    /**
6706     * Call this to try to give accessibility focus to this view.
6707     *
6708     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6709     * returns false or the view is no visible or the view already has accessibility
6710     * focus.
6711     *
6712     * See also {@link #focusSearch(int)}, which is what you call to say that you
6713     * have focus, and you want your parent to look for the next one.
6714     *
6715     * @return Whether this view actually took accessibility focus.
6716     *
6717     * @hide
6718     */
6719    public boolean requestAccessibilityFocus() {
6720        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6721        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6722            return false;
6723        }
6724        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6725            return false;
6726        }
6727        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6728            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6729            ViewRootImpl viewRootImpl = getViewRootImpl();
6730            if (viewRootImpl != null) {
6731                viewRootImpl.setAccessibilityFocus(this, null);
6732            }
6733            invalidate();
6734            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6735            return true;
6736        }
6737        return false;
6738    }
6739
6740    /**
6741     * Call this to try to clear accessibility focus of this view.
6742     *
6743     * See also {@link #focusSearch(int)}, which is what you call to say that you
6744     * have focus, and you want your parent to look for the next one.
6745     *
6746     * @hide
6747     */
6748    public void clearAccessibilityFocus() {
6749        clearAccessibilityFocusNoCallbacks();
6750        // Clear the global reference of accessibility focus if this
6751        // view or any of its descendants had accessibility focus.
6752        ViewRootImpl viewRootImpl = getViewRootImpl();
6753        if (viewRootImpl != null) {
6754            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6755            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6756                viewRootImpl.setAccessibilityFocus(null, null);
6757            }
6758        }
6759    }
6760
6761    private void sendAccessibilityHoverEvent(int eventType) {
6762        // Since we are not delivering to a client accessibility events from not
6763        // important views (unless the clinet request that) we need to fire the
6764        // event from the deepest view exposed to the client. As a consequence if
6765        // the user crosses a not exposed view the client will see enter and exit
6766        // of the exposed predecessor followed by and enter and exit of that same
6767        // predecessor when entering and exiting the not exposed descendant. This
6768        // is fine since the client has a clear idea which view is hovered at the
6769        // price of a couple more events being sent. This is a simple and
6770        // working solution.
6771        View source = this;
6772        while (true) {
6773            if (source.includeForAccessibility()) {
6774                source.sendAccessibilityEvent(eventType);
6775                return;
6776            }
6777            ViewParent parent = source.getParent();
6778            if (parent instanceof View) {
6779                source = (View) parent;
6780            } else {
6781                return;
6782            }
6783        }
6784    }
6785
6786    /**
6787     * Clears accessibility focus without calling any callback methods
6788     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6789     * is used for clearing accessibility focus when giving this focus to
6790     * another view.
6791     */
6792    void clearAccessibilityFocusNoCallbacks() {
6793        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6794            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6795            invalidate();
6796            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6797        }
6798    }
6799
6800    /**
6801     * Call this to try to give focus to a specific view or to one of its
6802     * descendants.
6803     *
6804     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6805     * false), or if it is focusable and it is not focusable in touch mode
6806     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6807     *
6808     * See also {@link #focusSearch(int)}, which is what you call to say that you
6809     * have focus, and you want your parent to look for the next one.
6810     *
6811     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6812     * {@link #FOCUS_DOWN} and <code>null</code>.
6813     *
6814     * @return Whether this view or one of its descendants actually took focus.
6815     */
6816    public final boolean requestFocus() {
6817        return requestFocus(View.FOCUS_DOWN);
6818    }
6819
6820    /**
6821     * Call this to try to give focus to a specific view or to one of its
6822     * descendants and give it a hint about what direction focus is heading.
6823     *
6824     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6825     * false), or if it is focusable and it is not focusable in touch mode
6826     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6827     *
6828     * See also {@link #focusSearch(int)}, which is what you call to say that you
6829     * have focus, and you want your parent to look for the next one.
6830     *
6831     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6832     * <code>null</code> set for the previously focused rectangle.
6833     *
6834     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6835     * @return Whether this view or one of its descendants actually took focus.
6836     */
6837    public final boolean requestFocus(int direction) {
6838        return requestFocus(direction, null);
6839    }
6840
6841    /**
6842     * Call this to try to give focus to a specific view or to one of its descendants
6843     * and give it hints about the direction and a specific rectangle that the focus
6844     * is coming from.  The rectangle can help give larger views a finer grained hint
6845     * about where focus is coming from, and therefore, where to show selection, or
6846     * forward focus change internally.
6847     *
6848     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6849     * false), or if it is focusable and it is not focusable in touch mode
6850     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6851     *
6852     * A View will not take focus if it is not visible.
6853     *
6854     * A View will not take focus if one of its parents has
6855     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6856     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6857     *
6858     * See also {@link #focusSearch(int)}, which is what you call to say that you
6859     * have focus, and you want your parent to look for the next one.
6860     *
6861     * You may wish to override this method if your custom {@link View} has an internal
6862     * {@link View} that it wishes to forward the request to.
6863     *
6864     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6865     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6866     *        to give a finer grained hint about where focus is coming from.  May be null
6867     *        if there is no hint.
6868     * @return Whether this view or one of its descendants actually took focus.
6869     */
6870    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6871        return requestFocusNoSearch(direction, previouslyFocusedRect);
6872    }
6873
6874    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6875        // need to be focusable
6876        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6877                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6878            return false;
6879        }
6880
6881        // need to be focusable in touch mode if in touch mode
6882        if (isInTouchMode() &&
6883            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6884               return false;
6885        }
6886
6887        // need to not have any parents blocking us
6888        if (hasAncestorThatBlocksDescendantFocus()) {
6889            return false;
6890        }
6891
6892        handleFocusGainInternal(direction, previouslyFocusedRect);
6893        return true;
6894    }
6895
6896    /**
6897     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6898     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6899     * touch mode to request focus when they are touched.
6900     *
6901     * @return Whether this view or one of its descendants actually took focus.
6902     *
6903     * @see #isInTouchMode()
6904     *
6905     */
6906    public final boolean requestFocusFromTouch() {
6907        // Leave touch mode if we need to
6908        if (isInTouchMode()) {
6909            ViewRootImpl viewRoot = getViewRootImpl();
6910            if (viewRoot != null) {
6911                viewRoot.ensureTouchMode(false);
6912            }
6913        }
6914        return requestFocus(View.FOCUS_DOWN);
6915    }
6916
6917    /**
6918     * @return Whether any ancestor of this view blocks descendant focus.
6919     */
6920    private boolean hasAncestorThatBlocksDescendantFocus() {
6921        ViewParent ancestor = mParent;
6922        while (ancestor instanceof ViewGroup) {
6923            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6924            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6925                return true;
6926            } else {
6927                ancestor = vgAncestor.getParent();
6928            }
6929        }
6930        return false;
6931    }
6932
6933    /**
6934     * Gets the mode for determining whether this View is important for accessibility
6935     * which is if it fires accessibility events and if it is reported to
6936     * accessibility services that query the screen.
6937     *
6938     * @return The mode for determining whether a View is important for accessibility.
6939     *
6940     * @attr ref android.R.styleable#View_importantForAccessibility
6941     *
6942     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6943     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6944     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6945     */
6946    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6947            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6948            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6949            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6950        })
6951    public int getImportantForAccessibility() {
6952        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6953                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6954    }
6955
6956    /**
6957     * Sets how to determine whether this view is important for accessibility
6958     * which is if it fires accessibility events and if it is reported to
6959     * accessibility services that query the screen.
6960     *
6961     * @param mode How to determine whether this view is important for accessibility.
6962     *
6963     * @attr ref android.R.styleable#View_importantForAccessibility
6964     *
6965     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6966     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6967     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6968     */
6969    public void setImportantForAccessibility(int mode) {
6970        final boolean oldIncludeForAccessibility = includeForAccessibility();
6971        if (mode != getImportantForAccessibility()) {
6972            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6973            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6974                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6975            if (oldIncludeForAccessibility != includeForAccessibility()) {
6976                notifySubtreeAccessibilityStateChangedIfNeeded();
6977            } else {
6978                notifyViewAccessibilityStateChangedIfNeeded();
6979            }
6980        }
6981    }
6982
6983    /**
6984     * Gets whether this view should be exposed for accessibility.
6985     *
6986     * @return Whether the view is exposed for accessibility.
6987     *
6988     * @hide
6989     */
6990    public boolean isImportantForAccessibility() {
6991        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6992                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6993        switch (mode) {
6994            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6995                return true;
6996            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6997                return false;
6998            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6999                return isActionableForAccessibility() || hasListenersForAccessibility()
7000                        || getAccessibilityNodeProvider() != null;
7001            default:
7002                throw new IllegalArgumentException("Unknow important for accessibility mode: "
7003                        + mode);
7004        }
7005    }
7006
7007    /**
7008     * Gets the parent for accessibility purposes. Note that the parent for
7009     * accessibility is not necessary the immediate parent. It is the first
7010     * predecessor that is important for accessibility.
7011     *
7012     * @return The parent for accessibility purposes.
7013     */
7014    public ViewParent getParentForAccessibility() {
7015        if (mParent instanceof View) {
7016            View parentView = (View) mParent;
7017            if (parentView.includeForAccessibility()) {
7018                return mParent;
7019            } else {
7020                return mParent.getParentForAccessibility();
7021            }
7022        }
7023        return null;
7024    }
7025
7026    /**
7027     * Adds the children of a given View for accessibility. Since some Views are
7028     * not important for accessibility the children for accessibility are not
7029     * necessarily direct children of the view, rather they are the first level of
7030     * descendants important for accessibility.
7031     *
7032     * @param children The list of children for accessibility.
7033     */
7034    public void addChildrenForAccessibility(ArrayList<View> children) {
7035        if (includeForAccessibility()) {
7036            children.add(this);
7037        }
7038    }
7039
7040    /**
7041     * Whether to regard this view for accessibility. A view is regarded for
7042     * accessibility if it is important for accessibility or the querying
7043     * accessibility service has explicitly requested that view not
7044     * important for accessibility are regarded.
7045     *
7046     * @return Whether to regard the view for accessibility.
7047     *
7048     * @hide
7049     */
7050    public boolean includeForAccessibility() {
7051        //noinspection SimplifiableIfStatement
7052        if (mAttachInfo != null) {
7053            return (mAttachInfo.mAccessibilityFetchFlags
7054                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7055                    || isImportantForAccessibility();
7056        }
7057        return false;
7058    }
7059
7060    /**
7061     * Returns whether the View is considered actionable from
7062     * accessibility perspective. Such view are important for
7063     * accessibility.
7064     *
7065     * @return True if the view is actionable for accessibility.
7066     *
7067     * @hide
7068     */
7069    public boolean isActionableForAccessibility() {
7070        return (isClickable() || isLongClickable() || isFocusable());
7071    }
7072
7073    /**
7074     * Returns whether the View has registered callbacks wich makes it
7075     * important for accessibility.
7076     *
7077     * @return True if the view is actionable for accessibility.
7078     */
7079    private boolean hasListenersForAccessibility() {
7080        ListenerInfo info = getListenerInfo();
7081        return mTouchDelegate != null || info.mOnKeyListener != null
7082                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7083                || info.mOnHoverListener != null || info.mOnDragListener != null;
7084    }
7085
7086    /**
7087     * Notifies that the accessibility state of this view changed. The change
7088     * is local to this view and does not represent structural changes such
7089     * as children and parent. For example, the view became focusable. The
7090     * notification is at at most once every
7091     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7092     * to avoid unnecessary load to the system. Also once a view has a pending
7093     * notifucation this method is a NOP until the notification has been sent.
7094     *
7095     * @hide
7096     */
7097    public void notifyViewAccessibilityStateChangedIfNeeded() {
7098        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7099            return;
7100        }
7101        if (mSendViewStateChangedAccessibilityEvent == null) {
7102            mSendViewStateChangedAccessibilityEvent =
7103                    new SendViewStateChangedAccessibilityEvent();
7104        }
7105        mSendViewStateChangedAccessibilityEvent.runOrPost();
7106    }
7107
7108    /**
7109     * Notifies that the accessibility state of this view changed. The change
7110     * is *not* local to this view and does represent structural changes such
7111     * as children and parent. For example, the view size changed. The
7112     * notification is at at most once every
7113     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7114     * to avoid unnecessary load to the system. Also once a view has a pending
7115     * notifucation this method is a NOP until the notification has been sent.
7116     *
7117     * @hide
7118     */
7119    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7120        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7121            return;
7122        }
7123        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7124            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7125            if (mParent != null) {
7126                try {
7127                    mParent.childAccessibilityStateChanged(this);
7128                } catch (AbstractMethodError e) {
7129                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7130                            " does not fully implement ViewParent", e);
7131                }
7132            }
7133        }
7134    }
7135
7136    /**
7137     * Reset the flag indicating the accessibility state of the subtree rooted
7138     * at this view changed.
7139     */
7140    void resetSubtreeAccessibilityStateChanged() {
7141        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7142    }
7143
7144    /**
7145     * Performs the specified accessibility action on the view. For
7146     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7147     * <p>
7148     * If an {@link AccessibilityDelegate} has been specified via calling
7149     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7150     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7151     * is responsible for handling this call.
7152     * </p>
7153     *
7154     * @param action The action to perform.
7155     * @param arguments Optional action arguments.
7156     * @return Whether the action was performed.
7157     */
7158    public boolean performAccessibilityAction(int action, Bundle arguments) {
7159      if (mAccessibilityDelegate != null) {
7160          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7161      } else {
7162          return performAccessibilityActionInternal(action, arguments);
7163      }
7164    }
7165
7166   /**
7167    * @see #performAccessibilityAction(int, Bundle)
7168    *
7169    * Note: Called from the default {@link AccessibilityDelegate}.
7170    */
7171    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7172        switch (action) {
7173            case AccessibilityNodeInfo.ACTION_CLICK: {
7174                if (isClickable()) {
7175                    performClick();
7176                    return true;
7177                }
7178            } break;
7179            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7180                if (isLongClickable()) {
7181                    performLongClick();
7182                    return true;
7183                }
7184            } break;
7185            case AccessibilityNodeInfo.ACTION_FOCUS: {
7186                if (!hasFocus()) {
7187                    // Get out of touch mode since accessibility
7188                    // wants to move focus around.
7189                    getViewRootImpl().ensureTouchMode(false);
7190                    return requestFocus();
7191                }
7192            } break;
7193            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7194                if (hasFocus()) {
7195                    clearFocus();
7196                    return !isFocused();
7197                }
7198            } break;
7199            case AccessibilityNodeInfo.ACTION_SELECT: {
7200                if (!isSelected()) {
7201                    setSelected(true);
7202                    return isSelected();
7203                }
7204            } break;
7205            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7206                if (isSelected()) {
7207                    setSelected(false);
7208                    return !isSelected();
7209                }
7210            } break;
7211            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7212                if (!isAccessibilityFocused()) {
7213                    return requestAccessibilityFocus();
7214                }
7215            } break;
7216            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7217                if (isAccessibilityFocused()) {
7218                    clearAccessibilityFocus();
7219                    return true;
7220                }
7221            } break;
7222            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7223                if (arguments != null) {
7224                    final int granularity = arguments.getInt(
7225                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7226                    final boolean extendSelection = arguments.getBoolean(
7227                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7228                    return traverseAtGranularity(granularity, true, extendSelection);
7229                }
7230            } break;
7231            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7232                if (arguments != null) {
7233                    final int granularity = arguments.getInt(
7234                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7235                    final boolean extendSelection = arguments.getBoolean(
7236                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7237                    return traverseAtGranularity(granularity, false, extendSelection);
7238                }
7239            } break;
7240            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7241                CharSequence text = getIterableTextForAccessibility();
7242                if (text == null) {
7243                    return false;
7244                }
7245                final int start = (arguments != null) ? arguments.getInt(
7246                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7247                final int end = (arguments != null) ? arguments.getInt(
7248                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7249                // Only cursor position can be specified (selection length == 0)
7250                if ((getAccessibilitySelectionStart() != start
7251                        || getAccessibilitySelectionEnd() != end)
7252                        && (start == end)) {
7253                    setAccessibilitySelection(start, end);
7254                    notifyViewAccessibilityStateChangedIfNeeded();
7255                    return true;
7256                }
7257            } break;
7258        }
7259        return false;
7260    }
7261
7262    private boolean traverseAtGranularity(int granularity, boolean forward,
7263            boolean extendSelection) {
7264        CharSequence text = getIterableTextForAccessibility();
7265        if (text == null || text.length() == 0) {
7266            return false;
7267        }
7268        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7269        if (iterator == null) {
7270            return false;
7271        }
7272        int current = getAccessibilitySelectionEnd();
7273        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7274            current = forward ? 0 : text.length();
7275        }
7276        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7277        if (range == null) {
7278            return false;
7279        }
7280        final int segmentStart = range[0];
7281        final int segmentEnd = range[1];
7282        int selectionStart;
7283        int selectionEnd;
7284        if (extendSelection && isAccessibilitySelectionExtendable()) {
7285            selectionStart = getAccessibilitySelectionStart();
7286            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7287                selectionStart = forward ? segmentStart : segmentEnd;
7288            }
7289            selectionEnd = forward ? segmentEnd : segmentStart;
7290        } else {
7291            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7292        }
7293        setAccessibilitySelection(selectionStart, selectionEnd);
7294        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7295                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7296        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7297        return true;
7298    }
7299
7300    /**
7301     * Gets the text reported for accessibility purposes.
7302     *
7303     * @return The accessibility text.
7304     *
7305     * @hide
7306     */
7307    public CharSequence getIterableTextForAccessibility() {
7308        return getContentDescription();
7309    }
7310
7311    /**
7312     * Gets whether accessibility selection can be extended.
7313     *
7314     * @return If selection is extensible.
7315     *
7316     * @hide
7317     */
7318    public boolean isAccessibilitySelectionExtendable() {
7319        return false;
7320    }
7321
7322    /**
7323     * @hide
7324     */
7325    public int getAccessibilitySelectionStart() {
7326        return mAccessibilityCursorPosition;
7327    }
7328
7329    /**
7330     * @hide
7331     */
7332    public int getAccessibilitySelectionEnd() {
7333        return getAccessibilitySelectionStart();
7334    }
7335
7336    /**
7337     * @hide
7338     */
7339    public void setAccessibilitySelection(int start, int end) {
7340        if (start ==  end && end == mAccessibilityCursorPosition) {
7341            return;
7342        }
7343        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7344            mAccessibilityCursorPosition = start;
7345        } else {
7346            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7347        }
7348        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7349    }
7350
7351    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7352            int fromIndex, int toIndex) {
7353        if (mParent == null) {
7354            return;
7355        }
7356        AccessibilityEvent event = AccessibilityEvent.obtain(
7357                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7358        onInitializeAccessibilityEvent(event);
7359        onPopulateAccessibilityEvent(event);
7360        event.setFromIndex(fromIndex);
7361        event.setToIndex(toIndex);
7362        event.setAction(action);
7363        event.setMovementGranularity(granularity);
7364        mParent.requestSendAccessibilityEvent(this, event);
7365    }
7366
7367    /**
7368     * @hide
7369     */
7370    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7371        switch (granularity) {
7372            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7373                CharSequence text = getIterableTextForAccessibility();
7374                if (text != null && text.length() > 0) {
7375                    CharacterTextSegmentIterator iterator =
7376                        CharacterTextSegmentIterator.getInstance(
7377                                mContext.getResources().getConfiguration().locale);
7378                    iterator.initialize(text.toString());
7379                    return iterator;
7380                }
7381            } break;
7382            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7383                CharSequence text = getIterableTextForAccessibility();
7384                if (text != null && text.length() > 0) {
7385                    WordTextSegmentIterator iterator =
7386                        WordTextSegmentIterator.getInstance(
7387                                mContext.getResources().getConfiguration().locale);
7388                    iterator.initialize(text.toString());
7389                    return iterator;
7390                }
7391            } break;
7392            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7393                CharSequence text = getIterableTextForAccessibility();
7394                if (text != null && text.length() > 0) {
7395                    ParagraphTextSegmentIterator iterator =
7396                        ParagraphTextSegmentIterator.getInstance();
7397                    iterator.initialize(text.toString());
7398                    return iterator;
7399                }
7400            } break;
7401        }
7402        return null;
7403    }
7404
7405    /**
7406     * @hide
7407     */
7408    public void dispatchStartTemporaryDetach() {
7409        clearDisplayList();
7410
7411        onStartTemporaryDetach();
7412    }
7413
7414    /**
7415     * This is called when a container is going to temporarily detach a child, with
7416     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7417     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7418     * {@link #onDetachedFromWindow()} when the container is done.
7419     */
7420    public void onStartTemporaryDetach() {
7421        removeUnsetPressCallback();
7422        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7423    }
7424
7425    /**
7426     * @hide
7427     */
7428    public void dispatchFinishTemporaryDetach() {
7429        onFinishTemporaryDetach();
7430    }
7431
7432    /**
7433     * Called after {@link #onStartTemporaryDetach} when the container is done
7434     * changing the view.
7435     */
7436    public void onFinishTemporaryDetach() {
7437    }
7438
7439    /**
7440     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7441     * for this view's window.  Returns null if the view is not currently attached
7442     * to the window.  Normally you will not need to use this directly, but
7443     * just use the standard high-level event callbacks like
7444     * {@link #onKeyDown(int, KeyEvent)}.
7445     */
7446    public KeyEvent.DispatcherState getKeyDispatcherState() {
7447        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7448    }
7449
7450    /**
7451     * Dispatch a key event before it is processed by any input method
7452     * associated with the view hierarchy.  This can be used to intercept
7453     * key events in special situations before the IME consumes them; a
7454     * typical example would be handling the BACK key to update the application's
7455     * UI instead of allowing the IME to see it and close itself.
7456     *
7457     * @param event The key event to be dispatched.
7458     * @return True if the event was handled, false otherwise.
7459     */
7460    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7461        return onKeyPreIme(event.getKeyCode(), event);
7462    }
7463
7464    /**
7465     * Dispatch a key event to the next view on the focus path. This path runs
7466     * from the top of the view tree down to the currently focused view. If this
7467     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7468     * the next node down the focus path. This method also fires any key
7469     * listeners.
7470     *
7471     * @param event The key event to be dispatched.
7472     * @return True if the event was handled, false otherwise.
7473     */
7474    public boolean dispatchKeyEvent(KeyEvent event) {
7475        if (mInputEventConsistencyVerifier != null) {
7476            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7477        }
7478
7479        // Give any attached key listener a first crack at the event.
7480        //noinspection SimplifiableIfStatement
7481        ListenerInfo li = mListenerInfo;
7482        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7483                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7484            return true;
7485        }
7486
7487        if (event.dispatch(this, mAttachInfo != null
7488                ? mAttachInfo.mKeyDispatchState : null, this)) {
7489            return true;
7490        }
7491
7492        if (mInputEventConsistencyVerifier != null) {
7493            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7494        }
7495        return false;
7496    }
7497
7498    /**
7499     * Dispatches a key shortcut event.
7500     *
7501     * @param event The key event to be dispatched.
7502     * @return True if the event was handled by the view, false otherwise.
7503     */
7504    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7505        return onKeyShortcut(event.getKeyCode(), event);
7506    }
7507
7508    /**
7509     * Pass the touch screen motion event down to the target view, or this
7510     * view if it is the target.
7511     *
7512     * @param event The motion event to be dispatched.
7513     * @return True if the event was handled by the view, false otherwise.
7514     */
7515    public boolean dispatchTouchEvent(MotionEvent event) {
7516        if (mInputEventConsistencyVerifier != null) {
7517            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7518        }
7519
7520        if (onFilterTouchEventForSecurity(event)) {
7521            //noinspection SimplifiableIfStatement
7522            ListenerInfo li = mListenerInfo;
7523            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7524                    && li.mOnTouchListener.onTouch(this, event)) {
7525                return true;
7526            }
7527
7528            if (onTouchEvent(event)) {
7529                return true;
7530            }
7531        }
7532
7533        if (mInputEventConsistencyVerifier != null) {
7534            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7535        }
7536        return false;
7537    }
7538
7539    /**
7540     * Filter the touch event to apply security policies.
7541     *
7542     * @param event The motion event to be filtered.
7543     * @return True if the event should be dispatched, false if the event should be dropped.
7544     *
7545     * @see #getFilterTouchesWhenObscured
7546     */
7547    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7548        //noinspection RedundantIfStatement
7549        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7550                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7551            // Window is obscured, drop this touch.
7552            return false;
7553        }
7554        return true;
7555    }
7556
7557    /**
7558     * Pass a trackball motion event down to the focused view.
7559     *
7560     * @param event The motion event to be dispatched.
7561     * @return True if the event was handled by the view, false otherwise.
7562     */
7563    public boolean dispatchTrackballEvent(MotionEvent event) {
7564        if (mInputEventConsistencyVerifier != null) {
7565            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7566        }
7567
7568        return onTrackballEvent(event);
7569    }
7570
7571    /**
7572     * Dispatch a generic motion event.
7573     * <p>
7574     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7575     * are delivered to the view under the pointer.  All other generic motion events are
7576     * delivered to the focused view.  Hover events are handled specially and are delivered
7577     * to {@link #onHoverEvent(MotionEvent)}.
7578     * </p>
7579     *
7580     * @param event The motion event to be dispatched.
7581     * @return True if the event was handled by the view, false otherwise.
7582     */
7583    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7584        if (mInputEventConsistencyVerifier != null) {
7585            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7586        }
7587
7588        final int source = event.getSource();
7589        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7590            final int action = event.getAction();
7591            if (action == MotionEvent.ACTION_HOVER_ENTER
7592                    || action == MotionEvent.ACTION_HOVER_MOVE
7593                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7594                if (dispatchHoverEvent(event)) {
7595                    return true;
7596                }
7597            } else if (dispatchGenericPointerEvent(event)) {
7598                return true;
7599            }
7600        } else if (dispatchGenericFocusedEvent(event)) {
7601            return true;
7602        }
7603
7604        if (dispatchGenericMotionEventInternal(event)) {
7605            return true;
7606        }
7607
7608        if (mInputEventConsistencyVerifier != null) {
7609            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7610        }
7611        return false;
7612    }
7613
7614    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7615        //noinspection SimplifiableIfStatement
7616        ListenerInfo li = mListenerInfo;
7617        if (li != null && li.mOnGenericMotionListener != null
7618                && (mViewFlags & ENABLED_MASK) == ENABLED
7619                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7620            return true;
7621        }
7622
7623        if (onGenericMotionEvent(event)) {
7624            return true;
7625        }
7626
7627        if (mInputEventConsistencyVerifier != null) {
7628            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7629        }
7630        return false;
7631    }
7632
7633    /**
7634     * Dispatch a hover event.
7635     * <p>
7636     * Do not call this method directly.
7637     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7638     * </p>
7639     *
7640     * @param event The motion event to be dispatched.
7641     * @return True if the event was handled by the view, false otherwise.
7642     */
7643    protected boolean dispatchHoverEvent(MotionEvent event) {
7644        ListenerInfo li = mListenerInfo;
7645        //noinspection SimplifiableIfStatement
7646        if (li != null && li.mOnHoverListener != null
7647                && (mViewFlags & ENABLED_MASK) == ENABLED
7648                && li.mOnHoverListener.onHover(this, event)) {
7649            return true;
7650        }
7651
7652        return onHoverEvent(event);
7653    }
7654
7655    /**
7656     * Returns true if the view has a child to which it has recently sent
7657     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7658     * it does not have a hovered child, then it must be the innermost hovered view.
7659     * @hide
7660     */
7661    protected boolean hasHoveredChild() {
7662        return false;
7663    }
7664
7665    /**
7666     * Dispatch a generic motion event to the view under the first pointer.
7667     * <p>
7668     * Do not call this method directly.
7669     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7670     * </p>
7671     *
7672     * @param event The motion event to be dispatched.
7673     * @return True if the event was handled by the view, false otherwise.
7674     */
7675    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7676        return false;
7677    }
7678
7679    /**
7680     * Dispatch a generic motion event to the currently focused view.
7681     * <p>
7682     * Do not call this method directly.
7683     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7684     * </p>
7685     *
7686     * @param event The motion event to be dispatched.
7687     * @return True if the event was handled by the view, false otherwise.
7688     */
7689    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7690        return false;
7691    }
7692
7693    /**
7694     * Dispatch a pointer event.
7695     * <p>
7696     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7697     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7698     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7699     * and should not be expected to handle other pointing device features.
7700     * </p>
7701     *
7702     * @param event The motion event to be dispatched.
7703     * @return True if the event was handled by the view, false otherwise.
7704     * @hide
7705     */
7706    public final boolean dispatchPointerEvent(MotionEvent event) {
7707        if (event.isTouchEvent()) {
7708            return dispatchTouchEvent(event);
7709        } else {
7710            return dispatchGenericMotionEvent(event);
7711        }
7712    }
7713
7714    /**
7715     * Called when the window containing this view gains or loses window focus.
7716     * ViewGroups should override to route to their children.
7717     *
7718     * @param hasFocus True if the window containing this view now has focus,
7719     *        false otherwise.
7720     */
7721    public void dispatchWindowFocusChanged(boolean hasFocus) {
7722        onWindowFocusChanged(hasFocus);
7723    }
7724
7725    /**
7726     * Called when the window containing this view gains or loses focus.  Note
7727     * that this is separate from view focus: to receive key events, both
7728     * your view and its window must have focus.  If a window is displayed
7729     * on top of yours that takes input focus, then your own window will lose
7730     * focus but the view focus will remain unchanged.
7731     *
7732     * @param hasWindowFocus True if the window containing this view now has
7733     *        focus, false otherwise.
7734     */
7735    public void onWindowFocusChanged(boolean hasWindowFocus) {
7736        InputMethodManager imm = InputMethodManager.peekInstance();
7737        if (!hasWindowFocus) {
7738            if (isPressed()) {
7739                setPressed(false);
7740            }
7741            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7742                imm.focusOut(this);
7743            }
7744            removeLongPressCallback();
7745            removeTapCallback();
7746            onFocusLost();
7747        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7748            imm.focusIn(this);
7749        }
7750        refreshDrawableState();
7751    }
7752
7753    /**
7754     * Returns true if this view is in a window that currently has window focus.
7755     * Note that this is not the same as the view itself having focus.
7756     *
7757     * @return True if this view is in a window that currently has window focus.
7758     */
7759    public boolean hasWindowFocus() {
7760        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7761    }
7762
7763    /**
7764     * Dispatch a view visibility change down the view hierarchy.
7765     * ViewGroups should override to route to their children.
7766     * @param changedView The view whose visibility changed. Could be 'this' or
7767     * an ancestor view.
7768     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7769     * {@link #INVISIBLE} or {@link #GONE}.
7770     */
7771    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7772        onVisibilityChanged(changedView, visibility);
7773    }
7774
7775    /**
7776     * Called when the visibility of the view or an ancestor of the view is changed.
7777     * @param changedView The view whose visibility changed. Could be 'this' or
7778     * an ancestor view.
7779     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7780     * {@link #INVISIBLE} or {@link #GONE}.
7781     */
7782    protected void onVisibilityChanged(View changedView, int visibility) {
7783        if (visibility == VISIBLE) {
7784            if (mAttachInfo != null) {
7785                initialAwakenScrollBars();
7786            } else {
7787                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7788            }
7789        }
7790    }
7791
7792    /**
7793     * Dispatch a hint about whether this view is displayed. For instance, when
7794     * a View moves out of the screen, it might receives a display hint indicating
7795     * the view is not displayed. Applications should not <em>rely</em> on this hint
7796     * as there is no guarantee that they will receive one.
7797     *
7798     * @param hint A hint about whether or not this view is displayed:
7799     * {@link #VISIBLE} or {@link #INVISIBLE}.
7800     */
7801    public void dispatchDisplayHint(int hint) {
7802        onDisplayHint(hint);
7803    }
7804
7805    /**
7806     * Gives this view a hint about whether is displayed or not. For instance, when
7807     * a View moves out of the screen, it might receives a display hint indicating
7808     * the view is not displayed. Applications should not <em>rely</em> on this hint
7809     * as there is no guarantee that they will receive one.
7810     *
7811     * @param hint A hint about whether or not this view is displayed:
7812     * {@link #VISIBLE} or {@link #INVISIBLE}.
7813     */
7814    protected void onDisplayHint(int hint) {
7815    }
7816
7817    /**
7818     * Dispatch a window visibility change down the view hierarchy.
7819     * ViewGroups should override to route to their children.
7820     *
7821     * @param visibility The new visibility of the window.
7822     *
7823     * @see #onWindowVisibilityChanged(int)
7824     */
7825    public void dispatchWindowVisibilityChanged(int visibility) {
7826        onWindowVisibilityChanged(visibility);
7827    }
7828
7829    /**
7830     * Called when the window containing has change its visibility
7831     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7832     * that this tells you whether or not your window is being made visible
7833     * to the window manager; this does <em>not</em> tell you whether or not
7834     * your window is obscured by other windows on the screen, even if it
7835     * is itself visible.
7836     *
7837     * @param visibility The new visibility of the window.
7838     */
7839    protected void onWindowVisibilityChanged(int visibility) {
7840        if (visibility == VISIBLE) {
7841            initialAwakenScrollBars();
7842        }
7843    }
7844
7845    /**
7846     * Returns the current visibility of the window this view is attached to
7847     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7848     *
7849     * @return Returns the current visibility of the view's window.
7850     */
7851    public int getWindowVisibility() {
7852        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7853    }
7854
7855    /**
7856     * Retrieve the overall visible display size in which the window this view is
7857     * attached to has been positioned in.  This takes into account screen
7858     * decorations above the window, for both cases where the window itself
7859     * is being position inside of them or the window is being placed under
7860     * then and covered insets are used for the window to position its content
7861     * inside.  In effect, this tells you the available area where content can
7862     * be placed and remain visible to users.
7863     *
7864     * <p>This function requires an IPC back to the window manager to retrieve
7865     * the requested information, so should not be used in performance critical
7866     * code like drawing.
7867     *
7868     * @param outRect Filled in with the visible display frame.  If the view
7869     * is not attached to a window, this is simply the raw display size.
7870     */
7871    public void getWindowVisibleDisplayFrame(Rect outRect) {
7872        if (mAttachInfo != null) {
7873            try {
7874                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7875            } catch (RemoteException e) {
7876                return;
7877            }
7878            // XXX This is really broken, and probably all needs to be done
7879            // in the window manager, and we need to know more about whether
7880            // we want the area behind or in front of the IME.
7881            final Rect insets = mAttachInfo.mVisibleInsets;
7882            outRect.left += insets.left;
7883            outRect.top += insets.top;
7884            outRect.right -= insets.right;
7885            outRect.bottom -= insets.bottom;
7886            return;
7887        }
7888        // The view is not attached to a display so we don't have a context.
7889        // Make a best guess about the display size.
7890        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7891        d.getRectSize(outRect);
7892    }
7893
7894    /**
7895     * Dispatch a notification about a resource configuration change down
7896     * the view hierarchy.
7897     * ViewGroups should override to route to their children.
7898     *
7899     * @param newConfig The new resource configuration.
7900     *
7901     * @see #onConfigurationChanged(android.content.res.Configuration)
7902     */
7903    public void dispatchConfigurationChanged(Configuration newConfig) {
7904        onConfigurationChanged(newConfig);
7905    }
7906
7907    /**
7908     * Called when the current configuration of the resources being used
7909     * by the application have changed.  You can use this to decide when
7910     * to reload resources that can changed based on orientation and other
7911     * configuration characterstics.  You only need to use this if you are
7912     * not relying on the normal {@link android.app.Activity} mechanism of
7913     * recreating the activity instance upon a configuration change.
7914     *
7915     * @param newConfig The new resource configuration.
7916     */
7917    protected void onConfigurationChanged(Configuration newConfig) {
7918    }
7919
7920    /**
7921     * Private function to aggregate all per-view attributes in to the view
7922     * root.
7923     */
7924    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7925        performCollectViewAttributes(attachInfo, visibility);
7926    }
7927
7928    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7929        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7930            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7931                attachInfo.mKeepScreenOn = true;
7932            }
7933            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7934            ListenerInfo li = mListenerInfo;
7935            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7936                attachInfo.mHasSystemUiListeners = true;
7937            }
7938        }
7939    }
7940
7941    void needGlobalAttributesUpdate(boolean force) {
7942        final AttachInfo ai = mAttachInfo;
7943        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7944            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7945                    || ai.mHasSystemUiListeners) {
7946                ai.mRecomputeGlobalAttributes = true;
7947            }
7948        }
7949    }
7950
7951    /**
7952     * Returns whether the device is currently in touch mode.  Touch mode is entered
7953     * once the user begins interacting with the device by touch, and affects various
7954     * things like whether focus is always visible to the user.
7955     *
7956     * @return Whether the device is in touch mode.
7957     */
7958    @ViewDebug.ExportedProperty
7959    public boolean isInTouchMode() {
7960        if (mAttachInfo != null) {
7961            return mAttachInfo.mInTouchMode;
7962        } else {
7963            return ViewRootImpl.isInTouchMode();
7964        }
7965    }
7966
7967    /**
7968     * Returns the context the view is running in, through which it can
7969     * access the current theme, resources, etc.
7970     *
7971     * @return The view's Context.
7972     */
7973    @ViewDebug.CapturedViewProperty
7974    public final Context getContext() {
7975        return mContext;
7976    }
7977
7978    /**
7979     * Handle a key event before it is processed by any input method
7980     * associated with the view hierarchy.  This can be used to intercept
7981     * key events in special situations before the IME consumes them; a
7982     * typical example would be handling the BACK key to update the application's
7983     * UI instead of allowing the IME to see it and close itself.
7984     *
7985     * @param keyCode The value in event.getKeyCode().
7986     * @param event Description of the key event.
7987     * @return If you handled the event, return true. If you want to allow the
7988     *         event to be handled by the next receiver, return false.
7989     */
7990    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7991        return false;
7992    }
7993
7994    /**
7995     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7996     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7997     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7998     * is released, if the view is enabled and clickable.
7999     *
8000     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8001     * although some may elect to do so in some situations. Do not rely on this to
8002     * catch software key presses.
8003     *
8004     * @param keyCode A key code that represents the button pressed, from
8005     *                {@link android.view.KeyEvent}.
8006     * @param event   The KeyEvent object that defines the button action.
8007     */
8008    public boolean onKeyDown(int keyCode, KeyEvent event) {
8009        boolean result = false;
8010
8011        if (KeyEvent.isConfirmKey(event.getKeyCode())) {
8012            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8013                return true;
8014            }
8015            // Long clickable items don't necessarily have to be clickable
8016            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8017                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8018                    (event.getRepeatCount() == 0)) {
8019                setPressed(true);
8020                checkForLongClick(0);
8021                return true;
8022            }
8023        }
8024        return result;
8025    }
8026
8027    /**
8028     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8029     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8030     * the event).
8031     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8032     * although some may elect to do so in some situations. Do not rely on this to
8033     * catch software key presses.
8034     */
8035    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8036        return false;
8037    }
8038
8039    /**
8040     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8041     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8042     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8043     * {@link KeyEvent#KEYCODE_ENTER} is released.
8044     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8045     * although some may elect to do so in some situations. Do not rely on this to
8046     * catch software key presses.
8047     *
8048     * @param keyCode A key code that represents the button pressed, from
8049     *                {@link android.view.KeyEvent}.
8050     * @param event   The KeyEvent object that defines the button action.
8051     */
8052    public boolean onKeyUp(int keyCode, KeyEvent event) {
8053        boolean result = false;
8054
8055        switch (keyCode) {
8056            case KeyEvent.KEYCODE_DPAD_CENTER:
8057            case KeyEvent.KEYCODE_ENTER: {
8058                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8059                    return true;
8060                }
8061                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8062                    setPressed(false);
8063
8064                    if (!mHasPerformedLongPress) {
8065                        // This is a tap, so remove the longpress check
8066                        removeLongPressCallback();
8067
8068                        result = performClick();
8069                    }
8070                }
8071                break;
8072            }
8073        }
8074        return result;
8075    }
8076
8077    /**
8078     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8079     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8080     * the event).
8081     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8082     * although some may elect to do so in some situations. Do not rely on this to
8083     * catch software key presses.
8084     *
8085     * @param keyCode     A key code that represents the button pressed, from
8086     *                    {@link android.view.KeyEvent}.
8087     * @param repeatCount The number of times the action was made.
8088     * @param event       The KeyEvent object that defines the button action.
8089     */
8090    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8091        return false;
8092    }
8093
8094    /**
8095     * Called on the focused view when a key shortcut event is not handled.
8096     * Override this method to implement local key shortcuts for the View.
8097     * Key shortcuts can also be implemented by setting the
8098     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8099     *
8100     * @param keyCode The value in event.getKeyCode().
8101     * @param event Description of the key event.
8102     * @return If you handled the event, return true. If you want to allow the
8103     *         event to be handled by the next receiver, return false.
8104     */
8105    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8106        return false;
8107    }
8108
8109    /**
8110     * Check whether the called view is a text editor, in which case it
8111     * would make sense to automatically display a soft input window for
8112     * it.  Subclasses should override this if they implement
8113     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8114     * a call on that method would return a non-null InputConnection, and
8115     * they are really a first-class editor that the user would normally
8116     * start typing on when the go into a window containing your view.
8117     *
8118     * <p>The default implementation always returns false.  This does
8119     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8120     * will not be called or the user can not otherwise perform edits on your
8121     * view; it is just a hint to the system that this is not the primary
8122     * purpose of this view.
8123     *
8124     * @return Returns true if this view is a text editor, else false.
8125     */
8126    public boolean onCheckIsTextEditor() {
8127        return false;
8128    }
8129
8130    /**
8131     * Create a new InputConnection for an InputMethod to interact
8132     * with the view.  The default implementation returns null, since it doesn't
8133     * support input methods.  You can override this to implement such support.
8134     * This is only needed for views that take focus and text input.
8135     *
8136     * <p>When implementing this, you probably also want to implement
8137     * {@link #onCheckIsTextEditor()} to indicate you will return a
8138     * non-null InputConnection.
8139     *
8140     * @param outAttrs Fill in with attribute information about the connection.
8141     */
8142    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8143        return null;
8144    }
8145
8146    /**
8147     * Called by the {@link android.view.inputmethod.InputMethodManager}
8148     * when a view who is not the current
8149     * input connection target is trying to make a call on the manager.  The
8150     * default implementation returns false; you can override this to return
8151     * true for certain views if you are performing InputConnection proxying
8152     * to them.
8153     * @param view The View that is making the InputMethodManager call.
8154     * @return Return true to allow the call, false to reject.
8155     */
8156    public boolean checkInputConnectionProxy(View view) {
8157        return false;
8158    }
8159
8160    /**
8161     * Show the context menu for this view. It is not safe to hold on to the
8162     * menu after returning from this method.
8163     *
8164     * You should normally not overload this method. Overload
8165     * {@link #onCreateContextMenu(ContextMenu)} or define an
8166     * {@link OnCreateContextMenuListener} to add items to the context menu.
8167     *
8168     * @param menu The context menu to populate
8169     */
8170    public void createContextMenu(ContextMenu menu) {
8171        ContextMenuInfo menuInfo = getContextMenuInfo();
8172
8173        // Sets the current menu info so all items added to menu will have
8174        // my extra info set.
8175        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8176
8177        onCreateContextMenu(menu);
8178        ListenerInfo li = mListenerInfo;
8179        if (li != null && li.mOnCreateContextMenuListener != null) {
8180            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8181        }
8182
8183        // Clear the extra information so subsequent items that aren't mine don't
8184        // have my extra info.
8185        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8186
8187        if (mParent != null) {
8188            mParent.createContextMenu(menu);
8189        }
8190    }
8191
8192    /**
8193     * Views should implement this if they have extra information to associate
8194     * with the context menu. The return result is supplied as a parameter to
8195     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8196     * callback.
8197     *
8198     * @return Extra information about the item for which the context menu
8199     *         should be shown. This information will vary across different
8200     *         subclasses of View.
8201     */
8202    protected ContextMenuInfo getContextMenuInfo() {
8203        return null;
8204    }
8205
8206    /**
8207     * Views should implement this if the view itself is going to add items to
8208     * the context menu.
8209     *
8210     * @param menu the context menu to populate
8211     */
8212    protected void onCreateContextMenu(ContextMenu menu) {
8213    }
8214
8215    /**
8216     * Implement this method to handle trackball motion events.  The
8217     * <em>relative</em> movement of the trackball since the last event
8218     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8219     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8220     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8221     * they will often be fractional values, representing the more fine-grained
8222     * movement information available from a trackball).
8223     *
8224     * @param event The motion event.
8225     * @return True if the event was handled, false otherwise.
8226     */
8227    public boolean onTrackballEvent(MotionEvent event) {
8228        return false;
8229    }
8230
8231    /**
8232     * Implement this method to handle generic motion events.
8233     * <p>
8234     * Generic motion events describe joystick movements, mouse hovers, track pad
8235     * touches, scroll wheel movements and other input events.  The
8236     * {@link MotionEvent#getSource() source} of the motion event specifies
8237     * the class of input that was received.  Implementations of this method
8238     * must examine the bits in the source before processing the event.
8239     * The following code example shows how this is done.
8240     * </p><p>
8241     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8242     * are delivered to the view under the pointer.  All other generic motion events are
8243     * delivered to the focused view.
8244     * </p>
8245     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8246     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8247     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8248     *             // process the joystick movement...
8249     *             return true;
8250     *         }
8251     *     }
8252     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8253     *         switch (event.getAction()) {
8254     *             case MotionEvent.ACTION_HOVER_MOVE:
8255     *                 // process the mouse hover movement...
8256     *                 return true;
8257     *             case MotionEvent.ACTION_SCROLL:
8258     *                 // process the scroll wheel movement...
8259     *                 return true;
8260     *         }
8261     *     }
8262     *     return super.onGenericMotionEvent(event);
8263     * }</pre>
8264     *
8265     * @param event The generic motion event being processed.
8266     * @return True if the event was handled, false otherwise.
8267     */
8268    public boolean onGenericMotionEvent(MotionEvent event) {
8269        return false;
8270    }
8271
8272    /**
8273     * Implement this method to handle hover events.
8274     * <p>
8275     * This method is called whenever a pointer is hovering into, over, or out of the
8276     * bounds of a view and the view is not currently being touched.
8277     * Hover events are represented as pointer events with action
8278     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8279     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8280     * </p>
8281     * <ul>
8282     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8283     * when the pointer enters the bounds of the view.</li>
8284     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8285     * when the pointer has already entered the bounds of the view and has moved.</li>
8286     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8287     * when the pointer has exited the bounds of the view or when the pointer is
8288     * about to go down due to a button click, tap, or similar user action that
8289     * causes the view to be touched.</li>
8290     * </ul>
8291     * <p>
8292     * The view should implement this method to return true to indicate that it is
8293     * handling the hover event, such as by changing its drawable state.
8294     * </p><p>
8295     * The default implementation calls {@link #setHovered} to update the hovered state
8296     * of the view when a hover enter or hover exit event is received, if the view
8297     * is enabled and is clickable.  The default implementation also sends hover
8298     * accessibility events.
8299     * </p>
8300     *
8301     * @param event The motion event that describes the hover.
8302     * @return True if the view handled the hover event.
8303     *
8304     * @see #isHovered
8305     * @see #setHovered
8306     * @see #onHoverChanged
8307     */
8308    public boolean onHoverEvent(MotionEvent event) {
8309        // The root view may receive hover (or touch) events that are outside the bounds of
8310        // the window.  This code ensures that we only send accessibility events for
8311        // hovers that are actually within the bounds of the root view.
8312        final int action = event.getActionMasked();
8313        if (!mSendingHoverAccessibilityEvents) {
8314            if ((action == MotionEvent.ACTION_HOVER_ENTER
8315                    || action == MotionEvent.ACTION_HOVER_MOVE)
8316                    && !hasHoveredChild()
8317                    && pointInView(event.getX(), event.getY())) {
8318                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8319                mSendingHoverAccessibilityEvents = true;
8320            }
8321        } else {
8322            if (action == MotionEvent.ACTION_HOVER_EXIT
8323                    || (action == MotionEvent.ACTION_MOVE
8324                            && !pointInView(event.getX(), event.getY()))) {
8325                mSendingHoverAccessibilityEvents = false;
8326                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8327                // If the window does not have input focus we take away accessibility
8328                // focus as soon as the user stop hovering over the view.
8329                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8330                    getViewRootImpl().setAccessibilityFocus(null, null);
8331                }
8332            }
8333        }
8334
8335        if (isHoverable()) {
8336            switch (action) {
8337                case MotionEvent.ACTION_HOVER_ENTER:
8338                    setHovered(true);
8339                    break;
8340                case MotionEvent.ACTION_HOVER_EXIT:
8341                    setHovered(false);
8342                    break;
8343            }
8344
8345            // Dispatch the event to onGenericMotionEvent before returning true.
8346            // This is to provide compatibility with existing applications that
8347            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8348            // break because of the new default handling for hoverable views
8349            // in onHoverEvent.
8350            // Note that onGenericMotionEvent will be called by default when
8351            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8352            dispatchGenericMotionEventInternal(event);
8353            // The event was already handled by calling setHovered(), so always
8354            // return true.
8355            return true;
8356        }
8357
8358        return false;
8359    }
8360
8361    /**
8362     * Returns true if the view should handle {@link #onHoverEvent}
8363     * by calling {@link #setHovered} to change its hovered state.
8364     *
8365     * @return True if the view is hoverable.
8366     */
8367    private boolean isHoverable() {
8368        final int viewFlags = mViewFlags;
8369        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8370            return false;
8371        }
8372
8373        return (viewFlags & CLICKABLE) == CLICKABLE
8374                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8375    }
8376
8377    /**
8378     * Returns true if the view is currently hovered.
8379     *
8380     * @return True if the view is currently hovered.
8381     *
8382     * @see #setHovered
8383     * @see #onHoverChanged
8384     */
8385    @ViewDebug.ExportedProperty
8386    public boolean isHovered() {
8387        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8388    }
8389
8390    /**
8391     * Sets whether the view is currently hovered.
8392     * <p>
8393     * Calling this method also changes the drawable state of the view.  This
8394     * enables the view to react to hover by using different drawable resources
8395     * to change its appearance.
8396     * </p><p>
8397     * The {@link #onHoverChanged} method is called when the hovered state changes.
8398     * </p>
8399     *
8400     * @param hovered True if the view is hovered.
8401     *
8402     * @see #isHovered
8403     * @see #onHoverChanged
8404     */
8405    public void setHovered(boolean hovered) {
8406        if (hovered) {
8407            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8408                mPrivateFlags |= PFLAG_HOVERED;
8409                refreshDrawableState();
8410                onHoverChanged(true);
8411            }
8412        } else {
8413            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8414                mPrivateFlags &= ~PFLAG_HOVERED;
8415                refreshDrawableState();
8416                onHoverChanged(false);
8417            }
8418        }
8419    }
8420
8421    /**
8422     * Implement this method to handle hover state changes.
8423     * <p>
8424     * This method is called whenever the hover state changes as a result of a
8425     * call to {@link #setHovered}.
8426     * </p>
8427     *
8428     * @param hovered The current hover state, as returned by {@link #isHovered}.
8429     *
8430     * @see #isHovered
8431     * @see #setHovered
8432     */
8433    public void onHoverChanged(boolean hovered) {
8434    }
8435
8436    /**
8437     * Implement this method to handle touch screen motion events.
8438     * <p>
8439     * If this method is used to detect click actions, it is recommended that
8440     * the actions be performed by implementing and calling
8441     * {@link #performClick()}. This will ensure consistent system behavior,
8442     * including:
8443     * <ul>
8444     * <li>obeying click sound preferences
8445     * <li>dispatching OnClickListener calls
8446     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8447     * accessibility features are enabled
8448     * </ul>
8449     *
8450     * @param event The motion event.
8451     * @return True if the event was handled, false otherwise.
8452     */
8453    public boolean onTouchEvent(MotionEvent event) {
8454        final int viewFlags = mViewFlags;
8455
8456        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8457            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8458                setPressed(false);
8459            }
8460            // A disabled view that is clickable still consumes the touch
8461            // events, it just doesn't respond to them.
8462            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8463                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8464        }
8465
8466        if (mTouchDelegate != null) {
8467            if (mTouchDelegate.onTouchEvent(event)) {
8468                return true;
8469            }
8470        }
8471
8472        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8473                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8474            switch (event.getAction()) {
8475                case MotionEvent.ACTION_UP:
8476                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8477                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8478                        // take focus if we don't have it already and we should in
8479                        // touch mode.
8480                        boolean focusTaken = false;
8481                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8482                            focusTaken = requestFocus();
8483                        }
8484
8485                        if (prepressed) {
8486                            // The button is being released before we actually
8487                            // showed it as pressed.  Make it show the pressed
8488                            // state now (before scheduling the click) to ensure
8489                            // the user sees it.
8490                            setPressed(true);
8491                       }
8492
8493                        if (!mHasPerformedLongPress) {
8494                            // This is a tap, so remove the longpress check
8495                            removeLongPressCallback();
8496
8497                            // Only perform take click actions if we were in the pressed state
8498                            if (!focusTaken) {
8499                                // Use a Runnable and post this rather than calling
8500                                // performClick directly. This lets other visual state
8501                                // of the view update before click actions start.
8502                                if (mPerformClick == null) {
8503                                    mPerformClick = new PerformClick();
8504                                }
8505                                if (!post(mPerformClick)) {
8506                                    performClick();
8507                                }
8508                            }
8509                        }
8510
8511                        if (mUnsetPressedState == null) {
8512                            mUnsetPressedState = new UnsetPressedState();
8513                        }
8514
8515                        if (prepressed) {
8516                            postDelayed(mUnsetPressedState,
8517                                    ViewConfiguration.getPressedStateDuration());
8518                        } else if (!post(mUnsetPressedState)) {
8519                            // If the post failed, unpress right now
8520                            mUnsetPressedState.run();
8521                        }
8522                        removeTapCallback();
8523                    }
8524                    break;
8525
8526                case MotionEvent.ACTION_DOWN:
8527                    mHasPerformedLongPress = false;
8528
8529                    if (performButtonActionOnTouchDown(event)) {
8530                        break;
8531                    }
8532
8533                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8534                    boolean isInScrollingContainer = isInScrollingContainer();
8535
8536                    // For views inside a scrolling container, delay the pressed feedback for
8537                    // a short period in case this is a scroll.
8538                    if (isInScrollingContainer) {
8539                        mPrivateFlags |= PFLAG_PREPRESSED;
8540                        if (mPendingCheckForTap == null) {
8541                            mPendingCheckForTap = new CheckForTap();
8542                        }
8543                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8544                    } else {
8545                        // Not inside a scrolling container, so show the feedback right away
8546                        setPressed(true);
8547                        checkForLongClick(0);
8548                    }
8549                    break;
8550
8551                case MotionEvent.ACTION_CANCEL:
8552                    setPressed(false);
8553                    removeTapCallback();
8554                    removeLongPressCallback();
8555                    break;
8556
8557                case MotionEvent.ACTION_MOVE:
8558                    final int x = (int) event.getX();
8559                    final int y = (int) event.getY();
8560
8561                    // Be lenient about moving outside of buttons
8562                    if (!pointInView(x, y, mTouchSlop)) {
8563                        // Outside button
8564                        removeTapCallback();
8565                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8566                            // Remove any future long press/tap checks
8567                            removeLongPressCallback();
8568
8569                            setPressed(false);
8570                        }
8571                    }
8572                    break;
8573            }
8574            return true;
8575        }
8576
8577        return false;
8578    }
8579
8580    /**
8581     * @hide
8582     */
8583    public boolean isInScrollingContainer() {
8584        ViewParent p = getParent();
8585        while (p != null && p instanceof ViewGroup) {
8586            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8587                return true;
8588            }
8589            p = p.getParent();
8590        }
8591        return false;
8592    }
8593
8594    /**
8595     * Remove the longpress detection timer.
8596     */
8597    private void removeLongPressCallback() {
8598        if (mPendingCheckForLongPress != null) {
8599          removeCallbacks(mPendingCheckForLongPress);
8600        }
8601    }
8602
8603    /**
8604     * Remove the pending click action
8605     */
8606    private void removePerformClickCallback() {
8607        if (mPerformClick != null) {
8608            removeCallbacks(mPerformClick);
8609        }
8610    }
8611
8612    /**
8613     * Remove the prepress detection timer.
8614     */
8615    private void removeUnsetPressCallback() {
8616        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8617            setPressed(false);
8618            removeCallbacks(mUnsetPressedState);
8619        }
8620    }
8621
8622    /**
8623     * Remove the tap detection timer.
8624     */
8625    private void removeTapCallback() {
8626        if (mPendingCheckForTap != null) {
8627            mPrivateFlags &= ~PFLAG_PREPRESSED;
8628            removeCallbacks(mPendingCheckForTap);
8629        }
8630    }
8631
8632    /**
8633     * Cancels a pending long press.  Your subclass can use this if you
8634     * want the context menu to come up if the user presses and holds
8635     * at the same place, but you don't want it to come up if they press
8636     * and then move around enough to cause scrolling.
8637     */
8638    public void cancelLongPress() {
8639        removeLongPressCallback();
8640
8641        /*
8642         * The prepressed state handled by the tap callback is a display
8643         * construct, but the tap callback will post a long press callback
8644         * less its own timeout. Remove it here.
8645         */
8646        removeTapCallback();
8647    }
8648
8649    /**
8650     * Remove the pending callback for sending a
8651     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8652     */
8653    private void removeSendViewScrolledAccessibilityEventCallback() {
8654        if (mSendViewScrolledAccessibilityEvent != null) {
8655            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8656            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8657        }
8658    }
8659
8660    /**
8661     * Sets the TouchDelegate for this View.
8662     */
8663    public void setTouchDelegate(TouchDelegate delegate) {
8664        mTouchDelegate = delegate;
8665    }
8666
8667    /**
8668     * Gets the TouchDelegate for this View.
8669     */
8670    public TouchDelegate getTouchDelegate() {
8671        return mTouchDelegate;
8672    }
8673
8674    /**
8675     * Set flags controlling behavior of this view.
8676     *
8677     * @param flags Constant indicating the value which should be set
8678     * @param mask Constant indicating the bit range that should be changed
8679     */
8680    void setFlags(int flags, int mask) {
8681        final boolean accessibilityEnabled =
8682                AccessibilityManager.getInstance(mContext).isEnabled();
8683        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8684
8685        int old = mViewFlags;
8686        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8687
8688        int changed = mViewFlags ^ old;
8689        if (changed == 0) {
8690            return;
8691        }
8692        int privateFlags = mPrivateFlags;
8693
8694        /* Check if the FOCUSABLE bit has changed */
8695        if (((changed & FOCUSABLE_MASK) != 0) &&
8696                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8697            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8698                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8699                /* Give up focus if we are no longer focusable */
8700                clearFocus();
8701            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8702                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8703                /*
8704                 * Tell the view system that we are now available to take focus
8705                 * if no one else already has it.
8706                 */
8707                if (mParent != null) mParent.focusableViewAvailable(this);
8708            }
8709        }
8710
8711        final int newVisibility = flags & VISIBILITY_MASK;
8712        if (newVisibility == VISIBLE) {
8713            if ((changed & VISIBILITY_MASK) != 0) {
8714                /*
8715                 * If this view is becoming visible, invalidate it in case it changed while
8716                 * it was not visible. Marking it drawn ensures that the invalidation will
8717                 * go through.
8718                 */
8719                mPrivateFlags |= PFLAG_DRAWN;
8720                invalidate(true);
8721
8722                needGlobalAttributesUpdate(true);
8723
8724                // a view becoming visible is worth notifying the parent
8725                // about in case nothing has focus.  even if this specific view
8726                // isn't focusable, it may contain something that is, so let
8727                // the root view try to give this focus if nothing else does.
8728                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8729                    mParent.focusableViewAvailable(this);
8730                }
8731            }
8732        }
8733
8734        /* Check if the GONE bit has changed */
8735        if ((changed & GONE) != 0) {
8736            needGlobalAttributesUpdate(false);
8737            requestLayout();
8738
8739            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8740                if (hasFocus()) clearFocus();
8741                clearAccessibilityFocus();
8742                destroyDrawingCache();
8743                if (mParent instanceof View) {
8744                    // GONE views noop invalidation, so invalidate the parent
8745                    ((View) mParent).invalidate(true);
8746                }
8747                // Mark the view drawn to ensure that it gets invalidated properly the next
8748                // time it is visible and gets invalidated
8749                mPrivateFlags |= PFLAG_DRAWN;
8750            }
8751            if (mAttachInfo != null) {
8752                mAttachInfo.mViewVisibilityChanged = true;
8753            }
8754        }
8755
8756        /* Check if the VISIBLE bit has changed */
8757        if ((changed & INVISIBLE) != 0) {
8758            needGlobalAttributesUpdate(false);
8759            /*
8760             * If this view is becoming invisible, set the DRAWN flag so that
8761             * the next invalidate() will not be skipped.
8762             */
8763            mPrivateFlags |= PFLAG_DRAWN;
8764
8765            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8766                // root view becoming invisible shouldn't clear focus and accessibility focus
8767                if (getRootView() != this) {
8768                    clearFocus();
8769                    clearAccessibilityFocus();
8770                }
8771            }
8772            if (mAttachInfo != null) {
8773                mAttachInfo.mViewVisibilityChanged = true;
8774            }
8775        }
8776
8777        if ((changed & VISIBILITY_MASK) != 0) {
8778            // If the view is invisible, cleanup its display list to free up resources
8779            if (newVisibility != VISIBLE) {
8780                cleanupDraw();
8781            }
8782
8783            if (mParent instanceof ViewGroup) {
8784                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8785                        (changed & VISIBILITY_MASK), newVisibility);
8786                ((View) mParent).invalidate(true);
8787            } else if (mParent != null) {
8788                mParent.invalidateChild(this, null);
8789            }
8790            dispatchVisibilityChanged(this, newVisibility);
8791        }
8792
8793        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8794            destroyDrawingCache();
8795        }
8796
8797        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8798            destroyDrawingCache();
8799            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8800            invalidateParentCaches();
8801        }
8802
8803        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8804            destroyDrawingCache();
8805            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8806        }
8807
8808        if ((changed & DRAW_MASK) != 0) {
8809            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8810                if (mBackground != null) {
8811                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8812                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8813                } else {
8814                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8815                }
8816            } else {
8817                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8818            }
8819            requestLayout();
8820            invalidate(true);
8821        }
8822
8823        if ((changed & KEEP_SCREEN_ON) != 0) {
8824            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8825                mParent.recomputeViewAttributes(this);
8826            }
8827        }
8828
8829        if (accessibilityEnabled) {
8830            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8831                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8832                if (oldIncludeForAccessibility != includeForAccessibility()) {
8833                    notifySubtreeAccessibilityStateChangedIfNeeded();
8834                } else {
8835                    notifyViewAccessibilityStateChangedIfNeeded();
8836                }
8837            }
8838            if ((changed & ENABLED_MASK) != 0) {
8839                notifyViewAccessibilityStateChangedIfNeeded();
8840            }
8841        }
8842    }
8843
8844    /**
8845     * Change the view's z order in the tree, so it's on top of other sibling
8846     * views. This ordering change may affect layout, if the parent container
8847     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
8848     * to {@link android.os.Build.VERSION_CODES#KEY_LIME_PIE} this
8849     * method should be followed by calls to {@link #requestLayout()} and
8850     * {@link View#invalidate()} on the view's parent to force the parent to redraw
8851     * with the new child ordering.
8852     *
8853     * @see ViewGroup#bringChildToFront(View)
8854     */
8855    public void bringToFront() {
8856        if (mParent != null) {
8857            mParent.bringChildToFront(this);
8858        }
8859    }
8860
8861    /**
8862     * This is called in response to an internal scroll in this view (i.e., the
8863     * view scrolled its own contents). This is typically as a result of
8864     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8865     * called.
8866     *
8867     * @param l Current horizontal scroll origin.
8868     * @param t Current vertical scroll origin.
8869     * @param oldl Previous horizontal scroll origin.
8870     * @param oldt Previous vertical scroll origin.
8871     */
8872    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8873        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8874            postSendViewScrolledAccessibilityEventCallback();
8875        }
8876
8877        mBackgroundSizeChanged = true;
8878
8879        final AttachInfo ai = mAttachInfo;
8880        if (ai != null) {
8881            ai.mViewScrollChanged = true;
8882        }
8883    }
8884
8885    /**
8886     * Interface definition for a callback to be invoked when the layout bounds of a view
8887     * changes due to layout processing.
8888     */
8889    public interface OnLayoutChangeListener {
8890        /**
8891         * Called when the focus state of a view has changed.
8892         *
8893         * @param v The view whose state has changed.
8894         * @param left The new value of the view's left property.
8895         * @param top The new value of the view's top property.
8896         * @param right The new value of the view's right property.
8897         * @param bottom The new value of the view's bottom property.
8898         * @param oldLeft The previous value of the view's left property.
8899         * @param oldTop The previous value of the view's top property.
8900         * @param oldRight The previous value of the view's right property.
8901         * @param oldBottom The previous value of the view's bottom property.
8902         */
8903        void onLayoutChange(View v, int left, int top, int right, int bottom,
8904            int oldLeft, int oldTop, int oldRight, int oldBottom);
8905    }
8906
8907    /**
8908     * This is called during layout when the size of this view has changed. If
8909     * you were just added to the view hierarchy, you're called with the old
8910     * values of 0.
8911     *
8912     * @param w Current width of this view.
8913     * @param h Current height of this view.
8914     * @param oldw Old width of this view.
8915     * @param oldh Old height of this view.
8916     */
8917    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8918    }
8919
8920    /**
8921     * Called by draw to draw the child views. This may be overridden
8922     * by derived classes to gain control just before its children are drawn
8923     * (but after its own view has been drawn).
8924     * @param canvas the canvas on which to draw the view
8925     */
8926    protected void dispatchDraw(Canvas canvas) {
8927
8928    }
8929
8930    /**
8931     * Gets the parent of this view. Note that the parent is a
8932     * ViewParent and not necessarily a View.
8933     *
8934     * @return Parent of this view.
8935     */
8936    public final ViewParent getParent() {
8937        return mParent;
8938    }
8939
8940    /**
8941     * Set the horizontal scrolled position of your view. This will cause a call to
8942     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8943     * invalidated.
8944     * @param value the x position to scroll to
8945     */
8946    public void setScrollX(int value) {
8947        scrollTo(value, mScrollY);
8948    }
8949
8950    /**
8951     * Set the vertical scrolled position of your view. This will cause a call to
8952     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8953     * invalidated.
8954     * @param value the y position to scroll to
8955     */
8956    public void setScrollY(int value) {
8957        scrollTo(mScrollX, value);
8958    }
8959
8960    /**
8961     * Return the scrolled left position of this view. This is the left edge of
8962     * the displayed part of your view. You do not need to draw any pixels
8963     * farther left, since those are outside of the frame of your view on
8964     * screen.
8965     *
8966     * @return The left edge of the displayed part of your view, in pixels.
8967     */
8968    public final int getScrollX() {
8969        return mScrollX;
8970    }
8971
8972    /**
8973     * Return the scrolled top position of this view. This is the top edge of
8974     * the displayed part of your view. You do not need to draw any pixels above
8975     * it, since those are outside of the frame of your view on screen.
8976     *
8977     * @return The top edge of the displayed part of your view, in pixels.
8978     */
8979    public final int getScrollY() {
8980        return mScrollY;
8981    }
8982
8983    /**
8984     * Return the width of the your view.
8985     *
8986     * @return The width of your view, in pixels.
8987     */
8988    @ViewDebug.ExportedProperty(category = "layout")
8989    public final int getWidth() {
8990        return mRight - mLeft;
8991    }
8992
8993    /**
8994     * Return the height of your view.
8995     *
8996     * @return The height of your view, in pixels.
8997     */
8998    @ViewDebug.ExportedProperty(category = "layout")
8999    public final int getHeight() {
9000        return mBottom - mTop;
9001    }
9002
9003    /**
9004     * Return the visible drawing bounds of your view. Fills in the output
9005     * rectangle with the values from getScrollX(), getScrollY(),
9006     * getWidth(), and getHeight(). These bounds do not account for any
9007     * transformation properties currently set on the view, such as
9008     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9009     *
9010     * @param outRect The (scrolled) drawing bounds of the view.
9011     */
9012    public void getDrawingRect(Rect outRect) {
9013        outRect.left = mScrollX;
9014        outRect.top = mScrollY;
9015        outRect.right = mScrollX + (mRight - mLeft);
9016        outRect.bottom = mScrollY + (mBottom - mTop);
9017    }
9018
9019    /**
9020     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9021     * raw width component (that is the result is masked by
9022     * {@link #MEASURED_SIZE_MASK}).
9023     *
9024     * @return The raw measured width of this view.
9025     */
9026    public final int getMeasuredWidth() {
9027        return mMeasuredWidth & MEASURED_SIZE_MASK;
9028    }
9029
9030    /**
9031     * Return the full width measurement information for this view as computed
9032     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9033     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9034     * This should be used during measurement and layout calculations only. Use
9035     * {@link #getWidth()} to see how wide a view is after layout.
9036     *
9037     * @return The measured width of this view as a bit mask.
9038     */
9039    public final int getMeasuredWidthAndState() {
9040        return mMeasuredWidth;
9041    }
9042
9043    /**
9044     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9045     * raw width component (that is the result is masked by
9046     * {@link #MEASURED_SIZE_MASK}).
9047     *
9048     * @return The raw measured height of this view.
9049     */
9050    public final int getMeasuredHeight() {
9051        return mMeasuredHeight & MEASURED_SIZE_MASK;
9052    }
9053
9054    /**
9055     * Return the full height measurement information for this view as computed
9056     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9057     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9058     * This should be used during measurement and layout calculations only. Use
9059     * {@link #getHeight()} to see how wide a view is after layout.
9060     *
9061     * @return The measured width of this view as a bit mask.
9062     */
9063    public final int getMeasuredHeightAndState() {
9064        return mMeasuredHeight;
9065    }
9066
9067    /**
9068     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9069     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9070     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9071     * and the height component is at the shifted bits
9072     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9073     */
9074    public final int getMeasuredState() {
9075        return (mMeasuredWidth&MEASURED_STATE_MASK)
9076                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9077                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9078    }
9079
9080    /**
9081     * The transform matrix of this view, which is calculated based on the current
9082     * roation, scale, and pivot properties.
9083     *
9084     * @see #getRotation()
9085     * @see #getScaleX()
9086     * @see #getScaleY()
9087     * @see #getPivotX()
9088     * @see #getPivotY()
9089     * @return The current transform matrix for the view
9090     */
9091    public Matrix getMatrix() {
9092        if (mTransformationInfo != null) {
9093            updateMatrix();
9094            return mTransformationInfo.mMatrix;
9095        }
9096        return Matrix.IDENTITY_MATRIX;
9097    }
9098
9099    /**
9100     * Utility function to determine if the value is far enough away from zero to be
9101     * considered non-zero.
9102     * @param value A floating point value to check for zero-ness
9103     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9104     */
9105    private static boolean nonzero(float value) {
9106        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9107    }
9108
9109    /**
9110     * Returns true if the transform matrix is the identity matrix.
9111     * Recomputes the matrix if necessary.
9112     *
9113     * @return True if the transform matrix is the identity matrix, false otherwise.
9114     */
9115    final boolean hasIdentityMatrix() {
9116        if (mTransformationInfo != null) {
9117            updateMatrix();
9118            return mTransformationInfo.mMatrixIsIdentity;
9119        }
9120        return true;
9121    }
9122
9123    void ensureTransformationInfo() {
9124        if (mTransformationInfo == null) {
9125            mTransformationInfo = new TransformationInfo();
9126        }
9127    }
9128
9129    /**
9130     * Recomputes the transform matrix if necessary.
9131     */
9132    private void updateMatrix() {
9133        final TransformationInfo info = mTransformationInfo;
9134        if (info == null) {
9135            return;
9136        }
9137        if (info.mMatrixDirty) {
9138            // transform-related properties have changed since the last time someone
9139            // asked for the matrix; recalculate it with the current values
9140
9141            // Figure out if we need to update the pivot point
9142            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9143                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9144                    info.mPrevWidth = mRight - mLeft;
9145                    info.mPrevHeight = mBottom - mTop;
9146                    info.mPivotX = info.mPrevWidth / 2f;
9147                    info.mPivotY = info.mPrevHeight / 2f;
9148                }
9149            }
9150            info.mMatrix.reset();
9151            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9152                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9153                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9154                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9155            } else {
9156                if (info.mCamera == null) {
9157                    info.mCamera = new Camera();
9158                    info.matrix3D = new Matrix();
9159                }
9160                info.mCamera.save();
9161                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9162                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9163                info.mCamera.getMatrix(info.matrix3D);
9164                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9165                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9166                        info.mPivotY + info.mTranslationY);
9167                info.mMatrix.postConcat(info.matrix3D);
9168                info.mCamera.restore();
9169            }
9170            info.mMatrixDirty = false;
9171            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9172            info.mInverseMatrixDirty = true;
9173        }
9174    }
9175
9176   /**
9177     * Utility method to retrieve the inverse of the current mMatrix property.
9178     * We cache the matrix to avoid recalculating it when transform properties
9179     * have not changed.
9180     *
9181     * @return The inverse of the current matrix of this view.
9182     */
9183    final Matrix getInverseMatrix() {
9184        final TransformationInfo info = mTransformationInfo;
9185        if (info != null) {
9186            updateMatrix();
9187            if (info.mInverseMatrixDirty) {
9188                if (info.mInverseMatrix == null) {
9189                    info.mInverseMatrix = new Matrix();
9190                }
9191                info.mMatrix.invert(info.mInverseMatrix);
9192                info.mInverseMatrixDirty = false;
9193            }
9194            return info.mInverseMatrix;
9195        }
9196        return Matrix.IDENTITY_MATRIX;
9197    }
9198
9199    /**
9200     * Gets the distance along the Z axis from the camera to this view.
9201     *
9202     * @see #setCameraDistance(float)
9203     *
9204     * @return The distance along the Z axis.
9205     */
9206    public float getCameraDistance() {
9207        ensureTransformationInfo();
9208        final float dpi = mResources.getDisplayMetrics().densityDpi;
9209        final TransformationInfo info = mTransformationInfo;
9210        if (info.mCamera == null) {
9211            info.mCamera = new Camera();
9212            info.matrix3D = new Matrix();
9213        }
9214        return -(info.mCamera.getLocationZ() * dpi);
9215    }
9216
9217    /**
9218     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9219     * views are drawn) from the camera to this view. The camera's distance
9220     * affects 3D transformations, for instance rotations around the X and Y
9221     * axis. If the rotationX or rotationY properties are changed and this view is
9222     * large (more than half the size of the screen), it is recommended to always
9223     * use a camera distance that's greater than the height (X axis rotation) or
9224     * the width (Y axis rotation) of this view.</p>
9225     *
9226     * <p>The distance of the camera from the view plane can have an affect on the
9227     * perspective distortion of the view when it is rotated around the x or y axis.
9228     * For example, a large distance will result in a large viewing angle, and there
9229     * will not be much perspective distortion of the view as it rotates. A short
9230     * distance may cause much more perspective distortion upon rotation, and can
9231     * also result in some drawing artifacts if the rotated view ends up partially
9232     * behind the camera (which is why the recommendation is to use a distance at
9233     * least as far as the size of the view, if the view is to be rotated.)</p>
9234     *
9235     * <p>The distance is expressed in "depth pixels." The default distance depends
9236     * on the screen density. For instance, on a medium density display, the
9237     * default distance is 1280. On a high density display, the default distance
9238     * is 1920.</p>
9239     *
9240     * <p>If you want to specify a distance that leads to visually consistent
9241     * results across various densities, use the following formula:</p>
9242     * <pre>
9243     * float scale = context.getResources().getDisplayMetrics().density;
9244     * view.setCameraDistance(distance * scale);
9245     * </pre>
9246     *
9247     * <p>The density scale factor of a high density display is 1.5,
9248     * and 1920 = 1280 * 1.5.</p>
9249     *
9250     * @param distance The distance in "depth pixels", if negative the opposite
9251     *        value is used
9252     *
9253     * @see #setRotationX(float)
9254     * @see #setRotationY(float)
9255     */
9256    public void setCameraDistance(float distance) {
9257        invalidateViewProperty(true, false);
9258
9259        ensureTransformationInfo();
9260        final float dpi = mResources.getDisplayMetrics().densityDpi;
9261        final TransformationInfo info = mTransformationInfo;
9262        if (info.mCamera == null) {
9263            info.mCamera = new Camera();
9264            info.matrix3D = new Matrix();
9265        }
9266
9267        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9268        info.mMatrixDirty = true;
9269
9270        invalidateViewProperty(false, false);
9271        if (mDisplayList != null) {
9272            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9273        }
9274        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9275            // View was rejected last time it was drawn by its parent; this may have changed
9276            invalidateParentIfNeeded();
9277        }
9278    }
9279
9280    /**
9281     * The degrees that the view is rotated around the pivot point.
9282     *
9283     * @see #setRotation(float)
9284     * @see #getPivotX()
9285     * @see #getPivotY()
9286     *
9287     * @return The degrees of rotation.
9288     */
9289    @ViewDebug.ExportedProperty(category = "drawing")
9290    public float getRotation() {
9291        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9292    }
9293
9294    /**
9295     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9296     * result in clockwise rotation.
9297     *
9298     * @param rotation The degrees of rotation.
9299     *
9300     * @see #getRotation()
9301     * @see #getPivotX()
9302     * @see #getPivotY()
9303     * @see #setRotationX(float)
9304     * @see #setRotationY(float)
9305     *
9306     * @attr ref android.R.styleable#View_rotation
9307     */
9308    public void setRotation(float rotation) {
9309        ensureTransformationInfo();
9310        final TransformationInfo info = mTransformationInfo;
9311        if (info.mRotation != rotation) {
9312            // Double-invalidation is necessary to capture view's old and new areas
9313            invalidateViewProperty(true, false);
9314            info.mRotation = rotation;
9315            info.mMatrixDirty = true;
9316            invalidateViewProperty(false, true);
9317            if (mDisplayList != null) {
9318                mDisplayList.setRotation(rotation);
9319            }
9320            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9321                // View was rejected last time it was drawn by its parent; this may have changed
9322                invalidateParentIfNeeded();
9323            }
9324        }
9325    }
9326
9327    /**
9328     * The degrees that the view is rotated around the vertical axis through the pivot point.
9329     *
9330     * @see #getPivotX()
9331     * @see #getPivotY()
9332     * @see #setRotationY(float)
9333     *
9334     * @return The degrees of Y rotation.
9335     */
9336    @ViewDebug.ExportedProperty(category = "drawing")
9337    public float getRotationY() {
9338        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9339    }
9340
9341    /**
9342     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9343     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9344     * down the y axis.
9345     *
9346     * When rotating large views, it is recommended to adjust the camera distance
9347     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9348     *
9349     * @param rotationY The degrees of Y rotation.
9350     *
9351     * @see #getRotationY()
9352     * @see #getPivotX()
9353     * @see #getPivotY()
9354     * @see #setRotation(float)
9355     * @see #setRotationX(float)
9356     * @see #setCameraDistance(float)
9357     *
9358     * @attr ref android.R.styleable#View_rotationY
9359     */
9360    public void setRotationY(float rotationY) {
9361        ensureTransformationInfo();
9362        final TransformationInfo info = mTransformationInfo;
9363        if (info.mRotationY != rotationY) {
9364            invalidateViewProperty(true, false);
9365            info.mRotationY = rotationY;
9366            info.mMatrixDirty = true;
9367            invalidateViewProperty(false, true);
9368            if (mDisplayList != null) {
9369                mDisplayList.setRotationY(rotationY);
9370            }
9371            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9372                // View was rejected last time it was drawn by its parent; this may have changed
9373                invalidateParentIfNeeded();
9374            }
9375        }
9376    }
9377
9378    /**
9379     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9380     *
9381     * @see #getPivotX()
9382     * @see #getPivotY()
9383     * @see #setRotationX(float)
9384     *
9385     * @return The degrees of X rotation.
9386     */
9387    @ViewDebug.ExportedProperty(category = "drawing")
9388    public float getRotationX() {
9389        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9390    }
9391
9392    /**
9393     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9394     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9395     * x axis.
9396     *
9397     * When rotating large views, it is recommended to adjust the camera distance
9398     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9399     *
9400     * @param rotationX The degrees of X rotation.
9401     *
9402     * @see #getRotationX()
9403     * @see #getPivotX()
9404     * @see #getPivotY()
9405     * @see #setRotation(float)
9406     * @see #setRotationY(float)
9407     * @see #setCameraDistance(float)
9408     *
9409     * @attr ref android.R.styleable#View_rotationX
9410     */
9411    public void setRotationX(float rotationX) {
9412        ensureTransformationInfo();
9413        final TransformationInfo info = mTransformationInfo;
9414        if (info.mRotationX != rotationX) {
9415            invalidateViewProperty(true, false);
9416            info.mRotationX = rotationX;
9417            info.mMatrixDirty = true;
9418            invalidateViewProperty(false, true);
9419            if (mDisplayList != null) {
9420                mDisplayList.setRotationX(rotationX);
9421            }
9422            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9423                // View was rejected last time it was drawn by its parent; this may have changed
9424                invalidateParentIfNeeded();
9425            }
9426        }
9427    }
9428
9429    /**
9430     * The amount that the view is scaled in x around the pivot point, as a proportion of
9431     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9432     *
9433     * <p>By default, this is 1.0f.
9434     *
9435     * @see #getPivotX()
9436     * @see #getPivotY()
9437     * @return The scaling factor.
9438     */
9439    @ViewDebug.ExportedProperty(category = "drawing")
9440    public float getScaleX() {
9441        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9442    }
9443
9444    /**
9445     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9446     * the view's unscaled width. A value of 1 means that no scaling is applied.
9447     *
9448     * @param scaleX The scaling factor.
9449     * @see #getPivotX()
9450     * @see #getPivotY()
9451     *
9452     * @attr ref android.R.styleable#View_scaleX
9453     */
9454    public void setScaleX(float scaleX) {
9455        ensureTransformationInfo();
9456        final TransformationInfo info = mTransformationInfo;
9457        if (info.mScaleX != scaleX) {
9458            invalidateViewProperty(true, false);
9459            info.mScaleX = scaleX;
9460            info.mMatrixDirty = true;
9461            invalidateViewProperty(false, true);
9462            if (mDisplayList != null) {
9463                mDisplayList.setScaleX(scaleX);
9464            }
9465            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9466                // View was rejected last time it was drawn by its parent; this may have changed
9467                invalidateParentIfNeeded();
9468            }
9469        }
9470    }
9471
9472    /**
9473     * The amount that the view is scaled in y around the pivot point, as a proportion of
9474     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9475     *
9476     * <p>By default, this is 1.0f.
9477     *
9478     * @see #getPivotX()
9479     * @see #getPivotY()
9480     * @return The scaling factor.
9481     */
9482    @ViewDebug.ExportedProperty(category = "drawing")
9483    public float getScaleY() {
9484        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9485    }
9486
9487    /**
9488     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9489     * the view's unscaled width. A value of 1 means that no scaling is applied.
9490     *
9491     * @param scaleY The scaling factor.
9492     * @see #getPivotX()
9493     * @see #getPivotY()
9494     *
9495     * @attr ref android.R.styleable#View_scaleY
9496     */
9497    public void setScaleY(float scaleY) {
9498        ensureTransformationInfo();
9499        final TransformationInfo info = mTransformationInfo;
9500        if (info.mScaleY != scaleY) {
9501            invalidateViewProperty(true, false);
9502            info.mScaleY = scaleY;
9503            info.mMatrixDirty = true;
9504            invalidateViewProperty(false, true);
9505            if (mDisplayList != null) {
9506                mDisplayList.setScaleY(scaleY);
9507            }
9508            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9509                // View was rejected last time it was drawn by its parent; this may have changed
9510                invalidateParentIfNeeded();
9511            }
9512        }
9513    }
9514
9515    /**
9516     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9517     * and {@link #setScaleX(float) scaled}.
9518     *
9519     * @see #getRotation()
9520     * @see #getScaleX()
9521     * @see #getScaleY()
9522     * @see #getPivotY()
9523     * @return The x location of the pivot point.
9524     *
9525     * @attr ref android.R.styleable#View_transformPivotX
9526     */
9527    @ViewDebug.ExportedProperty(category = "drawing")
9528    public float getPivotX() {
9529        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9530    }
9531
9532    /**
9533     * Sets the x location of the point around which the view is
9534     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9535     * By default, the pivot point is centered on the object.
9536     * Setting this property disables this behavior and causes the view to use only the
9537     * explicitly set pivotX and pivotY values.
9538     *
9539     * @param pivotX The x location of the pivot point.
9540     * @see #getRotation()
9541     * @see #getScaleX()
9542     * @see #getScaleY()
9543     * @see #getPivotY()
9544     *
9545     * @attr ref android.R.styleable#View_transformPivotX
9546     */
9547    public void setPivotX(float pivotX) {
9548        ensureTransformationInfo();
9549        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9550        final TransformationInfo info = mTransformationInfo;
9551        if (info.mPivotX != pivotX) {
9552            invalidateViewProperty(true, false);
9553            info.mPivotX = pivotX;
9554            info.mMatrixDirty = true;
9555            invalidateViewProperty(false, true);
9556            if (mDisplayList != null) {
9557                mDisplayList.setPivotX(pivotX);
9558            }
9559            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9560                // View was rejected last time it was drawn by its parent; this may have changed
9561                invalidateParentIfNeeded();
9562            }
9563        }
9564    }
9565
9566    /**
9567     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9568     * and {@link #setScaleY(float) scaled}.
9569     *
9570     * @see #getRotation()
9571     * @see #getScaleX()
9572     * @see #getScaleY()
9573     * @see #getPivotY()
9574     * @return The y location of the pivot point.
9575     *
9576     * @attr ref android.R.styleable#View_transformPivotY
9577     */
9578    @ViewDebug.ExportedProperty(category = "drawing")
9579    public float getPivotY() {
9580        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9581    }
9582
9583    /**
9584     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9585     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9586     * Setting this property disables this behavior and causes the view to use only the
9587     * explicitly set pivotX and pivotY values.
9588     *
9589     * @param pivotY The y location of the pivot point.
9590     * @see #getRotation()
9591     * @see #getScaleX()
9592     * @see #getScaleY()
9593     * @see #getPivotY()
9594     *
9595     * @attr ref android.R.styleable#View_transformPivotY
9596     */
9597    public void setPivotY(float pivotY) {
9598        ensureTransformationInfo();
9599        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9600        final TransformationInfo info = mTransformationInfo;
9601        if (info.mPivotY != pivotY) {
9602            invalidateViewProperty(true, false);
9603            info.mPivotY = pivotY;
9604            info.mMatrixDirty = true;
9605            invalidateViewProperty(false, true);
9606            if (mDisplayList != null) {
9607                mDisplayList.setPivotY(pivotY);
9608            }
9609            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9610                // View was rejected last time it was drawn by its parent; this may have changed
9611                invalidateParentIfNeeded();
9612            }
9613        }
9614    }
9615
9616    /**
9617     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9618     * completely transparent and 1 means the view is completely opaque.
9619     *
9620     * <p>By default this is 1.0f.
9621     * @return The opacity of the view.
9622     */
9623    @ViewDebug.ExportedProperty(category = "drawing")
9624    public float getAlpha() {
9625        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9626    }
9627
9628    /**
9629     * Returns whether this View has content which overlaps. This function, intended to be
9630     * overridden by specific View types, is an optimization when alpha is set on a view. If
9631     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9632     * and then composited it into place, which can be expensive. If the view has no overlapping
9633     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9634     * An example of overlapping rendering is a TextView with a background image, such as a
9635     * Button. An example of non-overlapping rendering is a TextView with no background, or
9636     * an ImageView with only the foreground image. The default implementation returns true;
9637     * subclasses should override if they have cases which can be optimized.
9638     *
9639     * @return true if the content in this view might overlap, false otherwise.
9640     */
9641    public boolean hasOverlappingRendering() {
9642        return true;
9643    }
9644
9645    /**
9646     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9647     * completely transparent and 1 means the view is completely opaque.</p>
9648     *
9649     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9650     * performance implications, especially for large views. It is best to use the alpha property
9651     * sparingly and transiently, as in the case of fading animations.</p>
9652     *
9653     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9654     * strongly recommended for performance reasons to either override
9655     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9656     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9657     *
9658     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9659     * responsible for applying the opacity itself.</p>
9660     *
9661     * <p>Note that if the view is backed by a
9662     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9663     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9664     * 1.0 will supercede the alpha of the layer paint.</p>
9665     *
9666     * @param alpha The opacity of the view.
9667     *
9668     * @see #hasOverlappingRendering()
9669     * @see #setLayerType(int, android.graphics.Paint)
9670     *
9671     * @attr ref android.R.styleable#View_alpha
9672     */
9673    public void setAlpha(float alpha) {
9674        ensureTransformationInfo();
9675        if (mTransformationInfo.mAlpha != alpha) {
9676            mTransformationInfo.mAlpha = alpha;
9677            if (onSetAlpha((int) (alpha * 255))) {
9678                mPrivateFlags |= PFLAG_ALPHA_SET;
9679                // subclass is handling alpha - don't optimize rendering cache invalidation
9680                invalidateParentCaches();
9681                invalidate(true);
9682            } else {
9683                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9684                invalidateViewProperty(true, false);
9685                if (mDisplayList != null) {
9686                    mDisplayList.setAlpha(alpha);
9687                }
9688            }
9689        }
9690    }
9691
9692    /**
9693     * Faster version of setAlpha() which performs the same steps except there are
9694     * no calls to invalidate(). The caller of this function should perform proper invalidation
9695     * on the parent and this object. The return value indicates whether the subclass handles
9696     * alpha (the return value for onSetAlpha()).
9697     *
9698     * @param alpha The new value for the alpha property
9699     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9700     *         the new value for the alpha property is different from the old value
9701     */
9702    boolean setAlphaNoInvalidation(float alpha) {
9703        ensureTransformationInfo();
9704        if (mTransformationInfo.mAlpha != alpha) {
9705            mTransformationInfo.mAlpha = alpha;
9706            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9707            if (subclassHandlesAlpha) {
9708                mPrivateFlags |= PFLAG_ALPHA_SET;
9709                return true;
9710            } else {
9711                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9712                if (mDisplayList != null) {
9713                    mDisplayList.setAlpha(alpha);
9714                }
9715            }
9716        }
9717        return false;
9718    }
9719
9720    /**
9721     * Top position of this view relative to its parent.
9722     *
9723     * @return The top of this view, in pixels.
9724     */
9725    @ViewDebug.CapturedViewProperty
9726    public final int getTop() {
9727        return mTop;
9728    }
9729
9730    /**
9731     * Sets the top position of this view relative to its parent. This method is meant to be called
9732     * by the layout system and should not generally be called otherwise, because the property
9733     * may be changed at any time by the layout.
9734     *
9735     * @param top The top of this view, in pixels.
9736     */
9737    public final void setTop(int top) {
9738        if (top != mTop) {
9739            updateMatrix();
9740            final boolean matrixIsIdentity = mTransformationInfo == null
9741                    || mTransformationInfo.mMatrixIsIdentity;
9742            if (matrixIsIdentity) {
9743                if (mAttachInfo != null) {
9744                    int minTop;
9745                    int yLoc;
9746                    if (top < mTop) {
9747                        minTop = top;
9748                        yLoc = top - mTop;
9749                    } else {
9750                        minTop = mTop;
9751                        yLoc = 0;
9752                    }
9753                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9754                }
9755            } else {
9756                // Double-invalidation is necessary to capture view's old and new areas
9757                invalidate(true);
9758            }
9759
9760            int width = mRight - mLeft;
9761            int oldHeight = mBottom - mTop;
9762
9763            mTop = top;
9764            if (mDisplayList != null) {
9765                mDisplayList.setTop(mTop);
9766            }
9767
9768            sizeChange(width, mBottom - mTop, width, oldHeight);
9769
9770            if (!matrixIsIdentity) {
9771                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9772                    // A change in dimension means an auto-centered pivot point changes, too
9773                    mTransformationInfo.mMatrixDirty = true;
9774                }
9775                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9776                invalidate(true);
9777            }
9778            mBackgroundSizeChanged = true;
9779            invalidateParentIfNeeded();
9780            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9781                // View was rejected last time it was drawn by its parent; this may have changed
9782                invalidateParentIfNeeded();
9783            }
9784        }
9785    }
9786
9787    /**
9788     * Bottom position of this view relative to its parent.
9789     *
9790     * @return The bottom of this view, in pixels.
9791     */
9792    @ViewDebug.CapturedViewProperty
9793    public final int getBottom() {
9794        return mBottom;
9795    }
9796
9797    /**
9798     * True if this view has changed since the last time being drawn.
9799     *
9800     * @return The dirty state of this view.
9801     */
9802    public boolean isDirty() {
9803        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9804    }
9805
9806    /**
9807     * Sets the bottom position of this view relative to its parent. This method is meant to be
9808     * called by the layout system and should not generally be called otherwise, because the
9809     * property may be changed at any time by the layout.
9810     *
9811     * @param bottom The bottom of this view, in pixels.
9812     */
9813    public final void setBottom(int bottom) {
9814        if (bottom != mBottom) {
9815            updateMatrix();
9816            final boolean matrixIsIdentity = mTransformationInfo == null
9817                    || mTransformationInfo.mMatrixIsIdentity;
9818            if (matrixIsIdentity) {
9819                if (mAttachInfo != null) {
9820                    int maxBottom;
9821                    if (bottom < mBottom) {
9822                        maxBottom = mBottom;
9823                    } else {
9824                        maxBottom = bottom;
9825                    }
9826                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9827                }
9828            } else {
9829                // Double-invalidation is necessary to capture view's old and new areas
9830                invalidate(true);
9831            }
9832
9833            int width = mRight - mLeft;
9834            int oldHeight = mBottom - mTop;
9835
9836            mBottom = bottom;
9837            if (mDisplayList != null) {
9838                mDisplayList.setBottom(mBottom);
9839            }
9840
9841            sizeChange(width, mBottom - mTop, width, oldHeight);
9842
9843            if (!matrixIsIdentity) {
9844                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9845                    // A change in dimension means an auto-centered pivot point changes, too
9846                    mTransformationInfo.mMatrixDirty = true;
9847                }
9848                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9849                invalidate(true);
9850            }
9851            mBackgroundSizeChanged = true;
9852            invalidateParentIfNeeded();
9853            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9854                // View was rejected last time it was drawn by its parent; this may have changed
9855                invalidateParentIfNeeded();
9856            }
9857        }
9858    }
9859
9860    /**
9861     * Left position of this view relative to its parent.
9862     *
9863     * @return The left edge of this view, in pixels.
9864     */
9865    @ViewDebug.CapturedViewProperty
9866    public final int getLeft() {
9867        return mLeft;
9868    }
9869
9870    /**
9871     * Sets the left position of this view relative to its parent. This method is meant to be called
9872     * by the layout system and should not generally be called otherwise, because the property
9873     * may be changed at any time by the layout.
9874     *
9875     * @param left The bottom of this view, in pixels.
9876     */
9877    public final void setLeft(int left) {
9878        if (left != mLeft) {
9879            updateMatrix();
9880            final boolean matrixIsIdentity = mTransformationInfo == null
9881                    || mTransformationInfo.mMatrixIsIdentity;
9882            if (matrixIsIdentity) {
9883                if (mAttachInfo != null) {
9884                    int minLeft;
9885                    int xLoc;
9886                    if (left < mLeft) {
9887                        minLeft = left;
9888                        xLoc = left - mLeft;
9889                    } else {
9890                        minLeft = mLeft;
9891                        xLoc = 0;
9892                    }
9893                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9894                }
9895            } else {
9896                // Double-invalidation is necessary to capture view's old and new areas
9897                invalidate(true);
9898            }
9899
9900            int oldWidth = mRight - mLeft;
9901            int height = mBottom - mTop;
9902
9903            mLeft = left;
9904            if (mDisplayList != null) {
9905                mDisplayList.setLeft(left);
9906            }
9907
9908            sizeChange(mRight - mLeft, height, oldWidth, height);
9909
9910            if (!matrixIsIdentity) {
9911                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9912                    // A change in dimension means an auto-centered pivot point changes, too
9913                    mTransformationInfo.mMatrixDirty = true;
9914                }
9915                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9916                invalidate(true);
9917            }
9918            mBackgroundSizeChanged = true;
9919            invalidateParentIfNeeded();
9920            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9921                // View was rejected last time it was drawn by its parent; this may have changed
9922                invalidateParentIfNeeded();
9923            }
9924        }
9925    }
9926
9927    /**
9928     * Right position of this view relative to its parent.
9929     *
9930     * @return The right edge of this view, in pixels.
9931     */
9932    @ViewDebug.CapturedViewProperty
9933    public final int getRight() {
9934        return mRight;
9935    }
9936
9937    /**
9938     * Sets the right position of this view relative to its parent. This method is meant to be called
9939     * by the layout system and should not generally be called otherwise, because the property
9940     * may be changed at any time by the layout.
9941     *
9942     * @param right The bottom of this view, in pixels.
9943     */
9944    public final void setRight(int right) {
9945        if (right != mRight) {
9946            updateMatrix();
9947            final boolean matrixIsIdentity = mTransformationInfo == null
9948                    || mTransformationInfo.mMatrixIsIdentity;
9949            if (matrixIsIdentity) {
9950                if (mAttachInfo != null) {
9951                    int maxRight;
9952                    if (right < mRight) {
9953                        maxRight = mRight;
9954                    } else {
9955                        maxRight = right;
9956                    }
9957                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9958                }
9959            } else {
9960                // Double-invalidation is necessary to capture view's old and new areas
9961                invalidate(true);
9962            }
9963
9964            int oldWidth = mRight - mLeft;
9965            int height = mBottom - mTop;
9966
9967            mRight = right;
9968            if (mDisplayList != null) {
9969                mDisplayList.setRight(mRight);
9970            }
9971
9972            sizeChange(mRight - mLeft, height, oldWidth, height);
9973
9974            if (!matrixIsIdentity) {
9975                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9976                    // A change in dimension means an auto-centered pivot point changes, too
9977                    mTransformationInfo.mMatrixDirty = true;
9978                }
9979                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9980                invalidate(true);
9981            }
9982            mBackgroundSizeChanged = true;
9983            invalidateParentIfNeeded();
9984            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9985                // View was rejected last time it was drawn by its parent; this may have changed
9986                invalidateParentIfNeeded();
9987            }
9988        }
9989    }
9990
9991    /**
9992     * The visual x position of this view, in pixels. This is equivalent to the
9993     * {@link #setTranslationX(float) translationX} property plus the current
9994     * {@link #getLeft() left} property.
9995     *
9996     * @return The visual x position of this view, in pixels.
9997     */
9998    @ViewDebug.ExportedProperty(category = "drawing")
9999    public float getX() {
10000        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10001    }
10002
10003    /**
10004     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10005     * {@link #setTranslationX(float) translationX} property to be the difference between
10006     * the x value passed in and the current {@link #getLeft() left} property.
10007     *
10008     * @param x The visual x position of this view, in pixels.
10009     */
10010    public void setX(float x) {
10011        setTranslationX(x - mLeft);
10012    }
10013
10014    /**
10015     * The visual y position of this view, in pixels. This is equivalent to the
10016     * {@link #setTranslationY(float) translationY} property plus the current
10017     * {@link #getTop() top} property.
10018     *
10019     * @return The visual y position of this view, in pixels.
10020     */
10021    @ViewDebug.ExportedProperty(category = "drawing")
10022    public float getY() {
10023        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10024    }
10025
10026    /**
10027     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10028     * {@link #setTranslationY(float) translationY} property to be the difference between
10029     * the y value passed in and the current {@link #getTop() top} property.
10030     *
10031     * @param y The visual y position of this view, in pixels.
10032     */
10033    public void setY(float y) {
10034        setTranslationY(y - mTop);
10035    }
10036
10037
10038    /**
10039     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10040     * This position is post-layout, in addition to wherever the object's
10041     * layout placed it.
10042     *
10043     * @return The horizontal position of this view relative to its left position, in pixels.
10044     */
10045    @ViewDebug.ExportedProperty(category = "drawing")
10046    public float getTranslationX() {
10047        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10048    }
10049
10050    /**
10051     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10052     * This effectively positions the object post-layout, in addition to wherever the object's
10053     * layout placed it.
10054     *
10055     * @param translationX The horizontal position of this view relative to its left position,
10056     * in pixels.
10057     *
10058     * @attr ref android.R.styleable#View_translationX
10059     */
10060    public void setTranslationX(float translationX) {
10061        ensureTransformationInfo();
10062        final TransformationInfo info = mTransformationInfo;
10063        if (info.mTranslationX != translationX) {
10064            // Double-invalidation is necessary to capture view's old and new areas
10065            invalidateViewProperty(true, false);
10066            info.mTranslationX = translationX;
10067            info.mMatrixDirty = true;
10068            invalidateViewProperty(false, true);
10069            if (mDisplayList != null) {
10070                mDisplayList.setTranslationX(translationX);
10071            }
10072            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10073                // View was rejected last time it was drawn by its parent; this may have changed
10074                invalidateParentIfNeeded();
10075            }
10076        }
10077    }
10078
10079    /**
10080     * The horizontal location of this view relative to its {@link #getTop() top} position.
10081     * This position is post-layout, in addition to wherever the object's
10082     * layout placed it.
10083     *
10084     * @return The vertical position of this view relative to its top position,
10085     * in pixels.
10086     */
10087    @ViewDebug.ExportedProperty(category = "drawing")
10088    public float getTranslationY() {
10089        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10090    }
10091
10092    /**
10093     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10094     * This effectively positions the object post-layout, in addition to wherever the object's
10095     * layout placed it.
10096     *
10097     * @param translationY The vertical position of this view relative to its top position,
10098     * in pixels.
10099     *
10100     * @attr ref android.R.styleable#View_translationY
10101     */
10102    public void setTranslationY(float translationY) {
10103        ensureTransformationInfo();
10104        final TransformationInfo info = mTransformationInfo;
10105        if (info.mTranslationY != translationY) {
10106            invalidateViewProperty(true, false);
10107            info.mTranslationY = translationY;
10108            info.mMatrixDirty = true;
10109            invalidateViewProperty(false, true);
10110            if (mDisplayList != null) {
10111                mDisplayList.setTranslationY(translationY);
10112            }
10113            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10114                // View was rejected last time it was drawn by its parent; this may have changed
10115                invalidateParentIfNeeded();
10116            }
10117        }
10118    }
10119
10120    /**
10121     * Hit rectangle in parent's coordinates
10122     *
10123     * @param outRect The hit rectangle of the view.
10124     */
10125    public void getHitRect(Rect outRect) {
10126        updateMatrix();
10127        final TransformationInfo info = mTransformationInfo;
10128        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10129            outRect.set(mLeft, mTop, mRight, mBottom);
10130        } else {
10131            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10132            tmpRect.set(0, 0, getWidth(), getHeight());
10133            info.mMatrix.mapRect(tmpRect);
10134            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10135                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10136        }
10137    }
10138
10139    /**
10140     * Determines whether the given point, in local coordinates is inside the view.
10141     */
10142    /*package*/ final boolean pointInView(float localX, float localY) {
10143        return localX >= 0 && localX < (mRight - mLeft)
10144                && localY >= 0 && localY < (mBottom - mTop);
10145    }
10146
10147    /**
10148     * Utility method to determine whether the given point, in local coordinates,
10149     * is inside the view, where the area of the view is expanded by the slop factor.
10150     * This method is called while processing touch-move events to determine if the event
10151     * is still within the view.
10152     *
10153     * @hide
10154     */
10155    public boolean pointInView(float localX, float localY, float slop) {
10156        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10157                localY < ((mBottom - mTop) + slop);
10158    }
10159
10160    /**
10161     * When a view has focus and the user navigates away from it, the next view is searched for
10162     * starting from the rectangle filled in by this method.
10163     *
10164     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10165     * of the view.  However, if your view maintains some idea of internal selection,
10166     * such as a cursor, or a selected row or column, you should override this method and
10167     * fill in a more specific rectangle.
10168     *
10169     * @param r The rectangle to fill in, in this view's coordinates.
10170     */
10171    public void getFocusedRect(Rect r) {
10172        getDrawingRect(r);
10173    }
10174
10175    /**
10176     * If some part of this view is not clipped by any of its parents, then
10177     * return that area in r in global (root) coordinates. To convert r to local
10178     * coordinates (without taking possible View rotations into account), offset
10179     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10180     * If the view is completely clipped or translated out, return false.
10181     *
10182     * @param r If true is returned, r holds the global coordinates of the
10183     *        visible portion of this view.
10184     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10185     *        between this view and its root. globalOffet may be null.
10186     * @return true if r is non-empty (i.e. part of the view is visible at the
10187     *         root level.
10188     */
10189    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10190        int width = mRight - mLeft;
10191        int height = mBottom - mTop;
10192        if (width > 0 && height > 0) {
10193            r.set(0, 0, width, height);
10194            if (globalOffset != null) {
10195                globalOffset.set(-mScrollX, -mScrollY);
10196            }
10197            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10198        }
10199        return false;
10200    }
10201
10202    public final boolean getGlobalVisibleRect(Rect r) {
10203        return getGlobalVisibleRect(r, null);
10204    }
10205
10206    public final boolean getLocalVisibleRect(Rect r) {
10207        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10208        if (getGlobalVisibleRect(r, offset)) {
10209            r.offset(-offset.x, -offset.y); // make r local
10210            return true;
10211        }
10212        return false;
10213    }
10214
10215    /**
10216     * Offset this view's vertical location by the specified number of pixels.
10217     *
10218     * @param offset the number of pixels to offset the view by
10219     */
10220    public void offsetTopAndBottom(int offset) {
10221        if (offset != 0) {
10222            updateMatrix();
10223            final boolean matrixIsIdentity = mTransformationInfo == null
10224                    || mTransformationInfo.mMatrixIsIdentity;
10225            if (matrixIsIdentity) {
10226                if (mDisplayList != null) {
10227                    invalidateViewProperty(false, false);
10228                } else {
10229                    final ViewParent p = mParent;
10230                    if (p != null && mAttachInfo != null) {
10231                        final Rect r = mAttachInfo.mTmpInvalRect;
10232                        int minTop;
10233                        int maxBottom;
10234                        int yLoc;
10235                        if (offset < 0) {
10236                            minTop = mTop + offset;
10237                            maxBottom = mBottom;
10238                            yLoc = offset;
10239                        } else {
10240                            minTop = mTop;
10241                            maxBottom = mBottom + offset;
10242                            yLoc = 0;
10243                        }
10244                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10245                        p.invalidateChild(this, r);
10246                    }
10247                }
10248            } else {
10249                invalidateViewProperty(false, false);
10250            }
10251
10252            mTop += offset;
10253            mBottom += offset;
10254            if (mDisplayList != null) {
10255                mDisplayList.offsetTopAndBottom(offset);
10256                invalidateViewProperty(false, false);
10257            } else {
10258                if (!matrixIsIdentity) {
10259                    invalidateViewProperty(false, true);
10260                }
10261                invalidateParentIfNeeded();
10262            }
10263        }
10264    }
10265
10266    /**
10267     * Offset this view's horizontal location by the specified amount of pixels.
10268     *
10269     * @param offset the number of pixels to offset the view by
10270     */
10271    public void offsetLeftAndRight(int offset) {
10272        if (offset != 0) {
10273            updateMatrix();
10274            final boolean matrixIsIdentity = mTransformationInfo == null
10275                    || mTransformationInfo.mMatrixIsIdentity;
10276            if (matrixIsIdentity) {
10277                if (mDisplayList != null) {
10278                    invalidateViewProperty(false, false);
10279                } else {
10280                    final ViewParent p = mParent;
10281                    if (p != null && mAttachInfo != null) {
10282                        final Rect r = mAttachInfo.mTmpInvalRect;
10283                        int minLeft;
10284                        int maxRight;
10285                        if (offset < 0) {
10286                            minLeft = mLeft + offset;
10287                            maxRight = mRight;
10288                        } else {
10289                            minLeft = mLeft;
10290                            maxRight = mRight + offset;
10291                        }
10292                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10293                        p.invalidateChild(this, r);
10294                    }
10295                }
10296            } else {
10297                invalidateViewProperty(false, false);
10298            }
10299
10300            mLeft += offset;
10301            mRight += offset;
10302            if (mDisplayList != null) {
10303                mDisplayList.offsetLeftAndRight(offset);
10304                invalidateViewProperty(false, false);
10305            } else {
10306                if (!matrixIsIdentity) {
10307                    invalidateViewProperty(false, true);
10308                }
10309                invalidateParentIfNeeded();
10310            }
10311        }
10312    }
10313
10314    /**
10315     * Get the LayoutParams associated with this view. All views should have
10316     * layout parameters. These supply parameters to the <i>parent</i> of this
10317     * view specifying how it should be arranged. There are many subclasses of
10318     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10319     * of ViewGroup that are responsible for arranging their children.
10320     *
10321     * This method may return null if this View is not attached to a parent
10322     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10323     * was not invoked successfully. When a View is attached to a parent
10324     * ViewGroup, this method must not return null.
10325     *
10326     * @return The LayoutParams associated with this view, or null if no
10327     *         parameters have been set yet
10328     */
10329    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10330    public ViewGroup.LayoutParams getLayoutParams() {
10331        return mLayoutParams;
10332    }
10333
10334    /**
10335     * Set the layout parameters associated with this view. These supply
10336     * parameters to the <i>parent</i> of this view specifying how it should be
10337     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10338     * correspond to the different subclasses of ViewGroup that are responsible
10339     * for arranging their children.
10340     *
10341     * @param params The layout parameters for this view, cannot be null
10342     */
10343    public void setLayoutParams(ViewGroup.LayoutParams params) {
10344        if (params == null) {
10345            throw new NullPointerException("Layout parameters cannot be null");
10346        }
10347        mLayoutParams = params;
10348        resolveLayoutParams();
10349        if (mParent instanceof ViewGroup) {
10350            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10351        }
10352        requestLayout();
10353    }
10354
10355    /**
10356     * Resolve the layout parameters depending on the resolved layout direction
10357     *
10358     * @hide
10359     */
10360    public void resolveLayoutParams() {
10361        if (mLayoutParams != null) {
10362            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10363        }
10364    }
10365
10366    /**
10367     * Set the scrolled position of your view. This will cause a call to
10368     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10369     * invalidated.
10370     * @param x the x position to scroll to
10371     * @param y the y position to scroll to
10372     */
10373    public void scrollTo(int x, int y) {
10374        if (mScrollX != x || mScrollY != y) {
10375            int oldX = mScrollX;
10376            int oldY = mScrollY;
10377            mScrollX = x;
10378            mScrollY = y;
10379            invalidateParentCaches();
10380            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10381            if (!awakenScrollBars()) {
10382                postInvalidateOnAnimation();
10383            }
10384        }
10385    }
10386
10387    /**
10388     * Move the scrolled position of your view. This will cause a call to
10389     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10390     * invalidated.
10391     * @param x the amount of pixels to scroll by horizontally
10392     * @param y the amount of pixels to scroll by vertically
10393     */
10394    public void scrollBy(int x, int y) {
10395        scrollTo(mScrollX + x, mScrollY + y);
10396    }
10397
10398    /**
10399     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10400     * animation to fade the scrollbars out after a default delay. If a subclass
10401     * provides animated scrolling, the start delay should equal the duration
10402     * of the scrolling animation.</p>
10403     *
10404     * <p>The animation starts only if at least one of the scrollbars is
10405     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10406     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10407     * this method returns true, and false otherwise. If the animation is
10408     * started, this method calls {@link #invalidate()}; in that case the
10409     * caller should not call {@link #invalidate()}.</p>
10410     *
10411     * <p>This method should be invoked every time a subclass directly updates
10412     * the scroll parameters.</p>
10413     *
10414     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10415     * and {@link #scrollTo(int, int)}.</p>
10416     *
10417     * @return true if the animation is played, false otherwise
10418     *
10419     * @see #awakenScrollBars(int)
10420     * @see #scrollBy(int, int)
10421     * @see #scrollTo(int, int)
10422     * @see #isHorizontalScrollBarEnabled()
10423     * @see #isVerticalScrollBarEnabled()
10424     * @see #setHorizontalScrollBarEnabled(boolean)
10425     * @see #setVerticalScrollBarEnabled(boolean)
10426     */
10427    protected boolean awakenScrollBars() {
10428        return mScrollCache != null &&
10429                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10430    }
10431
10432    /**
10433     * Trigger the scrollbars to draw.
10434     * This method differs from awakenScrollBars() only in its default duration.
10435     * initialAwakenScrollBars() will show the scroll bars for longer than
10436     * usual to give the user more of a chance to notice them.
10437     *
10438     * @return true if the animation is played, false otherwise.
10439     */
10440    private boolean initialAwakenScrollBars() {
10441        return mScrollCache != null &&
10442                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10443    }
10444
10445    /**
10446     * <p>
10447     * Trigger the scrollbars to draw. When invoked this method starts an
10448     * animation to fade the scrollbars out after a fixed delay. If a subclass
10449     * provides animated scrolling, the start delay should equal the duration of
10450     * the scrolling animation.
10451     * </p>
10452     *
10453     * <p>
10454     * The animation starts only if at least one of the scrollbars is enabled,
10455     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10456     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10457     * this method returns true, and false otherwise. If the animation is
10458     * started, this method calls {@link #invalidate()}; in that case the caller
10459     * should not call {@link #invalidate()}.
10460     * </p>
10461     *
10462     * <p>
10463     * This method should be invoked everytime a subclass directly updates the
10464     * scroll parameters.
10465     * </p>
10466     *
10467     * @param startDelay the delay, in milliseconds, after which the animation
10468     *        should start; when the delay is 0, the animation starts
10469     *        immediately
10470     * @return true if the animation is played, false otherwise
10471     *
10472     * @see #scrollBy(int, int)
10473     * @see #scrollTo(int, int)
10474     * @see #isHorizontalScrollBarEnabled()
10475     * @see #isVerticalScrollBarEnabled()
10476     * @see #setHorizontalScrollBarEnabled(boolean)
10477     * @see #setVerticalScrollBarEnabled(boolean)
10478     */
10479    protected boolean awakenScrollBars(int startDelay) {
10480        return awakenScrollBars(startDelay, true);
10481    }
10482
10483    /**
10484     * <p>
10485     * Trigger the scrollbars to draw. When invoked this method starts an
10486     * animation to fade the scrollbars out after a fixed delay. If a subclass
10487     * provides animated scrolling, the start delay should equal the duration of
10488     * the scrolling animation.
10489     * </p>
10490     *
10491     * <p>
10492     * The animation starts only if at least one of the scrollbars is enabled,
10493     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10494     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10495     * this method returns true, and false otherwise. If the animation is
10496     * started, this method calls {@link #invalidate()} if the invalidate parameter
10497     * is set to true; in that case the caller
10498     * should not call {@link #invalidate()}.
10499     * </p>
10500     *
10501     * <p>
10502     * This method should be invoked everytime a subclass directly updates the
10503     * scroll parameters.
10504     * </p>
10505     *
10506     * @param startDelay the delay, in milliseconds, after which the animation
10507     *        should start; when the delay is 0, the animation starts
10508     *        immediately
10509     *
10510     * @param invalidate Wheter this method should call invalidate
10511     *
10512     * @return true if the animation is played, false otherwise
10513     *
10514     * @see #scrollBy(int, int)
10515     * @see #scrollTo(int, int)
10516     * @see #isHorizontalScrollBarEnabled()
10517     * @see #isVerticalScrollBarEnabled()
10518     * @see #setHorizontalScrollBarEnabled(boolean)
10519     * @see #setVerticalScrollBarEnabled(boolean)
10520     */
10521    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10522        final ScrollabilityCache scrollCache = mScrollCache;
10523
10524        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10525            return false;
10526        }
10527
10528        if (scrollCache.scrollBar == null) {
10529            scrollCache.scrollBar = new ScrollBarDrawable();
10530        }
10531
10532        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10533
10534            if (invalidate) {
10535                // Invalidate to show the scrollbars
10536                postInvalidateOnAnimation();
10537            }
10538
10539            if (scrollCache.state == ScrollabilityCache.OFF) {
10540                // FIXME: this is copied from WindowManagerService.
10541                // We should get this value from the system when it
10542                // is possible to do so.
10543                final int KEY_REPEAT_FIRST_DELAY = 750;
10544                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10545            }
10546
10547            // Tell mScrollCache when we should start fading. This may
10548            // extend the fade start time if one was already scheduled
10549            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10550            scrollCache.fadeStartTime = fadeStartTime;
10551            scrollCache.state = ScrollabilityCache.ON;
10552
10553            // Schedule our fader to run, unscheduling any old ones first
10554            if (mAttachInfo != null) {
10555                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10556                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10557            }
10558
10559            return true;
10560        }
10561
10562        return false;
10563    }
10564
10565    /**
10566     * Do not invalidate views which are not visible and which are not running an animation. They
10567     * will not get drawn and they should not set dirty flags as if they will be drawn
10568     */
10569    private boolean skipInvalidate() {
10570        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10571                (!(mParent instanceof ViewGroup) ||
10572                        !((ViewGroup) mParent).isViewTransitioning(this));
10573    }
10574    /**
10575     * Mark the area defined by dirty as needing to be drawn. If the view is
10576     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10577     * in the future. This must be called from a UI thread. To call from a non-UI
10578     * thread, call {@link #postInvalidate()}.
10579     *
10580     * WARNING: This method is destructive to dirty.
10581     * @param dirty the rectangle representing the bounds of the dirty region
10582     */
10583    public void invalidate(Rect dirty) {
10584        if (skipInvalidate()) {
10585            return;
10586        }
10587        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10588                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10589                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10590            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10591            mPrivateFlags |= PFLAG_INVALIDATED;
10592            mPrivateFlags |= PFLAG_DIRTY;
10593            final ViewParent p = mParent;
10594            final AttachInfo ai = mAttachInfo;
10595            //noinspection PointlessBooleanExpression,ConstantConditions
10596            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10597                if (p != null && ai != null && ai.mHardwareAccelerated) {
10598                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10599                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10600                    p.invalidateChild(this, null);
10601                    return;
10602                }
10603            }
10604            if (p != null && ai != null) {
10605                final int scrollX = mScrollX;
10606                final int scrollY = mScrollY;
10607                final Rect r = ai.mTmpInvalRect;
10608                r.set(dirty.left - scrollX, dirty.top - scrollY,
10609                        dirty.right - scrollX, dirty.bottom - scrollY);
10610                mParent.invalidateChild(this, r);
10611            }
10612        }
10613    }
10614
10615    /**
10616     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10617     * The coordinates of the dirty rect are relative to the view.
10618     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10619     * will be called at some point in the future. This must be called from
10620     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10621     * @param l the left position of the dirty region
10622     * @param t the top position of the dirty region
10623     * @param r the right position of the dirty region
10624     * @param b the bottom position of the dirty region
10625     */
10626    public void invalidate(int l, int t, int r, int b) {
10627        if (skipInvalidate()) {
10628            return;
10629        }
10630        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10631                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10632                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10633            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10634            mPrivateFlags |= PFLAG_INVALIDATED;
10635            mPrivateFlags |= PFLAG_DIRTY;
10636            final ViewParent p = mParent;
10637            final AttachInfo ai = mAttachInfo;
10638            //noinspection PointlessBooleanExpression,ConstantConditions
10639            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10640                if (p != null && ai != null && ai.mHardwareAccelerated) {
10641                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10642                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10643                    p.invalidateChild(this, null);
10644                    return;
10645                }
10646            }
10647            if (p != null && ai != null && l < r && t < b) {
10648                final int scrollX = mScrollX;
10649                final int scrollY = mScrollY;
10650                final Rect tmpr = ai.mTmpInvalRect;
10651                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10652                p.invalidateChild(this, tmpr);
10653            }
10654        }
10655    }
10656
10657    /**
10658     * Invalidate the whole view. If the view is visible,
10659     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10660     * the future. This must be called from a UI thread. To call from a non-UI thread,
10661     * call {@link #postInvalidate()}.
10662     */
10663    public void invalidate() {
10664        invalidate(true);
10665    }
10666
10667    /**
10668     * This is where the invalidate() work actually happens. A full invalidate()
10669     * causes the drawing cache to be invalidated, but this function can be called with
10670     * invalidateCache set to false to skip that invalidation step for cases that do not
10671     * need it (for example, a component that remains at the same dimensions with the same
10672     * content).
10673     *
10674     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10675     * well. This is usually true for a full invalidate, but may be set to false if the
10676     * View's contents or dimensions have not changed.
10677     */
10678    void invalidate(boolean invalidateCache) {
10679        if (skipInvalidate()) {
10680            return;
10681        }
10682        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10683                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10684                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10685            mLastIsOpaque = isOpaque();
10686            mPrivateFlags &= ~PFLAG_DRAWN;
10687            mPrivateFlags |= PFLAG_DIRTY;
10688            if (invalidateCache) {
10689                mPrivateFlags |= PFLAG_INVALIDATED;
10690                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10691            }
10692            final AttachInfo ai = mAttachInfo;
10693            final ViewParent p = mParent;
10694            //noinspection PointlessBooleanExpression,ConstantConditions
10695            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10696                if (p != null && ai != null && ai.mHardwareAccelerated) {
10697                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10698                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10699                    p.invalidateChild(this, null);
10700                    return;
10701                }
10702            }
10703
10704            if (p != null && ai != null) {
10705                final Rect r = ai.mTmpInvalRect;
10706                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10707                // Don't call invalidate -- we don't want to internally scroll
10708                // our own bounds
10709                p.invalidateChild(this, r);
10710            }
10711        }
10712    }
10713
10714    /**
10715     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10716     * set any flags or handle all of the cases handled by the default invalidation methods.
10717     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10718     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10719     * walk up the hierarchy, transforming the dirty rect as necessary.
10720     *
10721     * The method also handles normal invalidation logic if display list properties are not
10722     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10723     * backup approach, to handle these cases used in the various property-setting methods.
10724     *
10725     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10726     * are not being used in this view
10727     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10728     * list properties are not being used in this view
10729     */
10730    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10731        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10732            if (invalidateParent) {
10733                invalidateParentCaches();
10734            }
10735            if (forceRedraw) {
10736                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10737            }
10738            invalidate(false);
10739        } else {
10740            final AttachInfo ai = mAttachInfo;
10741            final ViewParent p = mParent;
10742            if (p != null && ai != null) {
10743                final Rect r = ai.mTmpInvalRect;
10744                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10745                if (mParent instanceof ViewGroup) {
10746                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10747                } else {
10748                    mParent.invalidateChild(this, r);
10749                }
10750            }
10751        }
10752    }
10753
10754    /**
10755     * Utility method to transform a given Rect by the current matrix of this view.
10756     */
10757    void transformRect(final Rect rect) {
10758        if (!getMatrix().isIdentity()) {
10759            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10760            boundingRect.set(rect);
10761            getMatrix().mapRect(boundingRect);
10762            rect.set((int) Math.floor(boundingRect.left),
10763                    (int) Math.floor(boundingRect.top),
10764                    (int) Math.ceil(boundingRect.right),
10765                    (int) Math.ceil(boundingRect.bottom));
10766        }
10767    }
10768
10769    /**
10770     * Used to indicate that the parent of this view should clear its caches. This functionality
10771     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10772     * which is necessary when various parent-managed properties of the view change, such as
10773     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10774     * clears the parent caches and does not causes an invalidate event.
10775     *
10776     * @hide
10777     */
10778    protected void invalidateParentCaches() {
10779        if (mParent instanceof View) {
10780            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10781        }
10782    }
10783
10784    /**
10785     * Used to indicate that the parent of this view should be invalidated. This functionality
10786     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10787     * which is necessary when various parent-managed properties of the view change, such as
10788     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10789     * an invalidation event to the parent.
10790     *
10791     * @hide
10792     */
10793    protected void invalidateParentIfNeeded() {
10794        if (isHardwareAccelerated() && mParent instanceof View) {
10795            ((View) mParent).invalidate(true);
10796        }
10797    }
10798
10799    /**
10800     * Indicates whether this View is opaque. An opaque View guarantees that it will
10801     * draw all the pixels overlapping its bounds using a fully opaque color.
10802     *
10803     * Subclasses of View should override this method whenever possible to indicate
10804     * whether an instance is opaque. Opaque Views are treated in a special way by
10805     * the View hierarchy, possibly allowing it to perform optimizations during
10806     * invalidate/draw passes.
10807     *
10808     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10809     */
10810    @ViewDebug.ExportedProperty(category = "drawing")
10811    public boolean isOpaque() {
10812        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10813                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10814    }
10815
10816    /**
10817     * @hide
10818     */
10819    protected void computeOpaqueFlags() {
10820        // Opaque if:
10821        //   - Has a background
10822        //   - Background is opaque
10823        //   - Doesn't have scrollbars or scrollbars overlay
10824
10825        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10826            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10827        } else {
10828            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10829        }
10830
10831        final int flags = mViewFlags;
10832        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10833                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10834                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10835            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10836        } else {
10837            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10838        }
10839    }
10840
10841    /**
10842     * @hide
10843     */
10844    protected boolean hasOpaqueScrollbars() {
10845        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10846    }
10847
10848    /**
10849     * @return A handler associated with the thread running the View. This
10850     * handler can be used to pump events in the UI events queue.
10851     */
10852    public Handler getHandler() {
10853        final AttachInfo attachInfo = mAttachInfo;
10854        if (attachInfo != null) {
10855            return attachInfo.mHandler;
10856        }
10857        return null;
10858    }
10859
10860    /**
10861     * Gets the view root associated with the View.
10862     * @return The view root, or null if none.
10863     * @hide
10864     */
10865    public ViewRootImpl getViewRootImpl() {
10866        if (mAttachInfo != null) {
10867            return mAttachInfo.mViewRootImpl;
10868        }
10869        return null;
10870    }
10871
10872    /**
10873     * <p>Causes the Runnable to be added to the message queue.
10874     * The runnable will be run on the user interface thread.</p>
10875     *
10876     * @param action The Runnable that will be executed.
10877     *
10878     * @return Returns true if the Runnable was successfully placed in to the
10879     *         message queue.  Returns false on failure, usually because the
10880     *         looper processing the message queue is exiting.
10881     *
10882     * @see #postDelayed
10883     * @see #removeCallbacks
10884     */
10885    public boolean post(Runnable action) {
10886        final AttachInfo attachInfo = mAttachInfo;
10887        if (attachInfo != null) {
10888            return attachInfo.mHandler.post(action);
10889        }
10890        // Assume that post will succeed later
10891        ViewRootImpl.getRunQueue().post(action);
10892        return true;
10893    }
10894
10895    /**
10896     * <p>Causes the Runnable to be added to the message queue, to be run
10897     * after the specified amount of time elapses.
10898     * The runnable will be run on the user interface thread.</p>
10899     *
10900     * @param action The Runnable that will be executed.
10901     * @param delayMillis The delay (in milliseconds) until the Runnable
10902     *        will be executed.
10903     *
10904     * @return true if the Runnable was successfully placed in to the
10905     *         message queue.  Returns false on failure, usually because the
10906     *         looper processing the message queue is exiting.  Note that a
10907     *         result of true does not mean the Runnable will be processed --
10908     *         if the looper is quit before the delivery time of the message
10909     *         occurs then the message will be dropped.
10910     *
10911     * @see #post
10912     * @see #removeCallbacks
10913     */
10914    public boolean postDelayed(Runnable action, long delayMillis) {
10915        final AttachInfo attachInfo = mAttachInfo;
10916        if (attachInfo != null) {
10917            return attachInfo.mHandler.postDelayed(action, delayMillis);
10918        }
10919        // Assume that post will succeed later
10920        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10921        return true;
10922    }
10923
10924    /**
10925     * <p>Causes the Runnable to execute on the next animation time step.
10926     * The runnable will be run on the user interface thread.</p>
10927     *
10928     * @param action The Runnable that will be executed.
10929     *
10930     * @see #postOnAnimationDelayed
10931     * @see #removeCallbacks
10932     */
10933    public void postOnAnimation(Runnable action) {
10934        final AttachInfo attachInfo = mAttachInfo;
10935        if (attachInfo != null) {
10936            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10937                    Choreographer.CALLBACK_ANIMATION, action, null);
10938        } else {
10939            // Assume that post will succeed later
10940            ViewRootImpl.getRunQueue().post(action);
10941        }
10942    }
10943
10944    /**
10945     * <p>Causes the Runnable to execute on the next animation time step,
10946     * after the specified amount of time elapses.
10947     * The runnable will be run on the user interface thread.</p>
10948     *
10949     * @param action The Runnable that will be executed.
10950     * @param delayMillis The delay (in milliseconds) until the Runnable
10951     *        will be executed.
10952     *
10953     * @see #postOnAnimation
10954     * @see #removeCallbacks
10955     */
10956    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10957        final AttachInfo attachInfo = mAttachInfo;
10958        if (attachInfo != null) {
10959            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10960                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10961        } else {
10962            // Assume that post will succeed later
10963            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10964        }
10965    }
10966
10967    /**
10968     * <p>Removes the specified Runnable from the message queue.</p>
10969     *
10970     * @param action The Runnable to remove from the message handling queue
10971     *
10972     * @return true if this view could ask the Handler to remove the Runnable,
10973     *         false otherwise. When the returned value is true, the Runnable
10974     *         may or may not have been actually removed from the message queue
10975     *         (for instance, if the Runnable was not in the queue already.)
10976     *
10977     * @see #post
10978     * @see #postDelayed
10979     * @see #postOnAnimation
10980     * @see #postOnAnimationDelayed
10981     */
10982    public boolean removeCallbacks(Runnable action) {
10983        if (action != null) {
10984            final AttachInfo attachInfo = mAttachInfo;
10985            if (attachInfo != null) {
10986                attachInfo.mHandler.removeCallbacks(action);
10987                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10988                        Choreographer.CALLBACK_ANIMATION, action, null);
10989            } else {
10990                // Assume that post will succeed later
10991                ViewRootImpl.getRunQueue().removeCallbacks(action);
10992            }
10993        }
10994        return true;
10995    }
10996
10997    /**
10998     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10999     * Use this to invalidate the View from a non-UI thread.</p>
11000     *
11001     * <p>This method can be invoked from outside of the UI thread
11002     * only when this View is attached to a window.</p>
11003     *
11004     * @see #invalidate()
11005     * @see #postInvalidateDelayed(long)
11006     */
11007    public void postInvalidate() {
11008        postInvalidateDelayed(0);
11009    }
11010
11011    /**
11012     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11013     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11014     *
11015     * <p>This method can be invoked from outside of the UI thread
11016     * only when this View is attached to a window.</p>
11017     *
11018     * @param left The left coordinate of the rectangle to invalidate.
11019     * @param top The top coordinate of the rectangle to invalidate.
11020     * @param right The right coordinate of the rectangle to invalidate.
11021     * @param bottom The bottom coordinate of the rectangle to invalidate.
11022     *
11023     * @see #invalidate(int, int, int, int)
11024     * @see #invalidate(Rect)
11025     * @see #postInvalidateDelayed(long, int, int, int, int)
11026     */
11027    public void postInvalidate(int left, int top, int right, int bottom) {
11028        postInvalidateDelayed(0, left, top, right, bottom);
11029    }
11030
11031    /**
11032     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11033     * loop. Waits for the specified amount of time.</p>
11034     *
11035     * <p>This method can be invoked from outside of the UI thread
11036     * only when this View is attached to a window.</p>
11037     *
11038     * @param delayMilliseconds the duration in milliseconds to delay the
11039     *         invalidation by
11040     *
11041     * @see #invalidate()
11042     * @see #postInvalidate()
11043     */
11044    public void postInvalidateDelayed(long delayMilliseconds) {
11045        // We try only with the AttachInfo because there's no point in invalidating
11046        // if we are not attached to our window
11047        final AttachInfo attachInfo = mAttachInfo;
11048        if (attachInfo != null) {
11049            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11050        }
11051    }
11052
11053    /**
11054     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11055     * through the event loop. Waits for the specified amount of time.</p>
11056     *
11057     * <p>This method can be invoked from outside of the UI thread
11058     * only when this View is attached to a window.</p>
11059     *
11060     * @param delayMilliseconds the duration in milliseconds to delay the
11061     *         invalidation by
11062     * @param left The left coordinate of the rectangle to invalidate.
11063     * @param top The top coordinate of the rectangle to invalidate.
11064     * @param right The right coordinate of the rectangle to invalidate.
11065     * @param bottom The bottom coordinate of the rectangle to invalidate.
11066     *
11067     * @see #invalidate(int, int, int, int)
11068     * @see #invalidate(Rect)
11069     * @see #postInvalidate(int, int, int, int)
11070     */
11071    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11072            int right, int bottom) {
11073
11074        // We try only with the AttachInfo because there's no point in invalidating
11075        // if we are not attached to our window
11076        final AttachInfo attachInfo = mAttachInfo;
11077        if (attachInfo != null) {
11078            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11079            info.target = this;
11080            info.left = left;
11081            info.top = top;
11082            info.right = right;
11083            info.bottom = bottom;
11084
11085            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11086        }
11087    }
11088
11089    /**
11090     * <p>Cause an invalidate to happen on the next animation time step, typically the
11091     * next display frame.</p>
11092     *
11093     * <p>This method can be invoked from outside of the UI thread
11094     * only when this View is attached to a window.</p>
11095     *
11096     * @see #invalidate()
11097     */
11098    public void postInvalidateOnAnimation() {
11099        // We try only with the AttachInfo because there's no point in invalidating
11100        // if we are not attached to our window
11101        final AttachInfo attachInfo = mAttachInfo;
11102        if (attachInfo != null) {
11103            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11104        }
11105    }
11106
11107    /**
11108     * <p>Cause an invalidate of the specified area to happen on the next animation
11109     * time step, typically the next display frame.</p>
11110     *
11111     * <p>This method can be invoked from outside of the UI thread
11112     * only when this View is attached to a window.</p>
11113     *
11114     * @param left The left coordinate of the rectangle to invalidate.
11115     * @param top The top coordinate of the rectangle to invalidate.
11116     * @param right The right coordinate of the rectangle to invalidate.
11117     * @param bottom The bottom coordinate of the rectangle to invalidate.
11118     *
11119     * @see #invalidate(int, int, int, int)
11120     * @see #invalidate(Rect)
11121     */
11122    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11123        // We try only with the AttachInfo because there's no point in invalidating
11124        // if we are not attached to our window
11125        final AttachInfo attachInfo = mAttachInfo;
11126        if (attachInfo != null) {
11127            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11128            info.target = this;
11129            info.left = left;
11130            info.top = top;
11131            info.right = right;
11132            info.bottom = bottom;
11133
11134            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11135        }
11136    }
11137
11138    /**
11139     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11140     * This event is sent at most once every
11141     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11142     */
11143    private void postSendViewScrolledAccessibilityEventCallback() {
11144        if (mSendViewScrolledAccessibilityEvent == null) {
11145            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11146        }
11147        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11148            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11149            postDelayed(mSendViewScrolledAccessibilityEvent,
11150                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11151        }
11152    }
11153
11154    /**
11155     * Called by a parent to request that a child update its values for mScrollX
11156     * and mScrollY if necessary. This will typically be done if the child is
11157     * animating a scroll using a {@link android.widget.Scroller Scroller}
11158     * object.
11159     */
11160    public void computeScroll() {
11161    }
11162
11163    /**
11164     * <p>Indicate whether the horizontal edges are faded when the view is
11165     * scrolled horizontally.</p>
11166     *
11167     * @return true if the horizontal edges should are faded on scroll, false
11168     *         otherwise
11169     *
11170     * @see #setHorizontalFadingEdgeEnabled(boolean)
11171     *
11172     * @attr ref android.R.styleable#View_requiresFadingEdge
11173     */
11174    public boolean isHorizontalFadingEdgeEnabled() {
11175        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11176    }
11177
11178    /**
11179     * <p>Define whether the horizontal edges should be faded when this view
11180     * is scrolled horizontally.</p>
11181     *
11182     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11183     *                                    be faded when the view is scrolled
11184     *                                    horizontally
11185     *
11186     * @see #isHorizontalFadingEdgeEnabled()
11187     *
11188     * @attr ref android.R.styleable#View_requiresFadingEdge
11189     */
11190    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11191        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11192            if (horizontalFadingEdgeEnabled) {
11193                initScrollCache();
11194            }
11195
11196            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11197        }
11198    }
11199
11200    /**
11201     * <p>Indicate whether the vertical edges are faded when the view is
11202     * scrolled horizontally.</p>
11203     *
11204     * @return true if the vertical edges should are faded on scroll, false
11205     *         otherwise
11206     *
11207     * @see #setVerticalFadingEdgeEnabled(boolean)
11208     *
11209     * @attr ref android.R.styleable#View_requiresFadingEdge
11210     */
11211    public boolean isVerticalFadingEdgeEnabled() {
11212        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11213    }
11214
11215    /**
11216     * <p>Define whether the vertical edges should be faded when this view
11217     * is scrolled vertically.</p>
11218     *
11219     * @param verticalFadingEdgeEnabled true if the vertical edges should
11220     *                                  be faded when the view is scrolled
11221     *                                  vertically
11222     *
11223     * @see #isVerticalFadingEdgeEnabled()
11224     *
11225     * @attr ref android.R.styleable#View_requiresFadingEdge
11226     */
11227    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11228        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11229            if (verticalFadingEdgeEnabled) {
11230                initScrollCache();
11231            }
11232
11233            mViewFlags ^= FADING_EDGE_VERTICAL;
11234        }
11235    }
11236
11237    /**
11238     * Returns the strength, or intensity, of the top faded edge. The strength is
11239     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11240     * returns 0.0 or 1.0 but no value in between.
11241     *
11242     * Subclasses should override this method to provide a smoother fade transition
11243     * when scrolling occurs.
11244     *
11245     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11246     */
11247    protected float getTopFadingEdgeStrength() {
11248        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11249    }
11250
11251    /**
11252     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11253     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11254     * returns 0.0 or 1.0 but no value in between.
11255     *
11256     * Subclasses should override this method to provide a smoother fade transition
11257     * when scrolling occurs.
11258     *
11259     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11260     */
11261    protected float getBottomFadingEdgeStrength() {
11262        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11263                computeVerticalScrollRange() ? 1.0f : 0.0f;
11264    }
11265
11266    /**
11267     * Returns the strength, or intensity, of the left faded edge. The strength is
11268     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11269     * returns 0.0 or 1.0 but no value in between.
11270     *
11271     * Subclasses should override this method to provide a smoother fade transition
11272     * when scrolling occurs.
11273     *
11274     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11275     */
11276    protected float getLeftFadingEdgeStrength() {
11277        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11278    }
11279
11280    /**
11281     * Returns the strength, or intensity, of the right faded edge. The strength is
11282     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11283     * returns 0.0 or 1.0 but no value in between.
11284     *
11285     * Subclasses should override this method to provide a smoother fade transition
11286     * when scrolling occurs.
11287     *
11288     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11289     */
11290    protected float getRightFadingEdgeStrength() {
11291        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11292                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11293    }
11294
11295    /**
11296     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11297     * scrollbar is not drawn by default.</p>
11298     *
11299     * @return true if the horizontal scrollbar should be painted, false
11300     *         otherwise
11301     *
11302     * @see #setHorizontalScrollBarEnabled(boolean)
11303     */
11304    public boolean isHorizontalScrollBarEnabled() {
11305        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11306    }
11307
11308    /**
11309     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11310     * scrollbar is not drawn by default.</p>
11311     *
11312     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11313     *                                   be painted
11314     *
11315     * @see #isHorizontalScrollBarEnabled()
11316     */
11317    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11318        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11319            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11320            computeOpaqueFlags();
11321            resolvePadding();
11322        }
11323    }
11324
11325    /**
11326     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11327     * scrollbar is not drawn by default.</p>
11328     *
11329     * @return true if the vertical scrollbar should be painted, false
11330     *         otherwise
11331     *
11332     * @see #setVerticalScrollBarEnabled(boolean)
11333     */
11334    public boolean isVerticalScrollBarEnabled() {
11335        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11336    }
11337
11338    /**
11339     * <p>Define whether the vertical scrollbar should be drawn or not. The
11340     * scrollbar is not drawn by default.</p>
11341     *
11342     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11343     *                                 be painted
11344     *
11345     * @see #isVerticalScrollBarEnabled()
11346     */
11347    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11348        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11349            mViewFlags ^= SCROLLBARS_VERTICAL;
11350            computeOpaqueFlags();
11351            resolvePadding();
11352        }
11353    }
11354
11355    /**
11356     * @hide
11357     */
11358    protected void recomputePadding() {
11359        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11360    }
11361
11362    /**
11363     * Define whether scrollbars will fade when the view is not scrolling.
11364     *
11365     * @param fadeScrollbars wheter to enable fading
11366     *
11367     * @attr ref android.R.styleable#View_fadeScrollbars
11368     */
11369    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11370        initScrollCache();
11371        final ScrollabilityCache scrollabilityCache = mScrollCache;
11372        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11373        if (fadeScrollbars) {
11374            scrollabilityCache.state = ScrollabilityCache.OFF;
11375        } else {
11376            scrollabilityCache.state = ScrollabilityCache.ON;
11377        }
11378    }
11379
11380    /**
11381     *
11382     * Returns true if scrollbars will fade when this view is not scrolling
11383     *
11384     * @return true if scrollbar fading is enabled
11385     *
11386     * @attr ref android.R.styleable#View_fadeScrollbars
11387     */
11388    public boolean isScrollbarFadingEnabled() {
11389        return mScrollCache != null && mScrollCache.fadeScrollBars;
11390    }
11391
11392    /**
11393     *
11394     * Returns the delay before scrollbars fade.
11395     *
11396     * @return the delay before scrollbars fade
11397     *
11398     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11399     */
11400    public int getScrollBarDefaultDelayBeforeFade() {
11401        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11402                mScrollCache.scrollBarDefaultDelayBeforeFade;
11403    }
11404
11405    /**
11406     * Define the delay before scrollbars fade.
11407     *
11408     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11409     *
11410     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11411     */
11412    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11413        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11414    }
11415
11416    /**
11417     *
11418     * Returns the scrollbar fade duration.
11419     *
11420     * @return the scrollbar fade duration
11421     *
11422     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11423     */
11424    public int getScrollBarFadeDuration() {
11425        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11426                mScrollCache.scrollBarFadeDuration;
11427    }
11428
11429    /**
11430     * Define the scrollbar fade duration.
11431     *
11432     * @param scrollBarFadeDuration - the scrollbar fade duration
11433     *
11434     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11435     */
11436    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11437        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11438    }
11439
11440    /**
11441     *
11442     * Returns the scrollbar size.
11443     *
11444     * @return the scrollbar size
11445     *
11446     * @attr ref android.R.styleable#View_scrollbarSize
11447     */
11448    public int getScrollBarSize() {
11449        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11450                mScrollCache.scrollBarSize;
11451    }
11452
11453    /**
11454     * Define the scrollbar size.
11455     *
11456     * @param scrollBarSize - the scrollbar size
11457     *
11458     * @attr ref android.R.styleable#View_scrollbarSize
11459     */
11460    public void setScrollBarSize(int scrollBarSize) {
11461        getScrollCache().scrollBarSize = scrollBarSize;
11462    }
11463
11464    /**
11465     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11466     * inset. When inset, they add to the padding of the view. And the scrollbars
11467     * can be drawn inside the padding area or on the edge of the view. For example,
11468     * if a view has a background drawable and you want to draw the scrollbars
11469     * inside the padding specified by the drawable, you can use
11470     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11471     * appear at the edge of the view, ignoring the padding, then you can use
11472     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11473     * @param style the style of the scrollbars. Should be one of
11474     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11475     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11476     * @see #SCROLLBARS_INSIDE_OVERLAY
11477     * @see #SCROLLBARS_INSIDE_INSET
11478     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11479     * @see #SCROLLBARS_OUTSIDE_INSET
11480     *
11481     * @attr ref android.R.styleable#View_scrollbarStyle
11482     */
11483    public void setScrollBarStyle(int style) {
11484        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11485            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11486            computeOpaqueFlags();
11487            resolvePadding();
11488        }
11489    }
11490
11491    /**
11492     * <p>Returns the current scrollbar style.</p>
11493     * @return the current scrollbar style
11494     * @see #SCROLLBARS_INSIDE_OVERLAY
11495     * @see #SCROLLBARS_INSIDE_INSET
11496     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11497     * @see #SCROLLBARS_OUTSIDE_INSET
11498     *
11499     * @attr ref android.R.styleable#View_scrollbarStyle
11500     */
11501    @ViewDebug.ExportedProperty(mapping = {
11502            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11503            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11504            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11505            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11506    })
11507    public int getScrollBarStyle() {
11508        return mViewFlags & SCROLLBARS_STYLE_MASK;
11509    }
11510
11511    /**
11512     * <p>Compute the horizontal range that the horizontal scrollbar
11513     * represents.</p>
11514     *
11515     * <p>The range is expressed in arbitrary units that must be the same as the
11516     * units used by {@link #computeHorizontalScrollExtent()} and
11517     * {@link #computeHorizontalScrollOffset()}.</p>
11518     *
11519     * <p>The default range is the drawing width of this view.</p>
11520     *
11521     * @return the total horizontal range represented by the horizontal
11522     *         scrollbar
11523     *
11524     * @see #computeHorizontalScrollExtent()
11525     * @see #computeHorizontalScrollOffset()
11526     * @see android.widget.ScrollBarDrawable
11527     */
11528    protected int computeHorizontalScrollRange() {
11529        return getWidth();
11530    }
11531
11532    /**
11533     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11534     * within the horizontal range. This value is used to compute the position
11535     * of the thumb within the scrollbar's track.</p>
11536     *
11537     * <p>The range is expressed in arbitrary units that must be the same as the
11538     * units used by {@link #computeHorizontalScrollRange()} and
11539     * {@link #computeHorizontalScrollExtent()}.</p>
11540     *
11541     * <p>The default offset is the scroll offset of this view.</p>
11542     *
11543     * @return the horizontal offset of the scrollbar's thumb
11544     *
11545     * @see #computeHorizontalScrollRange()
11546     * @see #computeHorizontalScrollExtent()
11547     * @see android.widget.ScrollBarDrawable
11548     */
11549    protected int computeHorizontalScrollOffset() {
11550        return mScrollX;
11551    }
11552
11553    /**
11554     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11555     * within the horizontal range. This value is used to compute the length
11556     * of the thumb within the scrollbar's track.</p>
11557     *
11558     * <p>The range is expressed in arbitrary units that must be the same as the
11559     * units used by {@link #computeHorizontalScrollRange()} and
11560     * {@link #computeHorizontalScrollOffset()}.</p>
11561     *
11562     * <p>The default extent is the drawing width of this view.</p>
11563     *
11564     * @return the horizontal extent of the scrollbar's thumb
11565     *
11566     * @see #computeHorizontalScrollRange()
11567     * @see #computeHorizontalScrollOffset()
11568     * @see android.widget.ScrollBarDrawable
11569     */
11570    protected int computeHorizontalScrollExtent() {
11571        return getWidth();
11572    }
11573
11574    /**
11575     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11576     *
11577     * <p>The range is expressed in arbitrary units that must be the same as the
11578     * units used by {@link #computeVerticalScrollExtent()} and
11579     * {@link #computeVerticalScrollOffset()}.</p>
11580     *
11581     * @return the total vertical range represented by the vertical scrollbar
11582     *
11583     * <p>The default range is the drawing height of this view.</p>
11584     *
11585     * @see #computeVerticalScrollExtent()
11586     * @see #computeVerticalScrollOffset()
11587     * @see android.widget.ScrollBarDrawable
11588     */
11589    protected int computeVerticalScrollRange() {
11590        return getHeight();
11591    }
11592
11593    /**
11594     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11595     * within the horizontal range. This value is used to compute the position
11596     * of the thumb within the scrollbar's track.</p>
11597     *
11598     * <p>The range is expressed in arbitrary units that must be the same as the
11599     * units used by {@link #computeVerticalScrollRange()} and
11600     * {@link #computeVerticalScrollExtent()}.</p>
11601     *
11602     * <p>The default offset is the scroll offset of this view.</p>
11603     *
11604     * @return the vertical offset of the scrollbar's thumb
11605     *
11606     * @see #computeVerticalScrollRange()
11607     * @see #computeVerticalScrollExtent()
11608     * @see android.widget.ScrollBarDrawable
11609     */
11610    protected int computeVerticalScrollOffset() {
11611        return mScrollY;
11612    }
11613
11614    /**
11615     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11616     * within the vertical range. This value is used to compute the length
11617     * of the thumb within the scrollbar's track.</p>
11618     *
11619     * <p>The range is expressed in arbitrary units that must be the same as the
11620     * units used by {@link #computeVerticalScrollRange()} and
11621     * {@link #computeVerticalScrollOffset()}.</p>
11622     *
11623     * <p>The default extent is the drawing height of this view.</p>
11624     *
11625     * @return the vertical extent of the scrollbar's thumb
11626     *
11627     * @see #computeVerticalScrollRange()
11628     * @see #computeVerticalScrollOffset()
11629     * @see android.widget.ScrollBarDrawable
11630     */
11631    protected int computeVerticalScrollExtent() {
11632        return getHeight();
11633    }
11634
11635    /**
11636     * Check if this view can be scrolled horizontally in a certain direction.
11637     *
11638     * @param direction Negative to check scrolling left, positive to check scrolling right.
11639     * @return true if this view can be scrolled in the specified direction, false otherwise.
11640     */
11641    public boolean canScrollHorizontally(int direction) {
11642        final int offset = computeHorizontalScrollOffset();
11643        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11644        if (range == 0) return false;
11645        if (direction < 0) {
11646            return offset > 0;
11647        } else {
11648            return offset < range - 1;
11649        }
11650    }
11651
11652    /**
11653     * Check if this view can be scrolled vertically in a certain direction.
11654     *
11655     * @param direction Negative to check scrolling up, positive to check scrolling down.
11656     * @return true if this view can be scrolled in the specified direction, false otherwise.
11657     */
11658    public boolean canScrollVertically(int direction) {
11659        final int offset = computeVerticalScrollOffset();
11660        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11661        if (range == 0) return false;
11662        if (direction < 0) {
11663            return offset > 0;
11664        } else {
11665            return offset < range - 1;
11666        }
11667    }
11668
11669    /**
11670     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11671     * scrollbars are painted only if they have been awakened first.</p>
11672     *
11673     * @param canvas the canvas on which to draw the scrollbars
11674     *
11675     * @see #awakenScrollBars(int)
11676     */
11677    protected final void onDrawScrollBars(Canvas canvas) {
11678        // scrollbars are drawn only when the animation is running
11679        final ScrollabilityCache cache = mScrollCache;
11680        if (cache != null) {
11681
11682            int state = cache.state;
11683
11684            if (state == ScrollabilityCache.OFF) {
11685                return;
11686            }
11687
11688            boolean invalidate = false;
11689
11690            if (state == ScrollabilityCache.FADING) {
11691                // We're fading -- get our fade interpolation
11692                if (cache.interpolatorValues == null) {
11693                    cache.interpolatorValues = new float[1];
11694                }
11695
11696                float[] values = cache.interpolatorValues;
11697
11698                // Stops the animation if we're done
11699                if (cache.scrollBarInterpolator.timeToValues(values) ==
11700                        Interpolator.Result.FREEZE_END) {
11701                    cache.state = ScrollabilityCache.OFF;
11702                } else {
11703                    cache.scrollBar.setAlpha(Math.round(values[0]));
11704                }
11705
11706                // This will make the scroll bars inval themselves after
11707                // drawing. We only want this when we're fading so that
11708                // we prevent excessive redraws
11709                invalidate = true;
11710            } else {
11711                // We're just on -- but we may have been fading before so
11712                // reset alpha
11713                cache.scrollBar.setAlpha(255);
11714            }
11715
11716
11717            final int viewFlags = mViewFlags;
11718
11719            final boolean drawHorizontalScrollBar =
11720                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11721            final boolean drawVerticalScrollBar =
11722                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11723                && !isVerticalScrollBarHidden();
11724
11725            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11726                final int width = mRight - mLeft;
11727                final int height = mBottom - mTop;
11728
11729                final ScrollBarDrawable scrollBar = cache.scrollBar;
11730
11731                final int scrollX = mScrollX;
11732                final int scrollY = mScrollY;
11733                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11734
11735                int left;
11736                int top;
11737                int right;
11738                int bottom;
11739
11740                if (drawHorizontalScrollBar) {
11741                    int size = scrollBar.getSize(false);
11742                    if (size <= 0) {
11743                        size = cache.scrollBarSize;
11744                    }
11745
11746                    scrollBar.setParameters(computeHorizontalScrollRange(),
11747                                            computeHorizontalScrollOffset(),
11748                                            computeHorizontalScrollExtent(), false);
11749                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11750                            getVerticalScrollbarWidth() : 0;
11751                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11752                    left = scrollX + (mPaddingLeft & inside);
11753                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11754                    bottom = top + size;
11755                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11756                    if (invalidate) {
11757                        invalidate(left, top, right, bottom);
11758                    }
11759                }
11760
11761                if (drawVerticalScrollBar) {
11762                    int size = scrollBar.getSize(true);
11763                    if (size <= 0) {
11764                        size = cache.scrollBarSize;
11765                    }
11766
11767                    scrollBar.setParameters(computeVerticalScrollRange(),
11768                                            computeVerticalScrollOffset(),
11769                                            computeVerticalScrollExtent(), true);
11770                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11771                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11772                        verticalScrollbarPosition = isLayoutRtl() ?
11773                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11774                    }
11775                    switch (verticalScrollbarPosition) {
11776                        default:
11777                        case SCROLLBAR_POSITION_RIGHT:
11778                            left = scrollX + width - size - (mUserPaddingRight & inside);
11779                            break;
11780                        case SCROLLBAR_POSITION_LEFT:
11781                            left = scrollX + (mUserPaddingLeft & inside);
11782                            break;
11783                    }
11784                    top = scrollY + (mPaddingTop & inside);
11785                    right = left + size;
11786                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11787                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11788                    if (invalidate) {
11789                        invalidate(left, top, right, bottom);
11790                    }
11791                }
11792            }
11793        }
11794    }
11795
11796    /**
11797     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11798     * FastScroller is visible.
11799     * @return whether to temporarily hide the vertical scrollbar
11800     * @hide
11801     */
11802    protected boolean isVerticalScrollBarHidden() {
11803        return false;
11804    }
11805
11806    /**
11807     * <p>Draw the horizontal scrollbar if
11808     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11809     *
11810     * @param canvas the canvas on which to draw the scrollbar
11811     * @param scrollBar the scrollbar's drawable
11812     *
11813     * @see #isHorizontalScrollBarEnabled()
11814     * @see #computeHorizontalScrollRange()
11815     * @see #computeHorizontalScrollExtent()
11816     * @see #computeHorizontalScrollOffset()
11817     * @see android.widget.ScrollBarDrawable
11818     * @hide
11819     */
11820    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11821            int l, int t, int r, int b) {
11822        scrollBar.setBounds(l, t, r, b);
11823        scrollBar.draw(canvas);
11824    }
11825
11826    /**
11827     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11828     * returns true.</p>
11829     *
11830     * @param canvas the canvas on which to draw the scrollbar
11831     * @param scrollBar the scrollbar's drawable
11832     *
11833     * @see #isVerticalScrollBarEnabled()
11834     * @see #computeVerticalScrollRange()
11835     * @see #computeVerticalScrollExtent()
11836     * @see #computeVerticalScrollOffset()
11837     * @see android.widget.ScrollBarDrawable
11838     * @hide
11839     */
11840    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11841            int l, int t, int r, int b) {
11842        scrollBar.setBounds(l, t, r, b);
11843        scrollBar.draw(canvas);
11844    }
11845
11846    /**
11847     * Implement this to do your drawing.
11848     *
11849     * @param canvas the canvas on which the background will be drawn
11850     */
11851    protected void onDraw(Canvas canvas) {
11852    }
11853
11854    /*
11855     * Caller is responsible for calling requestLayout if necessary.
11856     * (This allows addViewInLayout to not request a new layout.)
11857     */
11858    void assignParent(ViewParent parent) {
11859        if (mParent == null) {
11860            mParent = parent;
11861        } else if (parent == null) {
11862            mParent = null;
11863        } else {
11864            throw new RuntimeException("view " + this + " being added, but"
11865                    + " it already has a parent");
11866        }
11867    }
11868
11869    /**
11870     * This is called when the view is attached to a window.  At this point it
11871     * has a Surface and will start drawing.  Note that this function is
11872     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11873     * however it may be called any time before the first onDraw -- including
11874     * before or after {@link #onMeasure(int, int)}.
11875     *
11876     * @see #onDetachedFromWindow()
11877     */
11878    protected void onAttachedToWindow() {
11879        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11880            mParent.requestTransparentRegion(this);
11881        }
11882
11883        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11884            initialAwakenScrollBars();
11885            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11886        }
11887
11888        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11889
11890        jumpDrawablesToCurrentState();
11891
11892        resetSubtreeAccessibilityStateChanged();
11893
11894        if (isFocused()) {
11895            InputMethodManager imm = InputMethodManager.peekInstance();
11896            imm.focusIn(this);
11897        }
11898
11899        if (mDisplayList != null) {
11900            mDisplayList.clearDirty();
11901        }
11902    }
11903
11904    /**
11905     * Resolve all RTL related properties.
11906     *
11907     * @return true if resolution of RTL properties has been done
11908     *
11909     * @hide
11910     */
11911    public boolean resolveRtlPropertiesIfNeeded() {
11912        if (!needRtlPropertiesResolution()) return false;
11913
11914        // Order is important here: LayoutDirection MUST be resolved first
11915        if (!isLayoutDirectionResolved()) {
11916            resolveLayoutDirection();
11917            resolveLayoutParams();
11918        }
11919        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11920        if (!isTextDirectionResolved()) {
11921            resolveTextDirection();
11922        }
11923        if (!isTextAlignmentResolved()) {
11924            resolveTextAlignment();
11925        }
11926        if (!isPaddingResolved()) {
11927            resolvePadding();
11928        }
11929        if (!isDrawablesResolved()) {
11930            resolveDrawables();
11931        }
11932        onRtlPropertiesChanged(getLayoutDirection());
11933        return true;
11934    }
11935
11936    /**
11937     * Reset resolution of all RTL related properties.
11938     *
11939     * @hide
11940     */
11941    public void resetRtlProperties() {
11942        resetResolvedLayoutDirection();
11943        resetResolvedTextDirection();
11944        resetResolvedTextAlignment();
11945        resetResolvedPadding();
11946        resetResolvedDrawables();
11947    }
11948
11949    /**
11950     * @see #onScreenStateChanged(int)
11951     */
11952    void dispatchScreenStateChanged(int screenState) {
11953        onScreenStateChanged(screenState);
11954    }
11955
11956    /**
11957     * This method is called whenever the state of the screen this view is
11958     * attached to changes. A state change will usually occurs when the screen
11959     * turns on or off (whether it happens automatically or the user does it
11960     * manually.)
11961     *
11962     * @param screenState The new state of the screen. Can be either
11963     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11964     */
11965    public void onScreenStateChanged(int screenState) {
11966    }
11967
11968    /**
11969     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11970     */
11971    private boolean hasRtlSupport() {
11972        return mContext.getApplicationInfo().hasRtlSupport();
11973    }
11974
11975    /**
11976     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11977     * RTL not supported)
11978     */
11979    private boolean isRtlCompatibilityMode() {
11980        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11981        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11982    }
11983
11984    /**
11985     * @return true if RTL properties need resolution.
11986     *
11987     */
11988    private boolean needRtlPropertiesResolution() {
11989        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11990    }
11991
11992    /**
11993     * Called when any RTL property (layout direction or text direction or text alignment) has
11994     * been changed.
11995     *
11996     * Subclasses need to override this method to take care of cached information that depends on the
11997     * resolved layout direction, or to inform child views that inherit their layout direction.
11998     *
11999     * The default implementation does nothing.
12000     *
12001     * @param layoutDirection the direction of the layout
12002     *
12003     * @see #LAYOUT_DIRECTION_LTR
12004     * @see #LAYOUT_DIRECTION_RTL
12005     */
12006    public void onRtlPropertiesChanged(int layoutDirection) {
12007    }
12008
12009    /**
12010     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12011     * that the parent directionality can and will be resolved before its children.
12012     *
12013     * @return true if resolution has been done, false otherwise.
12014     *
12015     * @hide
12016     */
12017    public boolean resolveLayoutDirection() {
12018        // Clear any previous layout direction resolution
12019        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12020
12021        if (hasRtlSupport()) {
12022            // Set resolved depending on layout direction
12023            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12024                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12025                case LAYOUT_DIRECTION_INHERIT:
12026                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12027                    // later to get the correct resolved value
12028                    if (!canResolveLayoutDirection()) return false;
12029
12030                    // Parent has not yet resolved, LTR is still the default
12031                    try {
12032                        if (!mParent.isLayoutDirectionResolved()) return false;
12033
12034                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12035                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12036                        }
12037                    } catch (AbstractMethodError e) {
12038                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12039                                " does not fully implement ViewParent", e);
12040                    }
12041                    break;
12042                case LAYOUT_DIRECTION_RTL:
12043                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12044                    break;
12045                case LAYOUT_DIRECTION_LOCALE:
12046                    if((LAYOUT_DIRECTION_RTL ==
12047                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12048                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12049                    }
12050                    break;
12051                default:
12052                    // Nothing to do, LTR by default
12053            }
12054        }
12055
12056        // Set to resolved
12057        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12058        return true;
12059    }
12060
12061    /**
12062     * Check if layout direction resolution can be done.
12063     *
12064     * @return true if layout direction resolution can be done otherwise return false.
12065     */
12066    public boolean canResolveLayoutDirection() {
12067        switch (getRawLayoutDirection()) {
12068            case LAYOUT_DIRECTION_INHERIT:
12069                if (mParent != null) {
12070                    try {
12071                        return mParent.canResolveLayoutDirection();
12072                    } catch (AbstractMethodError e) {
12073                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12074                                " does not fully implement ViewParent", e);
12075                    }
12076                }
12077                return false;
12078
12079            default:
12080                return true;
12081        }
12082    }
12083
12084    /**
12085     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12086     * {@link #onMeasure(int, int)}.
12087     *
12088     * @hide
12089     */
12090    public void resetResolvedLayoutDirection() {
12091        // Reset the current resolved bits
12092        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12093    }
12094
12095    /**
12096     * @return true if the layout direction is inherited.
12097     *
12098     * @hide
12099     */
12100    public boolean isLayoutDirectionInherited() {
12101        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12102    }
12103
12104    /**
12105     * @return true if layout direction has been resolved.
12106     */
12107    public boolean isLayoutDirectionResolved() {
12108        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12109    }
12110
12111    /**
12112     * Return if padding has been resolved
12113     *
12114     * @hide
12115     */
12116    boolean isPaddingResolved() {
12117        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12118    }
12119
12120    /**
12121     * Resolves padding depending on layout direction, if applicable, and
12122     * recomputes internal padding values to adjust for scroll bars.
12123     *
12124     * @hide
12125     */
12126    public void resolvePadding() {
12127        final int resolvedLayoutDirection = getLayoutDirection();
12128
12129        if (!isRtlCompatibilityMode()) {
12130            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12131            // If start / end padding are defined, they will be resolved (hence overriding) to
12132            // left / right or right / left depending on the resolved layout direction.
12133            // If start / end padding are not defined, use the left / right ones.
12134            switch (resolvedLayoutDirection) {
12135                case LAYOUT_DIRECTION_RTL:
12136                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12137                        mUserPaddingRight = mUserPaddingStart;
12138                    } else {
12139                        mUserPaddingRight = mUserPaddingRightInitial;
12140                    }
12141                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12142                        mUserPaddingLeft = mUserPaddingEnd;
12143                    } else {
12144                        mUserPaddingLeft = mUserPaddingLeftInitial;
12145                    }
12146                    break;
12147                case LAYOUT_DIRECTION_LTR:
12148                default:
12149                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12150                        mUserPaddingLeft = mUserPaddingStart;
12151                    } else {
12152                        mUserPaddingLeft = mUserPaddingLeftInitial;
12153                    }
12154                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12155                        mUserPaddingRight = mUserPaddingEnd;
12156                    } else {
12157                        mUserPaddingRight = mUserPaddingRightInitial;
12158                    }
12159            }
12160
12161            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12162        }
12163
12164        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12165        onRtlPropertiesChanged(resolvedLayoutDirection);
12166
12167        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12168    }
12169
12170    /**
12171     * Reset the resolved layout direction.
12172     *
12173     * @hide
12174     */
12175    public void resetResolvedPadding() {
12176        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12177    }
12178
12179    /**
12180     * This is called when the view is detached from a window.  At this point it
12181     * no longer has a surface for drawing.
12182     *
12183     * @see #onAttachedToWindow()
12184     */
12185    protected void onDetachedFromWindow() {
12186        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12187        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12188
12189        removeUnsetPressCallback();
12190        removeLongPressCallback();
12191        removePerformClickCallback();
12192        removeSendViewScrolledAccessibilityEventCallback();
12193
12194        destroyDrawingCache();
12195        destroyLayer(false);
12196
12197        cleanupDraw();
12198
12199        mCurrentAnimation = null;
12200    }
12201
12202    private void cleanupDraw() {
12203        if (mAttachInfo != null) {
12204            if (mDisplayList != null) {
12205                mDisplayList.markDirty();
12206                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12207            }
12208            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12209        } else {
12210            // Should never happen
12211            resetDisplayList();
12212        }
12213    }
12214
12215    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12216    }
12217
12218    /**
12219     * @return The number of times this view has been attached to a window
12220     */
12221    protected int getWindowAttachCount() {
12222        return mWindowAttachCount;
12223    }
12224
12225    /**
12226     * Retrieve a unique token identifying the window this view is attached to.
12227     * @return Return the window's token for use in
12228     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12229     */
12230    public IBinder getWindowToken() {
12231        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12232    }
12233
12234    /**
12235     * Retrieve the {@link WindowId} for the window this view is
12236     * currently attached to.
12237     */
12238    public WindowId getWindowId() {
12239        if (mAttachInfo == null) {
12240            return null;
12241        }
12242        if (mAttachInfo.mWindowId == null) {
12243            try {
12244                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12245                        mAttachInfo.mWindowToken);
12246                mAttachInfo.mWindowId = new WindowId(
12247                        mAttachInfo.mIWindowId);
12248            } catch (RemoteException e) {
12249            }
12250        }
12251        return mAttachInfo.mWindowId;
12252    }
12253
12254    /**
12255     * Retrieve a unique token identifying the top-level "real" window of
12256     * the window that this view is attached to.  That is, this is like
12257     * {@link #getWindowToken}, except if the window this view in is a panel
12258     * window (attached to another containing window), then the token of
12259     * the containing window is returned instead.
12260     *
12261     * @return Returns the associated window token, either
12262     * {@link #getWindowToken()} or the containing window's token.
12263     */
12264    public IBinder getApplicationWindowToken() {
12265        AttachInfo ai = mAttachInfo;
12266        if (ai != null) {
12267            IBinder appWindowToken = ai.mPanelParentWindowToken;
12268            if (appWindowToken == null) {
12269                appWindowToken = ai.mWindowToken;
12270            }
12271            return appWindowToken;
12272        }
12273        return null;
12274    }
12275
12276    /**
12277     * Gets the logical display to which the view's window has been attached.
12278     *
12279     * @return The logical display, or null if the view is not currently attached to a window.
12280     */
12281    public Display getDisplay() {
12282        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12283    }
12284
12285    /**
12286     * Retrieve private session object this view hierarchy is using to
12287     * communicate with the window manager.
12288     * @return the session object to communicate with the window manager
12289     */
12290    /*package*/ IWindowSession getWindowSession() {
12291        return mAttachInfo != null ? mAttachInfo.mSession : null;
12292    }
12293
12294    /**
12295     * @param info the {@link android.view.View.AttachInfo} to associated with
12296     *        this view
12297     */
12298    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12299        //System.out.println("Attached! " + this);
12300        mAttachInfo = info;
12301        if (mOverlay != null) {
12302            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12303        }
12304        mWindowAttachCount++;
12305        // We will need to evaluate the drawable state at least once.
12306        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12307        if (mFloatingTreeObserver != null) {
12308            info.mTreeObserver.merge(mFloatingTreeObserver);
12309            mFloatingTreeObserver = null;
12310        }
12311        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12312            mAttachInfo.mScrollContainers.add(this);
12313            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12314        }
12315        performCollectViewAttributes(mAttachInfo, visibility);
12316        onAttachedToWindow();
12317
12318        ListenerInfo li = mListenerInfo;
12319        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12320                li != null ? li.mOnAttachStateChangeListeners : null;
12321        if (listeners != null && listeners.size() > 0) {
12322            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12323            // perform the dispatching. The iterator is a safe guard against listeners that
12324            // could mutate the list by calling the various add/remove methods. This prevents
12325            // the array from being modified while we iterate it.
12326            for (OnAttachStateChangeListener listener : listeners) {
12327                listener.onViewAttachedToWindow(this);
12328            }
12329        }
12330
12331        int vis = info.mWindowVisibility;
12332        if (vis != GONE) {
12333            onWindowVisibilityChanged(vis);
12334        }
12335        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12336            // If nobody has evaluated the drawable state yet, then do it now.
12337            refreshDrawableState();
12338        }
12339        needGlobalAttributesUpdate(false);
12340    }
12341
12342    void dispatchDetachedFromWindow() {
12343        AttachInfo info = mAttachInfo;
12344        if (info != null) {
12345            int vis = info.mWindowVisibility;
12346            if (vis != GONE) {
12347                onWindowVisibilityChanged(GONE);
12348            }
12349        }
12350
12351        onDetachedFromWindow();
12352
12353        ListenerInfo li = mListenerInfo;
12354        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12355                li != null ? li.mOnAttachStateChangeListeners : null;
12356        if (listeners != null && listeners.size() > 0) {
12357            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12358            // perform the dispatching. The iterator is a safe guard against listeners that
12359            // could mutate the list by calling the various add/remove methods. This prevents
12360            // the array from being modified while we iterate it.
12361            for (OnAttachStateChangeListener listener : listeners) {
12362                listener.onViewDetachedFromWindow(this);
12363            }
12364        }
12365
12366        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12367            mAttachInfo.mScrollContainers.remove(this);
12368            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12369        }
12370
12371        mAttachInfo = null;
12372        if (mOverlay != null) {
12373            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12374        }
12375    }
12376
12377    /**
12378     * Cancel any deferred high-level input events that were previously posted to the event queue.
12379     *
12380     * <p>Many views post high-level events such as click handlers to the event queue
12381     * to run deferred in order to preserve a desired user experience - clearing visible
12382     * pressed states before executing, etc. This method will abort any events of this nature
12383     * that are currently in flight.</p>
12384     *
12385     * <p>Custom views that generate their own high-level deferred input events should override
12386     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
12387     *
12388     * <p>This will also cancel pending input events for any child views.</p>
12389     *
12390     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
12391     * This will not impact newer events posted after this call that may occur as a result of
12392     * lower-level input events still waiting in the queue. If you are trying to prevent
12393     * double-submitted  events for the duration of some sort of asynchronous transaction
12394     * you should also take other steps to protect against unexpected double inputs e.g. calling
12395     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
12396     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
12397     */
12398    public final void cancelPendingInputEvents() {
12399        dispatchCancelPendingInputEvents();
12400    }
12401
12402    /**
12403     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
12404     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
12405     */
12406    void dispatchCancelPendingInputEvents() {
12407        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
12408        onCancelPendingInputEvents();
12409        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
12410            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
12411                    " did not call through to super.onCancelPendingInputEvents()");
12412        }
12413    }
12414
12415    /**
12416     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
12417     * a parent view.
12418     *
12419     * <p>This method is responsible for removing any pending high-level input events that were
12420     * posted to the event queue to run later. Custom view classes that post their own deferred
12421     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
12422     * {@link android.os.Handler} should override this method, call
12423     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
12424     * </p>
12425     */
12426    public void onCancelPendingInputEvents() {
12427        removePerformClickCallback();
12428        cancelLongPress();
12429        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
12430    }
12431
12432    /**
12433     * Store this view hierarchy's frozen state into the given container.
12434     *
12435     * @param container The SparseArray in which to save the view's state.
12436     *
12437     * @see #restoreHierarchyState(android.util.SparseArray)
12438     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12439     * @see #onSaveInstanceState()
12440     */
12441    public void saveHierarchyState(SparseArray<Parcelable> container) {
12442        dispatchSaveInstanceState(container);
12443    }
12444
12445    /**
12446     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12447     * this view and its children. May be overridden to modify how freezing happens to a
12448     * view's children; for example, some views may want to not store state for their children.
12449     *
12450     * @param container The SparseArray in which to save the view's state.
12451     *
12452     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12453     * @see #saveHierarchyState(android.util.SparseArray)
12454     * @see #onSaveInstanceState()
12455     */
12456    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12457        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12458            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12459            Parcelable state = onSaveInstanceState();
12460            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12461                throw new IllegalStateException(
12462                        "Derived class did not call super.onSaveInstanceState()");
12463            }
12464            if (state != null) {
12465                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12466                // + ": " + state);
12467                container.put(mID, state);
12468            }
12469        }
12470    }
12471
12472    /**
12473     * Hook allowing a view to generate a representation of its internal state
12474     * that can later be used to create a new instance with that same state.
12475     * This state should only contain information that is not persistent or can
12476     * not be reconstructed later. For example, you will never store your
12477     * current position on screen because that will be computed again when a
12478     * new instance of the view is placed in its view hierarchy.
12479     * <p>
12480     * Some examples of things you may store here: the current cursor position
12481     * in a text view (but usually not the text itself since that is stored in a
12482     * content provider or other persistent storage), the currently selected
12483     * item in a list view.
12484     *
12485     * @return Returns a Parcelable object containing the view's current dynamic
12486     *         state, or null if there is nothing interesting to save. The
12487     *         default implementation returns null.
12488     * @see #onRestoreInstanceState(android.os.Parcelable)
12489     * @see #saveHierarchyState(android.util.SparseArray)
12490     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12491     * @see #setSaveEnabled(boolean)
12492     */
12493    protected Parcelable onSaveInstanceState() {
12494        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12495        return BaseSavedState.EMPTY_STATE;
12496    }
12497
12498    /**
12499     * Restore this view hierarchy's frozen state from the given container.
12500     *
12501     * @param container The SparseArray which holds previously frozen states.
12502     *
12503     * @see #saveHierarchyState(android.util.SparseArray)
12504     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12505     * @see #onRestoreInstanceState(android.os.Parcelable)
12506     */
12507    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12508        dispatchRestoreInstanceState(container);
12509    }
12510
12511    /**
12512     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12513     * state for this view and its children. May be overridden to modify how restoring
12514     * happens to a view's children; for example, some views may want to not store state
12515     * for their children.
12516     *
12517     * @param container The SparseArray which holds previously saved state.
12518     *
12519     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12520     * @see #restoreHierarchyState(android.util.SparseArray)
12521     * @see #onRestoreInstanceState(android.os.Parcelable)
12522     */
12523    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12524        if (mID != NO_ID) {
12525            Parcelable state = container.get(mID);
12526            if (state != null) {
12527                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12528                // + ": " + state);
12529                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12530                onRestoreInstanceState(state);
12531                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12532                    throw new IllegalStateException(
12533                            "Derived class did not call super.onRestoreInstanceState()");
12534                }
12535            }
12536        }
12537    }
12538
12539    /**
12540     * Hook allowing a view to re-apply a representation of its internal state that had previously
12541     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12542     * null state.
12543     *
12544     * @param state The frozen state that had previously been returned by
12545     *        {@link #onSaveInstanceState}.
12546     *
12547     * @see #onSaveInstanceState()
12548     * @see #restoreHierarchyState(android.util.SparseArray)
12549     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12550     */
12551    protected void onRestoreInstanceState(Parcelable state) {
12552        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12553        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12554            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12555                    + "received " + state.getClass().toString() + " instead. This usually happens "
12556                    + "when two views of different type have the same id in the same hierarchy. "
12557                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12558                    + "other views do not use the same id.");
12559        }
12560    }
12561
12562    /**
12563     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12564     *
12565     * @return the drawing start time in milliseconds
12566     */
12567    public long getDrawingTime() {
12568        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12569    }
12570
12571    /**
12572     * <p>Enables or disables the duplication of the parent's state into this view. When
12573     * duplication is enabled, this view gets its drawable state from its parent rather
12574     * than from its own internal properties.</p>
12575     *
12576     * <p>Note: in the current implementation, setting this property to true after the
12577     * view was added to a ViewGroup might have no effect at all. This property should
12578     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12579     *
12580     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12581     * property is enabled, an exception will be thrown.</p>
12582     *
12583     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12584     * parent, these states should not be affected by this method.</p>
12585     *
12586     * @param enabled True to enable duplication of the parent's drawable state, false
12587     *                to disable it.
12588     *
12589     * @see #getDrawableState()
12590     * @see #isDuplicateParentStateEnabled()
12591     */
12592    public void setDuplicateParentStateEnabled(boolean enabled) {
12593        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12594    }
12595
12596    /**
12597     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12598     *
12599     * @return True if this view's drawable state is duplicated from the parent,
12600     *         false otherwise
12601     *
12602     * @see #getDrawableState()
12603     * @see #setDuplicateParentStateEnabled(boolean)
12604     */
12605    public boolean isDuplicateParentStateEnabled() {
12606        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12607    }
12608
12609    /**
12610     * <p>Specifies the type of layer backing this view. The layer can be
12611     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12612     * {@link #LAYER_TYPE_HARDWARE}.</p>
12613     *
12614     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12615     * instance that controls how the layer is composed on screen. The following
12616     * properties of the paint are taken into account when composing the layer:</p>
12617     * <ul>
12618     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12619     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12620     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12621     * </ul>
12622     *
12623     * <p>If this view has an alpha value set to < 1.0 by calling
12624     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12625     * by this view's alpha value.</p>
12626     *
12627     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12628     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12629     * for more information on when and how to use layers.</p>
12630     *
12631     * @param layerType The type of layer to use with this view, must be one of
12632     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12633     *        {@link #LAYER_TYPE_HARDWARE}
12634     * @param paint The paint used to compose the layer. This argument is optional
12635     *        and can be null. It is ignored when the layer type is
12636     *        {@link #LAYER_TYPE_NONE}
12637     *
12638     * @see #getLayerType()
12639     * @see #LAYER_TYPE_NONE
12640     * @see #LAYER_TYPE_SOFTWARE
12641     * @see #LAYER_TYPE_HARDWARE
12642     * @see #setAlpha(float)
12643     *
12644     * @attr ref android.R.styleable#View_layerType
12645     */
12646    public void setLayerType(int layerType, Paint paint) {
12647        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12648            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12649                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12650        }
12651
12652        if (layerType == mLayerType) {
12653            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12654                mLayerPaint = paint == null ? new Paint() : paint;
12655                invalidateParentCaches();
12656                invalidate(true);
12657            }
12658            return;
12659        }
12660
12661        // Destroy any previous software drawing cache if needed
12662        switch (mLayerType) {
12663            case LAYER_TYPE_HARDWARE:
12664                destroyLayer(false);
12665                // fall through - non-accelerated views may use software layer mechanism instead
12666            case LAYER_TYPE_SOFTWARE:
12667                destroyDrawingCache();
12668                break;
12669            default:
12670                break;
12671        }
12672
12673        mLayerType = layerType;
12674        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12675        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12676        mLocalDirtyRect = layerDisabled ? null : new Rect();
12677
12678        invalidateParentCaches();
12679        invalidate(true);
12680    }
12681
12682    /**
12683     * Updates the {@link Paint} object used with the current layer (used only if the current
12684     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12685     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12686     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12687     * ensure that the view gets redrawn immediately.
12688     *
12689     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12690     * instance that controls how the layer is composed on screen. The following
12691     * properties of the paint are taken into account when composing the layer:</p>
12692     * <ul>
12693     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12694     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12695     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12696     * </ul>
12697     *
12698     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12699     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12700     *
12701     * @param paint The paint used to compose the layer. This argument is optional
12702     *        and can be null. It is ignored when the layer type is
12703     *        {@link #LAYER_TYPE_NONE}
12704     *
12705     * @see #setLayerType(int, android.graphics.Paint)
12706     */
12707    public void setLayerPaint(Paint paint) {
12708        int layerType = getLayerType();
12709        if (layerType != LAYER_TYPE_NONE) {
12710            mLayerPaint = paint == null ? new Paint() : paint;
12711            if (layerType == LAYER_TYPE_HARDWARE) {
12712                HardwareLayer layer = getHardwareLayer();
12713                if (layer != null) {
12714                    layer.setLayerPaint(paint);
12715                }
12716                invalidateViewProperty(false, false);
12717            } else {
12718                invalidate();
12719            }
12720        }
12721    }
12722
12723    /**
12724     * Indicates whether this view has a static layer. A view with layer type
12725     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12726     * dynamic.
12727     */
12728    boolean hasStaticLayer() {
12729        return true;
12730    }
12731
12732    /**
12733     * Indicates what type of layer is currently associated with this view. By default
12734     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12735     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12736     * for more information on the different types of layers.
12737     *
12738     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12739     *         {@link #LAYER_TYPE_HARDWARE}
12740     *
12741     * @see #setLayerType(int, android.graphics.Paint)
12742     * @see #buildLayer()
12743     * @see #LAYER_TYPE_NONE
12744     * @see #LAYER_TYPE_SOFTWARE
12745     * @see #LAYER_TYPE_HARDWARE
12746     */
12747    public int getLayerType() {
12748        return mLayerType;
12749    }
12750
12751    /**
12752     * Forces this view's layer to be created and this view to be rendered
12753     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12754     * invoking this method will have no effect.
12755     *
12756     * This method can for instance be used to render a view into its layer before
12757     * starting an animation. If this view is complex, rendering into the layer
12758     * before starting the animation will avoid skipping frames.
12759     *
12760     * @throws IllegalStateException If this view is not attached to a window
12761     *
12762     * @see #setLayerType(int, android.graphics.Paint)
12763     */
12764    public void buildLayer() {
12765        if (mLayerType == LAYER_TYPE_NONE) return;
12766
12767        final AttachInfo attachInfo = mAttachInfo;
12768        if (attachInfo == null) {
12769            throw new IllegalStateException("This view must be attached to a window first");
12770        }
12771
12772        switch (mLayerType) {
12773            case LAYER_TYPE_HARDWARE:
12774                if (attachInfo.mHardwareRenderer != null &&
12775                        attachInfo.mHardwareRenderer.isEnabled() &&
12776                        attachInfo.mHardwareRenderer.validate()) {
12777                    getHardwareLayer();
12778                    // TODO: We need a better way to handle this case
12779                    // If views have registered pre-draw listeners they need
12780                    // to be notified before we build the layer. Those listeners
12781                    // may however rely on other events to happen first so we
12782                    // cannot just invoke them here until they don't cancel the
12783                    // current frame
12784                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12785                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12786                    }
12787                }
12788                break;
12789            case LAYER_TYPE_SOFTWARE:
12790                buildDrawingCache(true);
12791                break;
12792        }
12793    }
12794
12795    /**
12796     * <p>Returns a hardware layer that can be used to draw this view again
12797     * without executing its draw method.</p>
12798     *
12799     * @return A HardwareLayer ready to render, or null if an error occurred.
12800     */
12801    HardwareLayer getHardwareLayer() {
12802        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12803                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12804            return null;
12805        }
12806
12807        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12808
12809        final int width = mRight - mLeft;
12810        final int height = mBottom - mTop;
12811
12812        if (width == 0 || height == 0) {
12813            return null;
12814        }
12815
12816        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12817            if (mHardwareLayer == null) {
12818                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12819                        width, height, isOpaque());
12820                mLocalDirtyRect.set(0, 0, width, height);
12821            } else {
12822                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12823                    if (mHardwareLayer.resize(width, height)) {
12824                        mLocalDirtyRect.set(0, 0, width, height);
12825                    }
12826                }
12827
12828                // This should not be necessary but applications that change
12829                // the parameters of their background drawable without calling
12830                // this.setBackground(Drawable) can leave the view in a bad state
12831                // (for instance isOpaque() returns true, but the background is
12832                // not opaque.)
12833                computeOpaqueFlags();
12834
12835                final boolean opaque = isOpaque();
12836                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12837                    mHardwareLayer.setOpaque(opaque);
12838                    mLocalDirtyRect.set(0, 0, width, height);
12839                }
12840            }
12841
12842            // The layer is not valid if the underlying GPU resources cannot be allocated
12843            if (!mHardwareLayer.isValid()) {
12844                return null;
12845            }
12846
12847            mHardwareLayer.setLayerPaint(mLayerPaint);
12848            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12849            ViewRootImpl viewRoot = getViewRootImpl();
12850            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12851
12852            mLocalDirtyRect.setEmpty();
12853        }
12854
12855        return mHardwareLayer;
12856    }
12857
12858    /**
12859     * Destroys this View's hardware layer if possible.
12860     *
12861     * @return True if the layer was destroyed, false otherwise.
12862     *
12863     * @see #setLayerType(int, android.graphics.Paint)
12864     * @see #LAYER_TYPE_HARDWARE
12865     */
12866    boolean destroyLayer(boolean valid) {
12867        if (mHardwareLayer != null) {
12868            AttachInfo info = mAttachInfo;
12869            if (info != null && info.mHardwareRenderer != null &&
12870                    info.mHardwareRenderer.isEnabled() &&
12871                    (valid || info.mHardwareRenderer.validate())) {
12872
12873                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12874                mHardwareLayer.destroy();
12875                mHardwareLayer = null;
12876
12877                invalidate(true);
12878                invalidateParentCaches();
12879            }
12880            return true;
12881        }
12882        return false;
12883    }
12884
12885    /**
12886     * Destroys all hardware rendering resources. This method is invoked
12887     * when the system needs to reclaim resources. Upon execution of this
12888     * method, you should free any OpenGL resources created by the view.
12889     *
12890     * Note: you <strong>must</strong> call
12891     * <code>super.destroyHardwareResources()</code> when overriding
12892     * this method.
12893     *
12894     * @hide
12895     */
12896    protected void destroyHardwareResources() {
12897        resetDisplayList();
12898        destroyLayer(true);
12899    }
12900
12901    /**
12902     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12903     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12904     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12905     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12906     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12907     * null.</p>
12908     *
12909     * <p>Enabling the drawing cache is similar to
12910     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12911     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12912     * drawing cache has no effect on rendering because the system uses a different mechanism
12913     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12914     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12915     * for information on how to enable software and hardware layers.</p>
12916     *
12917     * <p>This API can be used to manually generate
12918     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12919     * {@link #getDrawingCache()}.</p>
12920     *
12921     * @param enabled true to enable the drawing cache, false otherwise
12922     *
12923     * @see #isDrawingCacheEnabled()
12924     * @see #getDrawingCache()
12925     * @see #buildDrawingCache()
12926     * @see #setLayerType(int, android.graphics.Paint)
12927     */
12928    public void setDrawingCacheEnabled(boolean enabled) {
12929        mCachingFailed = false;
12930        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12931    }
12932
12933    /**
12934     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12935     *
12936     * @return true if the drawing cache is enabled
12937     *
12938     * @see #setDrawingCacheEnabled(boolean)
12939     * @see #getDrawingCache()
12940     */
12941    @ViewDebug.ExportedProperty(category = "drawing")
12942    public boolean isDrawingCacheEnabled() {
12943        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12944    }
12945
12946    /**
12947     * Debugging utility which recursively outputs the dirty state of a view and its
12948     * descendants.
12949     *
12950     * @hide
12951     */
12952    @SuppressWarnings({"UnusedDeclaration"})
12953    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12954        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12955                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12956                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12957                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12958        if (clear) {
12959            mPrivateFlags &= clearMask;
12960        }
12961        if (this instanceof ViewGroup) {
12962            ViewGroup parent = (ViewGroup) this;
12963            final int count = parent.getChildCount();
12964            for (int i = 0; i < count; i++) {
12965                final View child = parent.getChildAt(i);
12966                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12967            }
12968        }
12969    }
12970
12971    /**
12972     * This method is used by ViewGroup to cause its children to restore or recreate their
12973     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12974     * to recreate its own display list, which would happen if it went through the normal
12975     * draw/dispatchDraw mechanisms.
12976     *
12977     * @hide
12978     */
12979    protected void dispatchGetDisplayList() {}
12980
12981    /**
12982     * A view that is not attached or hardware accelerated cannot create a display list.
12983     * This method checks these conditions and returns the appropriate result.
12984     *
12985     * @return true if view has the ability to create a display list, false otherwise.
12986     *
12987     * @hide
12988     */
12989    public boolean canHaveDisplayList() {
12990        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12991    }
12992
12993    /**
12994     * @return The {@link HardwareRenderer} associated with that view or null if
12995     *         hardware rendering is not supported or this view is not attached
12996     *         to a window.
12997     *
12998     * @hide
12999     */
13000    public HardwareRenderer getHardwareRenderer() {
13001        if (mAttachInfo != null) {
13002            return mAttachInfo.mHardwareRenderer;
13003        }
13004        return null;
13005    }
13006
13007    /**
13008     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13009     * Otherwise, the same display list will be returned (after having been rendered into
13010     * along the way, depending on the invalidation state of the view).
13011     *
13012     * @param displayList The previous version of this displayList, could be null.
13013     * @param isLayer Whether the requester of the display list is a layer. If so,
13014     * the view will avoid creating a layer inside the resulting display list.
13015     * @return A new or reused DisplayList object.
13016     */
13017    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13018        if (!canHaveDisplayList()) {
13019            return null;
13020        }
13021
13022        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13023                displayList == null || !displayList.isValid() ||
13024                (!isLayer && mRecreateDisplayList))) {
13025            // Don't need to recreate the display list, just need to tell our
13026            // children to restore/recreate theirs
13027            if (displayList != null && displayList.isValid() &&
13028                    !isLayer && !mRecreateDisplayList) {
13029                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13030                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13031                dispatchGetDisplayList();
13032
13033                return displayList;
13034            }
13035
13036            if (!isLayer) {
13037                // If we got here, we're recreating it. Mark it as such to ensure that
13038                // we copy in child display lists into ours in drawChild()
13039                mRecreateDisplayList = true;
13040            }
13041            if (displayList == null) {
13042                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
13043                // If we're creating a new display list, make sure our parent gets invalidated
13044                // since they will need to recreate their display list to account for this
13045                // new child display list.
13046                invalidateParentCaches();
13047            }
13048
13049            boolean caching = false;
13050            int width = mRight - mLeft;
13051            int height = mBottom - mTop;
13052            int layerType = getLayerType();
13053
13054            final HardwareCanvas canvas = displayList.start(width, height);
13055
13056            try {
13057                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13058                    if (layerType == LAYER_TYPE_HARDWARE) {
13059                        final HardwareLayer layer = getHardwareLayer();
13060                        if (layer != null && layer.isValid()) {
13061                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13062                        } else {
13063                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13064                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13065                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13066                        }
13067                        caching = true;
13068                    } else {
13069                        buildDrawingCache(true);
13070                        Bitmap cache = getDrawingCache(true);
13071                        if (cache != null) {
13072                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13073                            caching = true;
13074                        }
13075                    }
13076                } else {
13077
13078                    computeScroll();
13079
13080                    canvas.translate(-mScrollX, -mScrollY);
13081                    if (!isLayer) {
13082                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13083                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13084                    }
13085
13086                    // Fast path for layouts with no backgrounds
13087                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13088                        dispatchDraw(canvas);
13089                        if (mOverlay != null && !mOverlay.isEmpty()) {
13090                            mOverlay.getOverlayView().draw(canvas);
13091                        }
13092                    } else {
13093                        draw(canvas);
13094                    }
13095                }
13096            } finally {
13097                displayList.end();
13098                displayList.setCaching(caching);
13099                if (isLayer) {
13100                    displayList.setLeftTopRightBottom(0, 0, width, height);
13101                } else {
13102                    setDisplayListProperties(displayList);
13103                }
13104            }
13105        } else if (!isLayer) {
13106            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13107            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13108        }
13109
13110        return displayList;
13111    }
13112
13113    /**
13114     * Get the DisplayList for the HardwareLayer
13115     *
13116     * @param layer The HardwareLayer whose DisplayList we want
13117     * @return A DisplayList fopr the specified HardwareLayer
13118     */
13119    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13120        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13121        layer.setDisplayList(displayList);
13122        return displayList;
13123    }
13124
13125
13126    /**
13127     * <p>Returns a display list that can be used to draw this view again
13128     * without executing its draw method.</p>
13129     *
13130     * @return A DisplayList ready to replay, or null if caching is not enabled.
13131     *
13132     * @hide
13133     */
13134    public DisplayList getDisplayList() {
13135        mDisplayList = getDisplayList(mDisplayList, false);
13136        return mDisplayList;
13137    }
13138
13139    private void clearDisplayList() {
13140        if (mDisplayList != null) {
13141            mDisplayList.clear();
13142        }
13143    }
13144
13145    private void resetDisplayList() {
13146        if (mDisplayList != null) {
13147            mDisplayList.reset();
13148        }
13149    }
13150
13151    /**
13152     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13153     *
13154     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13155     *
13156     * @see #getDrawingCache(boolean)
13157     */
13158    public Bitmap getDrawingCache() {
13159        return getDrawingCache(false);
13160    }
13161
13162    /**
13163     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13164     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13165     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13166     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13167     * request the drawing cache by calling this method and draw it on screen if the
13168     * returned bitmap is not null.</p>
13169     *
13170     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13171     * this method will create a bitmap of the same size as this view. Because this bitmap
13172     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13173     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13174     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13175     * size than the view. This implies that your application must be able to handle this
13176     * size.</p>
13177     *
13178     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13179     *        the current density of the screen when the application is in compatibility
13180     *        mode.
13181     *
13182     * @return A bitmap representing this view or null if cache is disabled.
13183     *
13184     * @see #setDrawingCacheEnabled(boolean)
13185     * @see #isDrawingCacheEnabled()
13186     * @see #buildDrawingCache(boolean)
13187     * @see #destroyDrawingCache()
13188     */
13189    public Bitmap getDrawingCache(boolean autoScale) {
13190        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13191            return null;
13192        }
13193        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13194            buildDrawingCache(autoScale);
13195        }
13196        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13197    }
13198
13199    /**
13200     * <p>Frees the resources used by the drawing cache. If you call
13201     * {@link #buildDrawingCache()} manually without calling
13202     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13203     * should cleanup the cache with this method afterwards.</p>
13204     *
13205     * @see #setDrawingCacheEnabled(boolean)
13206     * @see #buildDrawingCache()
13207     * @see #getDrawingCache()
13208     */
13209    public void destroyDrawingCache() {
13210        if (mDrawingCache != null) {
13211            mDrawingCache.recycle();
13212            mDrawingCache = null;
13213        }
13214        if (mUnscaledDrawingCache != null) {
13215            mUnscaledDrawingCache.recycle();
13216            mUnscaledDrawingCache = null;
13217        }
13218    }
13219
13220    /**
13221     * Setting a solid background color for the drawing cache's bitmaps will improve
13222     * performance and memory usage. Note, though that this should only be used if this
13223     * view will always be drawn on top of a solid color.
13224     *
13225     * @param color The background color to use for the drawing cache's bitmap
13226     *
13227     * @see #setDrawingCacheEnabled(boolean)
13228     * @see #buildDrawingCache()
13229     * @see #getDrawingCache()
13230     */
13231    public void setDrawingCacheBackgroundColor(int color) {
13232        if (color != mDrawingCacheBackgroundColor) {
13233            mDrawingCacheBackgroundColor = color;
13234            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13235        }
13236    }
13237
13238    /**
13239     * @see #setDrawingCacheBackgroundColor(int)
13240     *
13241     * @return The background color to used for the drawing cache's bitmap
13242     */
13243    public int getDrawingCacheBackgroundColor() {
13244        return mDrawingCacheBackgroundColor;
13245    }
13246
13247    /**
13248     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13249     *
13250     * @see #buildDrawingCache(boolean)
13251     */
13252    public void buildDrawingCache() {
13253        buildDrawingCache(false);
13254    }
13255
13256    /**
13257     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13258     *
13259     * <p>If you call {@link #buildDrawingCache()} manually without calling
13260     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13261     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13262     *
13263     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13264     * this method will create a bitmap of the same size as this view. Because this bitmap
13265     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13266     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13267     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13268     * size than the view. This implies that your application must be able to handle this
13269     * size.</p>
13270     *
13271     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13272     * you do not need the drawing cache bitmap, calling this method will increase memory
13273     * usage and cause the view to be rendered in software once, thus negatively impacting
13274     * performance.</p>
13275     *
13276     * @see #getDrawingCache()
13277     * @see #destroyDrawingCache()
13278     */
13279    public void buildDrawingCache(boolean autoScale) {
13280        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13281                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13282            mCachingFailed = false;
13283
13284            int width = mRight - mLeft;
13285            int height = mBottom - mTop;
13286
13287            final AttachInfo attachInfo = mAttachInfo;
13288            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13289
13290            if (autoScale && scalingRequired) {
13291                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13292                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13293            }
13294
13295            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13296            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13297            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13298
13299            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13300            final long drawingCacheSize =
13301                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13302            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13303                if (width > 0 && height > 0) {
13304                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13305                            + projectedBitmapSize + " bytes, only "
13306                            + drawingCacheSize + " available");
13307                }
13308                destroyDrawingCache();
13309                mCachingFailed = true;
13310                return;
13311            }
13312
13313            boolean clear = true;
13314            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13315
13316            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13317                Bitmap.Config quality;
13318                if (!opaque) {
13319                    // Never pick ARGB_4444 because it looks awful
13320                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13321                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13322                        case DRAWING_CACHE_QUALITY_AUTO:
13323                        case DRAWING_CACHE_QUALITY_LOW:
13324                        case DRAWING_CACHE_QUALITY_HIGH:
13325                        default:
13326                            quality = Bitmap.Config.ARGB_8888;
13327                            break;
13328                    }
13329                } else {
13330                    // Optimization for translucent windows
13331                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13332                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13333                }
13334
13335                // Try to cleanup memory
13336                if (bitmap != null) bitmap.recycle();
13337
13338                try {
13339                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13340                            width, height, quality);
13341                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13342                    if (autoScale) {
13343                        mDrawingCache = bitmap;
13344                    } else {
13345                        mUnscaledDrawingCache = bitmap;
13346                    }
13347                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13348                } catch (OutOfMemoryError e) {
13349                    // If there is not enough memory to create the bitmap cache, just
13350                    // ignore the issue as bitmap caches are not required to draw the
13351                    // view hierarchy
13352                    if (autoScale) {
13353                        mDrawingCache = null;
13354                    } else {
13355                        mUnscaledDrawingCache = null;
13356                    }
13357                    mCachingFailed = true;
13358                    return;
13359                }
13360
13361                clear = drawingCacheBackgroundColor != 0;
13362            }
13363
13364            Canvas canvas;
13365            if (attachInfo != null) {
13366                canvas = attachInfo.mCanvas;
13367                if (canvas == null) {
13368                    canvas = new Canvas();
13369                }
13370                canvas.setBitmap(bitmap);
13371                // Temporarily clobber the cached Canvas in case one of our children
13372                // is also using a drawing cache. Without this, the children would
13373                // steal the canvas by attaching their own bitmap to it and bad, bad
13374                // thing would happen (invisible views, corrupted drawings, etc.)
13375                attachInfo.mCanvas = null;
13376            } else {
13377                // This case should hopefully never or seldom happen
13378                canvas = new Canvas(bitmap);
13379            }
13380
13381            if (clear) {
13382                bitmap.eraseColor(drawingCacheBackgroundColor);
13383            }
13384
13385            computeScroll();
13386            final int restoreCount = canvas.save();
13387
13388            if (autoScale && scalingRequired) {
13389                final float scale = attachInfo.mApplicationScale;
13390                canvas.scale(scale, scale);
13391            }
13392
13393            canvas.translate(-mScrollX, -mScrollY);
13394
13395            mPrivateFlags |= PFLAG_DRAWN;
13396            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13397                    mLayerType != LAYER_TYPE_NONE) {
13398                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13399            }
13400
13401            // Fast path for layouts with no backgrounds
13402            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13403                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13404                dispatchDraw(canvas);
13405                if (mOverlay != null && !mOverlay.isEmpty()) {
13406                    mOverlay.getOverlayView().draw(canvas);
13407                }
13408            } else {
13409                draw(canvas);
13410            }
13411
13412            canvas.restoreToCount(restoreCount);
13413            canvas.setBitmap(null);
13414
13415            if (attachInfo != null) {
13416                // Restore the cached Canvas for our siblings
13417                attachInfo.mCanvas = canvas;
13418            }
13419        }
13420    }
13421
13422    /**
13423     * Create a snapshot of the view into a bitmap.  We should probably make
13424     * some form of this public, but should think about the API.
13425     */
13426    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13427        int width = mRight - mLeft;
13428        int height = mBottom - mTop;
13429
13430        final AttachInfo attachInfo = mAttachInfo;
13431        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13432        width = (int) ((width * scale) + 0.5f);
13433        height = (int) ((height * scale) + 0.5f);
13434
13435        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13436                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13437        if (bitmap == null) {
13438            throw new OutOfMemoryError();
13439        }
13440
13441        Resources resources = getResources();
13442        if (resources != null) {
13443            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13444        }
13445
13446        Canvas canvas;
13447        if (attachInfo != null) {
13448            canvas = attachInfo.mCanvas;
13449            if (canvas == null) {
13450                canvas = new Canvas();
13451            }
13452            canvas.setBitmap(bitmap);
13453            // Temporarily clobber the cached Canvas in case one of our children
13454            // is also using a drawing cache. Without this, the children would
13455            // steal the canvas by attaching their own bitmap to it and bad, bad
13456            // things would happen (invisible views, corrupted drawings, etc.)
13457            attachInfo.mCanvas = null;
13458        } else {
13459            // This case should hopefully never or seldom happen
13460            canvas = new Canvas(bitmap);
13461        }
13462
13463        if ((backgroundColor & 0xff000000) != 0) {
13464            bitmap.eraseColor(backgroundColor);
13465        }
13466
13467        computeScroll();
13468        final int restoreCount = canvas.save();
13469        canvas.scale(scale, scale);
13470        canvas.translate(-mScrollX, -mScrollY);
13471
13472        // Temporarily remove the dirty mask
13473        int flags = mPrivateFlags;
13474        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13475
13476        // Fast path for layouts with no backgrounds
13477        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13478            dispatchDraw(canvas);
13479        } else {
13480            draw(canvas);
13481        }
13482
13483        mPrivateFlags = flags;
13484
13485        canvas.restoreToCount(restoreCount);
13486        canvas.setBitmap(null);
13487
13488        if (attachInfo != null) {
13489            // Restore the cached Canvas for our siblings
13490            attachInfo.mCanvas = canvas;
13491        }
13492
13493        return bitmap;
13494    }
13495
13496    /**
13497     * Indicates whether this View is currently in edit mode. A View is usually
13498     * in edit mode when displayed within a developer tool. For instance, if
13499     * this View is being drawn by a visual user interface builder, this method
13500     * should return true.
13501     *
13502     * Subclasses should check the return value of this method to provide
13503     * different behaviors if their normal behavior might interfere with the
13504     * host environment. For instance: the class spawns a thread in its
13505     * constructor, the drawing code relies on device-specific features, etc.
13506     *
13507     * This method is usually checked in the drawing code of custom widgets.
13508     *
13509     * @return True if this View is in edit mode, false otherwise.
13510     */
13511    public boolean isInEditMode() {
13512        return false;
13513    }
13514
13515    /**
13516     * If the View draws content inside its padding and enables fading edges,
13517     * it needs to support padding offsets. Padding offsets are added to the
13518     * fading edges to extend the length of the fade so that it covers pixels
13519     * drawn inside the padding.
13520     *
13521     * Subclasses of this class should override this method if they need
13522     * to draw content inside the padding.
13523     *
13524     * @return True if padding offset must be applied, false otherwise.
13525     *
13526     * @see #getLeftPaddingOffset()
13527     * @see #getRightPaddingOffset()
13528     * @see #getTopPaddingOffset()
13529     * @see #getBottomPaddingOffset()
13530     *
13531     * @since CURRENT
13532     */
13533    protected boolean isPaddingOffsetRequired() {
13534        return false;
13535    }
13536
13537    /**
13538     * Amount by which to extend the left fading region. Called only when
13539     * {@link #isPaddingOffsetRequired()} returns true.
13540     *
13541     * @return The left padding offset in pixels.
13542     *
13543     * @see #isPaddingOffsetRequired()
13544     *
13545     * @since CURRENT
13546     */
13547    protected int getLeftPaddingOffset() {
13548        return 0;
13549    }
13550
13551    /**
13552     * Amount by which to extend the right fading region. Called only when
13553     * {@link #isPaddingOffsetRequired()} returns true.
13554     *
13555     * @return The right padding offset in pixels.
13556     *
13557     * @see #isPaddingOffsetRequired()
13558     *
13559     * @since CURRENT
13560     */
13561    protected int getRightPaddingOffset() {
13562        return 0;
13563    }
13564
13565    /**
13566     * Amount by which to extend the top fading region. Called only when
13567     * {@link #isPaddingOffsetRequired()} returns true.
13568     *
13569     * @return The top padding offset in pixels.
13570     *
13571     * @see #isPaddingOffsetRequired()
13572     *
13573     * @since CURRENT
13574     */
13575    protected int getTopPaddingOffset() {
13576        return 0;
13577    }
13578
13579    /**
13580     * Amount by which to extend the bottom fading region. Called only when
13581     * {@link #isPaddingOffsetRequired()} returns true.
13582     *
13583     * @return The bottom padding offset in pixels.
13584     *
13585     * @see #isPaddingOffsetRequired()
13586     *
13587     * @since CURRENT
13588     */
13589    protected int getBottomPaddingOffset() {
13590        return 0;
13591    }
13592
13593    /**
13594     * @hide
13595     * @param offsetRequired
13596     */
13597    protected int getFadeTop(boolean offsetRequired) {
13598        int top = mPaddingTop;
13599        if (offsetRequired) top += getTopPaddingOffset();
13600        return top;
13601    }
13602
13603    /**
13604     * @hide
13605     * @param offsetRequired
13606     */
13607    protected int getFadeHeight(boolean offsetRequired) {
13608        int padding = mPaddingTop;
13609        if (offsetRequired) padding += getTopPaddingOffset();
13610        return mBottom - mTop - mPaddingBottom - padding;
13611    }
13612
13613    /**
13614     * <p>Indicates whether this view is attached to a hardware accelerated
13615     * window or not.</p>
13616     *
13617     * <p>Even if this method returns true, it does not mean that every call
13618     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13619     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13620     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13621     * window is hardware accelerated,
13622     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13623     * return false, and this method will return true.</p>
13624     *
13625     * @return True if the view is attached to a window and the window is
13626     *         hardware accelerated; false in any other case.
13627     */
13628    public boolean isHardwareAccelerated() {
13629        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13630    }
13631
13632    /**
13633     * Sets a rectangular area on this view to which the view will be clipped
13634     * when it is drawn. Setting the value to null will remove the clip bounds
13635     * and the view will draw normally, using its full bounds.
13636     *
13637     * @param clipBounds The rectangular area, in the local coordinates of
13638     * this view, to which future drawing operations will be clipped.
13639     */
13640    public void setClipBounds(Rect clipBounds) {
13641        if (clipBounds != null) {
13642            if (clipBounds.equals(mClipBounds)) {
13643                return;
13644            }
13645            if (mClipBounds == null) {
13646                invalidate();
13647                mClipBounds = new Rect(clipBounds);
13648            } else {
13649                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13650                        Math.min(mClipBounds.top, clipBounds.top),
13651                        Math.max(mClipBounds.right, clipBounds.right),
13652                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13653                mClipBounds.set(clipBounds);
13654            }
13655        } else {
13656            if (mClipBounds != null) {
13657                invalidate();
13658                mClipBounds = null;
13659            }
13660        }
13661    }
13662
13663    /**
13664     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13665     *
13666     * @return A copy of the current clip bounds if clip bounds are set,
13667     * otherwise null.
13668     */
13669    public Rect getClipBounds() {
13670        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13671    }
13672
13673    /**
13674     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13675     * case of an active Animation being run on the view.
13676     */
13677    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13678            Animation a, boolean scalingRequired) {
13679        Transformation invalidationTransform;
13680        final int flags = parent.mGroupFlags;
13681        final boolean initialized = a.isInitialized();
13682        if (!initialized) {
13683            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13684            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13685            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13686            onAnimationStart();
13687        }
13688
13689        final Transformation t = parent.getChildTransformation();
13690        boolean more = a.getTransformation(drawingTime, t, 1f);
13691        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13692            if (parent.mInvalidationTransformation == null) {
13693                parent.mInvalidationTransformation = new Transformation();
13694            }
13695            invalidationTransform = parent.mInvalidationTransformation;
13696            a.getTransformation(drawingTime, invalidationTransform, 1f);
13697        } else {
13698            invalidationTransform = t;
13699        }
13700
13701        if (more) {
13702            if (!a.willChangeBounds()) {
13703                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13704                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13705                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13706                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13707                    // The child need to draw an animation, potentially offscreen, so
13708                    // make sure we do not cancel invalidate requests
13709                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13710                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13711                }
13712            } else {
13713                if (parent.mInvalidateRegion == null) {
13714                    parent.mInvalidateRegion = new RectF();
13715                }
13716                final RectF region = parent.mInvalidateRegion;
13717                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13718                        invalidationTransform);
13719
13720                // The child need to draw an animation, potentially offscreen, so
13721                // make sure we do not cancel invalidate requests
13722                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13723
13724                final int left = mLeft + (int) region.left;
13725                final int top = mTop + (int) region.top;
13726                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13727                        top + (int) (region.height() + .5f));
13728            }
13729        }
13730        return more;
13731    }
13732
13733    /**
13734     * This method is called by getDisplayList() when a display list is created or re-rendered.
13735     * It sets or resets the current value of all properties on that display list (resetting is
13736     * necessary when a display list is being re-created, because we need to make sure that
13737     * previously-set transform values
13738     */
13739    void setDisplayListProperties(DisplayList displayList) {
13740        if (displayList != null) {
13741            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13742            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13743            if (mParent instanceof ViewGroup) {
13744                displayList.setClipToBounds(
13745                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13746            }
13747            float alpha = 1;
13748            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13749                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13750                ViewGroup parentVG = (ViewGroup) mParent;
13751                final Transformation t = parentVG.getChildTransformation();
13752                if (parentVG.getChildStaticTransformation(this, t)) {
13753                    final int transformType = t.getTransformationType();
13754                    if (transformType != Transformation.TYPE_IDENTITY) {
13755                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13756                            alpha = t.getAlpha();
13757                        }
13758                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13759                            displayList.setMatrix(t.getMatrix());
13760                        }
13761                    }
13762                }
13763            }
13764            if (mTransformationInfo != null) {
13765                alpha *= mTransformationInfo.mAlpha;
13766                if (alpha < 1) {
13767                    final int multipliedAlpha = (int) (255 * alpha);
13768                    if (onSetAlpha(multipliedAlpha)) {
13769                        alpha = 1;
13770                    }
13771                }
13772                displayList.setTransformationInfo(alpha,
13773                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13774                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13775                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13776                        mTransformationInfo.mScaleY);
13777                if (mTransformationInfo.mCamera == null) {
13778                    mTransformationInfo.mCamera = new Camera();
13779                    mTransformationInfo.matrix3D = new Matrix();
13780                }
13781                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13782                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13783                    displayList.setPivotX(getPivotX());
13784                    displayList.setPivotY(getPivotY());
13785                }
13786            } else if (alpha < 1) {
13787                displayList.setAlpha(alpha);
13788            }
13789        }
13790    }
13791
13792    /**
13793     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13794     * This draw() method is an implementation detail and is not intended to be overridden or
13795     * to be called from anywhere else other than ViewGroup.drawChild().
13796     */
13797    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13798        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13799        boolean more = false;
13800        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13801        final int flags = parent.mGroupFlags;
13802
13803        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13804            parent.getChildTransformation().clear();
13805            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13806        }
13807
13808        Transformation transformToApply = null;
13809        boolean concatMatrix = false;
13810
13811        boolean scalingRequired = false;
13812        boolean caching;
13813        int layerType = getLayerType();
13814
13815        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13816        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13817                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13818            caching = true;
13819            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13820            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13821        } else {
13822            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13823        }
13824
13825        final Animation a = getAnimation();
13826        if (a != null) {
13827            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13828            concatMatrix = a.willChangeTransformationMatrix();
13829            if (concatMatrix) {
13830                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13831            }
13832            transformToApply = parent.getChildTransformation();
13833        } else {
13834            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13835                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13836                // No longer animating: clear out old animation matrix
13837                mDisplayList.setAnimationMatrix(null);
13838                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13839            }
13840            if (!useDisplayListProperties &&
13841                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13842                final Transformation t = parent.getChildTransformation();
13843                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13844                if (hasTransform) {
13845                    final int transformType = t.getTransformationType();
13846                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13847                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13848                }
13849            }
13850        }
13851
13852        concatMatrix |= !childHasIdentityMatrix;
13853
13854        // Sets the flag as early as possible to allow draw() implementations
13855        // to call invalidate() successfully when doing animations
13856        mPrivateFlags |= PFLAG_DRAWN;
13857
13858        if (!concatMatrix &&
13859                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13860                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13861                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13862                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13863            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13864            return more;
13865        }
13866        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13867
13868        if (hardwareAccelerated) {
13869            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13870            // retain the flag's value temporarily in the mRecreateDisplayList flag
13871            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13872            mPrivateFlags &= ~PFLAG_INVALIDATED;
13873        }
13874
13875        DisplayList displayList = null;
13876        Bitmap cache = null;
13877        boolean hasDisplayList = false;
13878        if (caching) {
13879            if (!hardwareAccelerated) {
13880                if (layerType != LAYER_TYPE_NONE) {
13881                    layerType = LAYER_TYPE_SOFTWARE;
13882                    buildDrawingCache(true);
13883                }
13884                cache = getDrawingCache(true);
13885            } else {
13886                switch (layerType) {
13887                    case LAYER_TYPE_SOFTWARE:
13888                        if (useDisplayListProperties) {
13889                            hasDisplayList = canHaveDisplayList();
13890                        } else {
13891                            buildDrawingCache(true);
13892                            cache = getDrawingCache(true);
13893                        }
13894                        break;
13895                    case LAYER_TYPE_HARDWARE:
13896                        if (useDisplayListProperties) {
13897                            hasDisplayList = canHaveDisplayList();
13898                        }
13899                        break;
13900                    case LAYER_TYPE_NONE:
13901                        // Delay getting the display list until animation-driven alpha values are
13902                        // set up and possibly passed on to the view
13903                        hasDisplayList = canHaveDisplayList();
13904                        break;
13905                }
13906            }
13907        }
13908        useDisplayListProperties &= hasDisplayList;
13909        if (useDisplayListProperties) {
13910            displayList = getDisplayList();
13911            if (!displayList.isValid()) {
13912                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13913                // to getDisplayList(), the display list will be marked invalid and we should not
13914                // try to use it again.
13915                displayList = null;
13916                hasDisplayList = false;
13917                useDisplayListProperties = false;
13918            }
13919        }
13920
13921        int sx = 0;
13922        int sy = 0;
13923        if (!hasDisplayList) {
13924            computeScroll();
13925            sx = mScrollX;
13926            sy = mScrollY;
13927        }
13928
13929        final boolean hasNoCache = cache == null || hasDisplayList;
13930        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13931                layerType != LAYER_TYPE_HARDWARE;
13932
13933        int restoreTo = -1;
13934        if (!useDisplayListProperties || transformToApply != null) {
13935            restoreTo = canvas.save();
13936        }
13937        if (offsetForScroll) {
13938            canvas.translate(mLeft - sx, mTop - sy);
13939        } else {
13940            if (!useDisplayListProperties) {
13941                canvas.translate(mLeft, mTop);
13942            }
13943            if (scalingRequired) {
13944                if (useDisplayListProperties) {
13945                    // TODO: Might not need this if we put everything inside the DL
13946                    restoreTo = canvas.save();
13947                }
13948                // mAttachInfo cannot be null, otherwise scalingRequired == false
13949                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13950                canvas.scale(scale, scale);
13951            }
13952        }
13953
13954        float alpha = useDisplayListProperties ? 1 : getAlpha();
13955        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13956                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13957            if (transformToApply != null || !childHasIdentityMatrix) {
13958                int transX = 0;
13959                int transY = 0;
13960
13961                if (offsetForScroll) {
13962                    transX = -sx;
13963                    transY = -sy;
13964                }
13965
13966                if (transformToApply != null) {
13967                    if (concatMatrix) {
13968                        if (useDisplayListProperties) {
13969                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13970                        } else {
13971                            // Undo the scroll translation, apply the transformation matrix,
13972                            // then redo the scroll translate to get the correct result.
13973                            canvas.translate(-transX, -transY);
13974                            canvas.concat(transformToApply.getMatrix());
13975                            canvas.translate(transX, transY);
13976                        }
13977                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13978                    }
13979
13980                    float transformAlpha = transformToApply.getAlpha();
13981                    if (transformAlpha < 1) {
13982                        alpha *= transformAlpha;
13983                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13984                    }
13985                }
13986
13987                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13988                    canvas.translate(-transX, -transY);
13989                    canvas.concat(getMatrix());
13990                    canvas.translate(transX, transY);
13991                }
13992            }
13993
13994            // Deal with alpha if it is or used to be <1
13995            if (alpha < 1 ||
13996                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13997                if (alpha < 1) {
13998                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13999                } else {
14000                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14001                }
14002                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14003                if (hasNoCache) {
14004                    final int multipliedAlpha = (int) (255 * alpha);
14005                    if (!onSetAlpha(multipliedAlpha)) {
14006                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14007                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14008                                layerType != LAYER_TYPE_NONE) {
14009                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14010                        }
14011                        if (useDisplayListProperties) {
14012                            displayList.setAlpha(alpha * getAlpha());
14013                        } else  if (layerType == LAYER_TYPE_NONE) {
14014                            final int scrollX = hasDisplayList ? 0 : sx;
14015                            final int scrollY = hasDisplayList ? 0 : sy;
14016                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14017                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14018                        }
14019                    } else {
14020                        // Alpha is handled by the child directly, clobber the layer's alpha
14021                        mPrivateFlags |= PFLAG_ALPHA_SET;
14022                    }
14023                }
14024            }
14025        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14026            onSetAlpha(255);
14027            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14028        }
14029
14030        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14031                !useDisplayListProperties && cache == null) {
14032            if (offsetForScroll) {
14033                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14034            } else {
14035                if (!scalingRequired || cache == null) {
14036                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14037                } else {
14038                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14039                }
14040            }
14041        }
14042
14043        if (!useDisplayListProperties && hasDisplayList) {
14044            displayList = getDisplayList();
14045            if (!displayList.isValid()) {
14046                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14047                // to getDisplayList(), the display list will be marked invalid and we should not
14048                // try to use it again.
14049                displayList = null;
14050                hasDisplayList = false;
14051            }
14052        }
14053
14054        if (hasNoCache) {
14055            boolean layerRendered = false;
14056            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14057                final HardwareLayer layer = getHardwareLayer();
14058                if (layer != null && layer.isValid()) {
14059                    mLayerPaint.setAlpha((int) (alpha * 255));
14060                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14061                    layerRendered = true;
14062                } else {
14063                    final int scrollX = hasDisplayList ? 0 : sx;
14064                    final int scrollY = hasDisplayList ? 0 : sy;
14065                    canvas.saveLayer(scrollX, scrollY,
14066                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14067                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14068                }
14069            }
14070
14071            if (!layerRendered) {
14072                if (!hasDisplayList) {
14073                    // Fast path for layouts with no backgrounds
14074                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14075                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14076                        dispatchDraw(canvas);
14077                    } else {
14078                        draw(canvas);
14079                    }
14080                } else {
14081                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14082                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14083                }
14084            }
14085        } else if (cache != null) {
14086            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14087            Paint cachePaint;
14088
14089            if (layerType == LAYER_TYPE_NONE) {
14090                cachePaint = parent.mCachePaint;
14091                if (cachePaint == null) {
14092                    cachePaint = new Paint();
14093                    cachePaint.setDither(false);
14094                    parent.mCachePaint = cachePaint;
14095                }
14096                if (alpha < 1) {
14097                    cachePaint.setAlpha((int) (alpha * 255));
14098                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14099                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14100                    cachePaint.setAlpha(255);
14101                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14102                }
14103            } else {
14104                cachePaint = mLayerPaint;
14105                cachePaint.setAlpha((int) (alpha * 255));
14106            }
14107            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14108        }
14109
14110        if (restoreTo >= 0) {
14111            canvas.restoreToCount(restoreTo);
14112        }
14113
14114        if (a != null && !more) {
14115            if (!hardwareAccelerated && !a.getFillAfter()) {
14116                onSetAlpha(255);
14117            }
14118            parent.finishAnimatingView(this, a);
14119        }
14120
14121        if (more && hardwareAccelerated) {
14122            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14123                // alpha animations should cause the child to recreate its display list
14124                invalidate(true);
14125            }
14126        }
14127
14128        mRecreateDisplayList = false;
14129
14130        return more;
14131    }
14132
14133    /**
14134     * Manually render this view (and all of its children) to the given Canvas.
14135     * The view must have already done a full layout before this function is
14136     * called.  When implementing a view, implement
14137     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14138     * If you do need to override this method, call the superclass version.
14139     *
14140     * @param canvas The Canvas to which the View is rendered.
14141     */
14142    public void draw(Canvas canvas) {
14143        if (mClipBounds != null) {
14144            canvas.clipRect(mClipBounds);
14145        }
14146        final int privateFlags = mPrivateFlags;
14147        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14148                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14149        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14150
14151        /*
14152         * Draw traversal performs several drawing steps which must be executed
14153         * in the appropriate order:
14154         *
14155         *      1. Draw the background
14156         *      2. If necessary, save the canvas' layers to prepare for fading
14157         *      3. Draw view's content
14158         *      4. Draw children
14159         *      5. If necessary, draw the fading edges and restore layers
14160         *      6. Draw decorations (scrollbars for instance)
14161         */
14162
14163        // Step 1, draw the background, if needed
14164        int saveCount;
14165
14166        if (!dirtyOpaque) {
14167            final Drawable background = mBackground;
14168            if (background != null) {
14169                final int scrollX = mScrollX;
14170                final int scrollY = mScrollY;
14171
14172                if (mBackgroundSizeChanged) {
14173                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14174                    mBackgroundSizeChanged = false;
14175                }
14176
14177                if ((scrollX | scrollY) == 0) {
14178                    background.draw(canvas);
14179                } else {
14180                    canvas.translate(scrollX, scrollY);
14181                    background.draw(canvas);
14182                    canvas.translate(-scrollX, -scrollY);
14183                }
14184            }
14185        }
14186
14187        // skip step 2 & 5 if possible (common case)
14188        final int viewFlags = mViewFlags;
14189        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14190        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14191        if (!verticalEdges && !horizontalEdges) {
14192            // Step 3, draw the content
14193            if (!dirtyOpaque) onDraw(canvas);
14194
14195            // Step 4, draw the children
14196            dispatchDraw(canvas);
14197
14198            // Step 6, draw decorations (scrollbars)
14199            onDrawScrollBars(canvas);
14200
14201            if (mOverlay != null && !mOverlay.isEmpty()) {
14202                mOverlay.getOverlayView().dispatchDraw(canvas);
14203            }
14204
14205            // we're done...
14206            return;
14207        }
14208
14209        /*
14210         * Here we do the full fledged routine...
14211         * (this is an uncommon case where speed matters less,
14212         * this is why we repeat some of the tests that have been
14213         * done above)
14214         */
14215
14216        boolean drawTop = false;
14217        boolean drawBottom = false;
14218        boolean drawLeft = false;
14219        boolean drawRight = false;
14220
14221        float topFadeStrength = 0.0f;
14222        float bottomFadeStrength = 0.0f;
14223        float leftFadeStrength = 0.0f;
14224        float rightFadeStrength = 0.0f;
14225
14226        // Step 2, save the canvas' layers
14227        int paddingLeft = mPaddingLeft;
14228
14229        final boolean offsetRequired = isPaddingOffsetRequired();
14230        if (offsetRequired) {
14231            paddingLeft += getLeftPaddingOffset();
14232        }
14233
14234        int left = mScrollX + paddingLeft;
14235        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14236        int top = mScrollY + getFadeTop(offsetRequired);
14237        int bottom = top + getFadeHeight(offsetRequired);
14238
14239        if (offsetRequired) {
14240            right += getRightPaddingOffset();
14241            bottom += getBottomPaddingOffset();
14242        }
14243
14244        final ScrollabilityCache scrollabilityCache = mScrollCache;
14245        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14246        int length = (int) fadeHeight;
14247
14248        // clip the fade length if top and bottom fades overlap
14249        // overlapping fades produce odd-looking artifacts
14250        if (verticalEdges && (top + length > bottom - length)) {
14251            length = (bottom - top) / 2;
14252        }
14253
14254        // also clip horizontal fades if necessary
14255        if (horizontalEdges && (left + length > right - length)) {
14256            length = (right - left) / 2;
14257        }
14258
14259        if (verticalEdges) {
14260            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14261            drawTop = topFadeStrength * fadeHeight > 1.0f;
14262            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14263            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14264        }
14265
14266        if (horizontalEdges) {
14267            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14268            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14269            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14270            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14271        }
14272
14273        saveCount = canvas.getSaveCount();
14274
14275        int solidColor = getSolidColor();
14276        if (solidColor == 0) {
14277            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14278
14279            if (drawTop) {
14280                canvas.saveLayer(left, top, right, top + length, null, flags);
14281            }
14282
14283            if (drawBottom) {
14284                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14285            }
14286
14287            if (drawLeft) {
14288                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14289            }
14290
14291            if (drawRight) {
14292                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14293            }
14294        } else {
14295            scrollabilityCache.setFadeColor(solidColor);
14296        }
14297
14298        // Step 3, draw the content
14299        if (!dirtyOpaque) onDraw(canvas);
14300
14301        // Step 4, draw the children
14302        dispatchDraw(canvas);
14303
14304        // Step 5, draw the fade effect and restore layers
14305        final Paint p = scrollabilityCache.paint;
14306        final Matrix matrix = scrollabilityCache.matrix;
14307        final Shader fade = scrollabilityCache.shader;
14308
14309        if (drawTop) {
14310            matrix.setScale(1, fadeHeight * topFadeStrength);
14311            matrix.postTranslate(left, top);
14312            fade.setLocalMatrix(matrix);
14313            canvas.drawRect(left, top, right, top + length, p);
14314        }
14315
14316        if (drawBottom) {
14317            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14318            matrix.postRotate(180);
14319            matrix.postTranslate(left, bottom);
14320            fade.setLocalMatrix(matrix);
14321            canvas.drawRect(left, bottom - length, right, bottom, p);
14322        }
14323
14324        if (drawLeft) {
14325            matrix.setScale(1, fadeHeight * leftFadeStrength);
14326            matrix.postRotate(-90);
14327            matrix.postTranslate(left, top);
14328            fade.setLocalMatrix(matrix);
14329            canvas.drawRect(left, top, left + length, bottom, p);
14330        }
14331
14332        if (drawRight) {
14333            matrix.setScale(1, fadeHeight * rightFadeStrength);
14334            matrix.postRotate(90);
14335            matrix.postTranslate(right, top);
14336            fade.setLocalMatrix(matrix);
14337            canvas.drawRect(right - length, top, right, bottom, p);
14338        }
14339
14340        canvas.restoreToCount(saveCount);
14341
14342        // Step 6, draw decorations (scrollbars)
14343        onDrawScrollBars(canvas);
14344
14345        if (mOverlay != null && !mOverlay.isEmpty()) {
14346            mOverlay.getOverlayView().dispatchDraw(canvas);
14347        }
14348    }
14349
14350    /**
14351     * Returns the overlay for this view, creating it if it does not yet exist.
14352     * Adding drawables to the overlay will cause them to be displayed whenever
14353     * the view itself is redrawn. Objects in the overlay should be actively
14354     * managed: remove them when they should not be displayed anymore. The
14355     * overlay will always have the same size as its host view.
14356     *
14357     * <p>Note: Overlays do not currently work correctly with {@link
14358     * SurfaceView} or {@link TextureView}; contents in overlays for these
14359     * types of views may not display correctly.</p>
14360     *
14361     * @return The ViewOverlay object for this view.
14362     * @see ViewOverlay
14363     */
14364    public ViewOverlay getOverlay() {
14365        if (mOverlay == null) {
14366            mOverlay = new ViewOverlay(mContext, this);
14367        }
14368        return mOverlay;
14369    }
14370
14371    /**
14372     * Override this if your view is known to always be drawn on top of a solid color background,
14373     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14374     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14375     * should be set to 0xFF.
14376     *
14377     * @see #setVerticalFadingEdgeEnabled(boolean)
14378     * @see #setHorizontalFadingEdgeEnabled(boolean)
14379     *
14380     * @return The known solid color background for this view, or 0 if the color may vary
14381     */
14382    @ViewDebug.ExportedProperty(category = "drawing")
14383    public int getSolidColor() {
14384        return 0;
14385    }
14386
14387    /**
14388     * Build a human readable string representation of the specified view flags.
14389     *
14390     * @param flags the view flags to convert to a string
14391     * @return a String representing the supplied flags
14392     */
14393    private static String printFlags(int flags) {
14394        String output = "";
14395        int numFlags = 0;
14396        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14397            output += "TAKES_FOCUS";
14398            numFlags++;
14399        }
14400
14401        switch (flags & VISIBILITY_MASK) {
14402        case INVISIBLE:
14403            if (numFlags > 0) {
14404                output += " ";
14405            }
14406            output += "INVISIBLE";
14407            // USELESS HERE numFlags++;
14408            break;
14409        case GONE:
14410            if (numFlags > 0) {
14411                output += " ";
14412            }
14413            output += "GONE";
14414            // USELESS HERE numFlags++;
14415            break;
14416        default:
14417            break;
14418        }
14419        return output;
14420    }
14421
14422    /**
14423     * Build a human readable string representation of the specified private
14424     * view flags.
14425     *
14426     * @param privateFlags the private view flags to convert to a string
14427     * @return a String representing the supplied flags
14428     */
14429    private static String printPrivateFlags(int privateFlags) {
14430        String output = "";
14431        int numFlags = 0;
14432
14433        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14434            output += "WANTS_FOCUS";
14435            numFlags++;
14436        }
14437
14438        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14439            if (numFlags > 0) {
14440                output += " ";
14441            }
14442            output += "FOCUSED";
14443            numFlags++;
14444        }
14445
14446        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14447            if (numFlags > 0) {
14448                output += " ";
14449            }
14450            output += "SELECTED";
14451            numFlags++;
14452        }
14453
14454        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14455            if (numFlags > 0) {
14456                output += " ";
14457            }
14458            output += "IS_ROOT_NAMESPACE";
14459            numFlags++;
14460        }
14461
14462        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14463            if (numFlags > 0) {
14464                output += " ";
14465            }
14466            output += "HAS_BOUNDS";
14467            numFlags++;
14468        }
14469
14470        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14471            if (numFlags > 0) {
14472                output += " ";
14473            }
14474            output += "DRAWN";
14475            // USELESS HERE numFlags++;
14476        }
14477        return output;
14478    }
14479
14480    /**
14481     * <p>Indicates whether or not this view's layout will be requested during
14482     * the next hierarchy layout pass.</p>
14483     *
14484     * @return true if the layout will be forced during next layout pass
14485     */
14486    public boolean isLayoutRequested() {
14487        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14488    }
14489
14490    /**
14491     * Return true if o is a ViewGroup that is laying out using optical bounds.
14492     * @hide
14493     */
14494    public static boolean isLayoutModeOptical(Object o) {
14495        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14496    }
14497
14498    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14499        Insets parentInsets = mParent instanceof View ?
14500                ((View) mParent).getOpticalInsets() : Insets.NONE;
14501        Insets childInsets = getOpticalInsets();
14502        return setFrame(
14503                left   + parentInsets.left - childInsets.left,
14504                top    + parentInsets.top  - childInsets.top,
14505                right  + parentInsets.left + childInsets.right,
14506                bottom + parentInsets.top  + childInsets.bottom);
14507    }
14508
14509    /**
14510     * Assign a size and position to a view and all of its
14511     * descendants
14512     *
14513     * <p>This is the second phase of the layout mechanism.
14514     * (The first is measuring). In this phase, each parent calls
14515     * layout on all of its children to position them.
14516     * This is typically done using the child measurements
14517     * that were stored in the measure pass().</p>
14518     *
14519     * <p>Derived classes should not override this method.
14520     * Derived classes with children should override
14521     * onLayout. In that method, they should
14522     * call layout on each of their children.</p>
14523     *
14524     * @param l Left position, relative to parent
14525     * @param t Top position, relative to parent
14526     * @param r Right position, relative to parent
14527     * @param b Bottom position, relative to parent
14528     */
14529    @SuppressWarnings({"unchecked"})
14530    public void layout(int l, int t, int r, int b) {
14531        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14532            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14533            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14534        }
14535
14536        int oldL = mLeft;
14537        int oldT = mTop;
14538        int oldB = mBottom;
14539        int oldR = mRight;
14540
14541        boolean changed = isLayoutModeOptical(mParent) ?
14542                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14543
14544        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14545            onLayout(changed, l, t, r, b);
14546            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14547
14548            ListenerInfo li = mListenerInfo;
14549            if (li != null && li.mOnLayoutChangeListeners != null) {
14550                ArrayList<OnLayoutChangeListener> listenersCopy =
14551                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14552                int numListeners = listenersCopy.size();
14553                for (int i = 0; i < numListeners; ++i) {
14554                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14555                }
14556            }
14557        }
14558
14559        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14560        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14561    }
14562
14563    /**
14564     * Called from layout when this view should
14565     * assign a size and position to each of its children.
14566     *
14567     * Derived classes with children should override
14568     * this method and call layout on each of
14569     * their children.
14570     * @param changed This is a new size or position for this view
14571     * @param left Left position, relative to parent
14572     * @param top Top position, relative to parent
14573     * @param right Right position, relative to parent
14574     * @param bottom Bottom position, relative to parent
14575     */
14576    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14577    }
14578
14579    /**
14580     * Assign a size and position to this view.
14581     *
14582     * This is called from layout.
14583     *
14584     * @param left Left position, relative to parent
14585     * @param top Top position, relative to parent
14586     * @param right Right position, relative to parent
14587     * @param bottom Bottom position, relative to parent
14588     * @return true if the new size and position are different than the
14589     *         previous ones
14590     * {@hide}
14591     */
14592    protected boolean setFrame(int left, int top, int right, int bottom) {
14593        boolean changed = false;
14594
14595        if (DBG) {
14596            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14597                    + right + "," + bottom + ")");
14598        }
14599
14600        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14601            changed = true;
14602
14603            // Remember our drawn bit
14604            int drawn = mPrivateFlags & PFLAG_DRAWN;
14605
14606            int oldWidth = mRight - mLeft;
14607            int oldHeight = mBottom - mTop;
14608            int newWidth = right - left;
14609            int newHeight = bottom - top;
14610            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14611
14612            // Invalidate our old position
14613            invalidate(sizeChanged);
14614
14615            mLeft = left;
14616            mTop = top;
14617            mRight = right;
14618            mBottom = bottom;
14619            if (mDisplayList != null) {
14620                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14621            }
14622
14623            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14624
14625
14626            if (sizeChanged) {
14627                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14628                    // A change in dimension means an auto-centered pivot point changes, too
14629                    if (mTransformationInfo != null) {
14630                        mTransformationInfo.mMatrixDirty = true;
14631                    }
14632                }
14633                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14634            }
14635
14636            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14637                // If we are visible, force the DRAWN bit to on so that
14638                // this invalidate will go through (at least to our parent).
14639                // This is because someone may have invalidated this view
14640                // before this call to setFrame came in, thereby clearing
14641                // the DRAWN bit.
14642                mPrivateFlags |= PFLAG_DRAWN;
14643                invalidate(sizeChanged);
14644                // parent display list may need to be recreated based on a change in the bounds
14645                // of any child
14646                invalidateParentCaches();
14647            }
14648
14649            // Reset drawn bit to original value (invalidate turns it off)
14650            mPrivateFlags |= drawn;
14651
14652            mBackgroundSizeChanged = true;
14653
14654            notifySubtreeAccessibilityStateChangedIfNeeded();
14655        }
14656        return changed;
14657    }
14658
14659    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14660        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14661        if (mOverlay != null) {
14662            mOverlay.getOverlayView().setRight(newWidth);
14663            mOverlay.getOverlayView().setBottom(newHeight);
14664        }
14665    }
14666
14667    /**
14668     * Finalize inflating a view from XML.  This is called as the last phase
14669     * of inflation, after all child views have been added.
14670     *
14671     * <p>Even if the subclass overrides onFinishInflate, they should always be
14672     * sure to call the super method, so that we get called.
14673     */
14674    protected void onFinishInflate() {
14675    }
14676
14677    /**
14678     * Returns the resources associated with this view.
14679     *
14680     * @return Resources object.
14681     */
14682    public Resources getResources() {
14683        return mResources;
14684    }
14685
14686    /**
14687     * Invalidates the specified Drawable.
14688     *
14689     * @param drawable the drawable to invalidate
14690     */
14691    public void invalidateDrawable(Drawable drawable) {
14692        if (verifyDrawable(drawable)) {
14693            final Rect dirty = drawable.getBounds();
14694            final int scrollX = mScrollX;
14695            final int scrollY = mScrollY;
14696
14697            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14698                    dirty.right + scrollX, dirty.bottom + scrollY);
14699        }
14700    }
14701
14702    /**
14703     * Schedules an action on a drawable to occur at a specified time.
14704     *
14705     * @param who the recipient of the action
14706     * @param what the action to run on the drawable
14707     * @param when the time at which the action must occur. Uses the
14708     *        {@link SystemClock#uptimeMillis} timebase.
14709     */
14710    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14711        if (verifyDrawable(who) && what != null) {
14712            final long delay = when - SystemClock.uptimeMillis();
14713            if (mAttachInfo != null) {
14714                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14715                        Choreographer.CALLBACK_ANIMATION, what, who,
14716                        Choreographer.subtractFrameDelay(delay));
14717            } else {
14718                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14719            }
14720        }
14721    }
14722
14723    /**
14724     * Cancels a scheduled action on a drawable.
14725     *
14726     * @param who the recipient of the action
14727     * @param what the action to cancel
14728     */
14729    public void unscheduleDrawable(Drawable who, Runnable what) {
14730        if (verifyDrawable(who) && what != null) {
14731            if (mAttachInfo != null) {
14732                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14733                        Choreographer.CALLBACK_ANIMATION, what, who);
14734            } else {
14735                ViewRootImpl.getRunQueue().removeCallbacks(what);
14736            }
14737        }
14738    }
14739
14740    /**
14741     * Unschedule any events associated with the given Drawable.  This can be
14742     * used when selecting a new Drawable into a view, so that the previous
14743     * one is completely unscheduled.
14744     *
14745     * @param who The Drawable to unschedule.
14746     *
14747     * @see #drawableStateChanged
14748     */
14749    public void unscheduleDrawable(Drawable who) {
14750        if (mAttachInfo != null && who != null) {
14751            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14752                    Choreographer.CALLBACK_ANIMATION, null, who);
14753        }
14754    }
14755
14756    /**
14757     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14758     * that the View directionality can and will be resolved before its Drawables.
14759     *
14760     * Will call {@link View#onResolveDrawables} when resolution is done.
14761     *
14762     * @hide
14763     */
14764    protected void resolveDrawables() {
14765        // Drawables resolution may need to happen before resolving the layout direction (which is
14766        // done only during the measure() call).
14767        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
14768        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
14769        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
14770        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
14771        // direction to be resolved as its resolved value will be the same as its raw value.
14772        if (!isLayoutDirectionResolved() &&
14773                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
14774            return;
14775        }
14776
14777        final int layoutDirection = isLayoutDirectionResolved() ?
14778                getLayoutDirection() : getRawLayoutDirection();
14779
14780        if (mBackground != null) {
14781            mBackground.setLayoutDirection(layoutDirection);
14782        }
14783        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14784        onResolveDrawables(layoutDirection);
14785    }
14786
14787    /**
14788     * Called when layout direction has been resolved.
14789     *
14790     * The default implementation does nothing.
14791     *
14792     * @param layoutDirection The resolved layout direction.
14793     *
14794     * @see #LAYOUT_DIRECTION_LTR
14795     * @see #LAYOUT_DIRECTION_RTL
14796     *
14797     * @hide
14798     */
14799    public void onResolveDrawables(int layoutDirection) {
14800    }
14801
14802    /**
14803     * @hide
14804     */
14805    protected void resetResolvedDrawables() {
14806        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14807    }
14808
14809    private boolean isDrawablesResolved() {
14810        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14811    }
14812
14813    /**
14814     * If your view subclass is displaying its own Drawable objects, it should
14815     * override this function and return true for any Drawable it is
14816     * displaying.  This allows animations for those drawables to be
14817     * scheduled.
14818     *
14819     * <p>Be sure to call through to the super class when overriding this
14820     * function.
14821     *
14822     * @param who The Drawable to verify.  Return true if it is one you are
14823     *            displaying, else return the result of calling through to the
14824     *            super class.
14825     *
14826     * @return boolean If true than the Drawable is being displayed in the
14827     *         view; else false and it is not allowed to animate.
14828     *
14829     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14830     * @see #drawableStateChanged()
14831     */
14832    protected boolean verifyDrawable(Drawable who) {
14833        return who == mBackground;
14834    }
14835
14836    /**
14837     * This function is called whenever the state of the view changes in such
14838     * a way that it impacts the state of drawables being shown.
14839     *
14840     * <p>Be sure to call through to the superclass when overriding this
14841     * function.
14842     *
14843     * @see Drawable#setState(int[])
14844     */
14845    protected void drawableStateChanged() {
14846        Drawable d = mBackground;
14847        if (d != null && d.isStateful()) {
14848            d.setState(getDrawableState());
14849        }
14850    }
14851
14852    /**
14853     * Call this to force a view to update its drawable state. This will cause
14854     * drawableStateChanged to be called on this view. Views that are interested
14855     * in the new state should call getDrawableState.
14856     *
14857     * @see #drawableStateChanged
14858     * @see #getDrawableState
14859     */
14860    public void refreshDrawableState() {
14861        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14862        drawableStateChanged();
14863
14864        ViewParent parent = mParent;
14865        if (parent != null) {
14866            parent.childDrawableStateChanged(this);
14867        }
14868    }
14869
14870    /**
14871     * Return an array of resource IDs of the drawable states representing the
14872     * current state of the view.
14873     *
14874     * @return The current drawable state
14875     *
14876     * @see Drawable#setState(int[])
14877     * @see #drawableStateChanged()
14878     * @see #onCreateDrawableState(int)
14879     */
14880    public final int[] getDrawableState() {
14881        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14882            return mDrawableState;
14883        } else {
14884            mDrawableState = onCreateDrawableState(0);
14885            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14886            return mDrawableState;
14887        }
14888    }
14889
14890    /**
14891     * Generate the new {@link android.graphics.drawable.Drawable} state for
14892     * this view. This is called by the view
14893     * system when the cached Drawable state is determined to be invalid.  To
14894     * retrieve the current state, you should use {@link #getDrawableState}.
14895     *
14896     * @param extraSpace if non-zero, this is the number of extra entries you
14897     * would like in the returned array in which you can place your own
14898     * states.
14899     *
14900     * @return Returns an array holding the current {@link Drawable} state of
14901     * the view.
14902     *
14903     * @see #mergeDrawableStates(int[], int[])
14904     */
14905    protected int[] onCreateDrawableState(int extraSpace) {
14906        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14907                mParent instanceof View) {
14908            return ((View) mParent).onCreateDrawableState(extraSpace);
14909        }
14910
14911        int[] drawableState;
14912
14913        int privateFlags = mPrivateFlags;
14914
14915        int viewStateIndex = 0;
14916        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14917        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14918        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14919        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14920        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14921        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14922        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14923                HardwareRenderer.isAvailable()) {
14924            // This is set if HW acceleration is requested, even if the current
14925            // process doesn't allow it.  This is just to allow app preview
14926            // windows to better match their app.
14927            viewStateIndex |= VIEW_STATE_ACCELERATED;
14928        }
14929        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14930
14931        final int privateFlags2 = mPrivateFlags2;
14932        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14933        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14934
14935        drawableState = VIEW_STATE_SETS[viewStateIndex];
14936
14937        //noinspection ConstantIfStatement
14938        if (false) {
14939            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14940            Log.i("View", toString()
14941                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14942                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14943                    + " fo=" + hasFocus()
14944                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14945                    + " wf=" + hasWindowFocus()
14946                    + ": " + Arrays.toString(drawableState));
14947        }
14948
14949        if (extraSpace == 0) {
14950            return drawableState;
14951        }
14952
14953        final int[] fullState;
14954        if (drawableState != null) {
14955            fullState = new int[drawableState.length + extraSpace];
14956            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14957        } else {
14958            fullState = new int[extraSpace];
14959        }
14960
14961        return fullState;
14962    }
14963
14964    /**
14965     * Merge your own state values in <var>additionalState</var> into the base
14966     * state values <var>baseState</var> that were returned by
14967     * {@link #onCreateDrawableState(int)}.
14968     *
14969     * @param baseState The base state values returned by
14970     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14971     * own additional state values.
14972     *
14973     * @param additionalState The additional state values you would like
14974     * added to <var>baseState</var>; this array is not modified.
14975     *
14976     * @return As a convenience, the <var>baseState</var> array you originally
14977     * passed into the function is returned.
14978     *
14979     * @see #onCreateDrawableState(int)
14980     */
14981    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14982        final int N = baseState.length;
14983        int i = N - 1;
14984        while (i >= 0 && baseState[i] == 0) {
14985            i--;
14986        }
14987        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14988        return baseState;
14989    }
14990
14991    /**
14992     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14993     * on all Drawable objects associated with this view.
14994     */
14995    public void jumpDrawablesToCurrentState() {
14996        if (mBackground != null) {
14997            mBackground.jumpToCurrentState();
14998        }
14999    }
15000
15001    /**
15002     * Sets the background color for this view.
15003     * @param color the color of the background
15004     */
15005    @RemotableViewMethod
15006    public void setBackgroundColor(int color) {
15007        if (mBackground instanceof ColorDrawable) {
15008            ((ColorDrawable) mBackground.mutate()).setColor(color);
15009            computeOpaqueFlags();
15010            mBackgroundResource = 0;
15011        } else {
15012            setBackground(new ColorDrawable(color));
15013        }
15014    }
15015
15016    /**
15017     * Set the background to a given resource. The resource should refer to
15018     * a Drawable object or 0 to remove the background.
15019     * @param resid The identifier of the resource.
15020     *
15021     * @attr ref android.R.styleable#View_background
15022     */
15023    @RemotableViewMethod
15024    public void setBackgroundResource(int resid) {
15025        if (resid != 0 && resid == mBackgroundResource) {
15026            return;
15027        }
15028
15029        Drawable d= null;
15030        if (resid != 0) {
15031            d = mResources.getDrawable(resid);
15032        }
15033        setBackground(d);
15034
15035        mBackgroundResource = resid;
15036    }
15037
15038    /**
15039     * Set the background to a given Drawable, or remove the background. If the
15040     * background has padding, this View's padding is set to the background's
15041     * padding. However, when a background is removed, this View's padding isn't
15042     * touched. If setting the padding is desired, please use
15043     * {@link #setPadding(int, int, int, int)}.
15044     *
15045     * @param background The Drawable to use as the background, or null to remove the
15046     *        background
15047     */
15048    public void setBackground(Drawable background) {
15049        //noinspection deprecation
15050        setBackgroundDrawable(background);
15051    }
15052
15053    /**
15054     * @deprecated use {@link #setBackground(Drawable)} instead
15055     */
15056    @Deprecated
15057    public void setBackgroundDrawable(Drawable background) {
15058        computeOpaqueFlags();
15059
15060        if (background == mBackground) {
15061            return;
15062        }
15063
15064        boolean requestLayout = false;
15065
15066        mBackgroundResource = 0;
15067
15068        /*
15069         * Regardless of whether we're setting a new background or not, we want
15070         * to clear the previous drawable.
15071         */
15072        if (mBackground != null) {
15073            mBackground.setCallback(null);
15074            unscheduleDrawable(mBackground);
15075        }
15076
15077        if (background != null) {
15078            Rect padding = sThreadLocal.get();
15079            if (padding == null) {
15080                padding = new Rect();
15081                sThreadLocal.set(padding);
15082            }
15083            resetResolvedDrawables();
15084            background.setLayoutDirection(getLayoutDirection());
15085            if (background.getPadding(padding)) {
15086                resetResolvedPadding();
15087                switch (background.getLayoutDirection()) {
15088                    case LAYOUT_DIRECTION_RTL:
15089                        mUserPaddingLeftInitial = padding.right;
15090                        mUserPaddingRightInitial = padding.left;
15091                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15092                        break;
15093                    case LAYOUT_DIRECTION_LTR:
15094                    default:
15095                        mUserPaddingLeftInitial = padding.left;
15096                        mUserPaddingRightInitial = padding.right;
15097                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15098                }
15099            }
15100
15101            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15102            // if it has a different minimum size, we should layout again
15103            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15104                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15105                requestLayout = true;
15106            }
15107
15108            background.setCallback(this);
15109            if (background.isStateful()) {
15110                background.setState(getDrawableState());
15111            }
15112            background.setVisible(getVisibility() == VISIBLE, false);
15113            mBackground = background;
15114
15115            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15116                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15117                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15118                requestLayout = true;
15119            }
15120        } else {
15121            /* Remove the background */
15122            mBackground = null;
15123
15124            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15125                /*
15126                 * This view ONLY drew the background before and we're removing
15127                 * the background, so now it won't draw anything
15128                 * (hence we SKIP_DRAW)
15129                 */
15130                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15131                mPrivateFlags |= PFLAG_SKIP_DRAW;
15132            }
15133
15134            /*
15135             * When the background is set, we try to apply its padding to this
15136             * View. When the background is removed, we don't touch this View's
15137             * padding. This is noted in the Javadocs. Hence, we don't need to
15138             * requestLayout(), the invalidate() below is sufficient.
15139             */
15140
15141            // The old background's minimum size could have affected this
15142            // View's layout, so let's requestLayout
15143            requestLayout = true;
15144        }
15145
15146        computeOpaqueFlags();
15147
15148        if (requestLayout) {
15149            requestLayout();
15150        }
15151
15152        mBackgroundSizeChanged = true;
15153        invalidate(true);
15154    }
15155
15156    /**
15157     * Gets the background drawable
15158     *
15159     * @return The drawable used as the background for this view, if any.
15160     *
15161     * @see #setBackground(Drawable)
15162     *
15163     * @attr ref android.R.styleable#View_background
15164     */
15165    public Drawable getBackground() {
15166        return mBackground;
15167    }
15168
15169    /**
15170     * Sets the padding. The view may add on the space required to display
15171     * the scrollbars, depending on the style and visibility of the scrollbars.
15172     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15173     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15174     * from the values set in this call.
15175     *
15176     * @attr ref android.R.styleable#View_padding
15177     * @attr ref android.R.styleable#View_paddingBottom
15178     * @attr ref android.R.styleable#View_paddingLeft
15179     * @attr ref android.R.styleable#View_paddingRight
15180     * @attr ref android.R.styleable#View_paddingTop
15181     * @param left the left padding in pixels
15182     * @param top the top padding in pixels
15183     * @param right the right padding in pixels
15184     * @param bottom the bottom padding in pixels
15185     */
15186    public void setPadding(int left, int top, int right, int bottom) {
15187        resetResolvedPadding();
15188
15189        mUserPaddingStart = UNDEFINED_PADDING;
15190        mUserPaddingEnd = UNDEFINED_PADDING;
15191
15192        mUserPaddingLeftInitial = left;
15193        mUserPaddingRightInitial = right;
15194
15195        internalSetPadding(left, top, right, bottom);
15196    }
15197
15198    /**
15199     * @hide
15200     */
15201    protected void internalSetPadding(int left, int top, int right, int bottom) {
15202        mUserPaddingLeft = left;
15203        mUserPaddingRight = right;
15204        mUserPaddingBottom = bottom;
15205
15206        final int viewFlags = mViewFlags;
15207        boolean changed = false;
15208
15209        // Common case is there are no scroll bars.
15210        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15211            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15212                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15213                        ? 0 : getVerticalScrollbarWidth();
15214                switch (mVerticalScrollbarPosition) {
15215                    case SCROLLBAR_POSITION_DEFAULT:
15216                        if (isLayoutRtl()) {
15217                            left += offset;
15218                        } else {
15219                            right += offset;
15220                        }
15221                        break;
15222                    case SCROLLBAR_POSITION_RIGHT:
15223                        right += offset;
15224                        break;
15225                    case SCROLLBAR_POSITION_LEFT:
15226                        left += offset;
15227                        break;
15228                }
15229            }
15230            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15231                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15232                        ? 0 : getHorizontalScrollbarHeight();
15233            }
15234        }
15235
15236        if (mPaddingLeft != left) {
15237            changed = true;
15238            mPaddingLeft = left;
15239        }
15240        if (mPaddingTop != top) {
15241            changed = true;
15242            mPaddingTop = top;
15243        }
15244        if (mPaddingRight != right) {
15245            changed = true;
15246            mPaddingRight = right;
15247        }
15248        if (mPaddingBottom != bottom) {
15249            changed = true;
15250            mPaddingBottom = bottom;
15251        }
15252
15253        if (changed) {
15254            requestLayout();
15255        }
15256    }
15257
15258    /**
15259     * Sets the relative padding. The view may add on the space required to display
15260     * the scrollbars, depending on the style and visibility of the scrollbars.
15261     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15262     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15263     * from the values set in this call.
15264     *
15265     * @attr ref android.R.styleable#View_padding
15266     * @attr ref android.R.styleable#View_paddingBottom
15267     * @attr ref android.R.styleable#View_paddingStart
15268     * @attr ref android.R.styleable#View_paddingEnd
15269     * @attr ref android.R.styleable#View_paddingTop
15270     * @param start the start padding in pixels
15271     * @param top the top padding in pixels
15272     * @param end the end padding in pixels
15273     * @param bottom the bottom padding in pixels
15274     */
15275    public void setPaddingRelative(int start, int top, int end, int bottom) {
15276        resetResolvedPadding();
15277
15278        mUserPaddingStart = start;
15279        mUserPaddingEnd = end;
15280
15281        switch(getLayoutDirection()) {
15282            case LAYOUT_DIRECTION_RTL:
15283                mUserPaddingLeftInitial = end;
15284                mUserPaddingRightInitial = start;
15285                internalSetPadding(end, top, start, bottom);
15286                break;
15287            case LAYOUT_DIRECTION_LTR:
15288            default:
15289                mUserPaddingLeftInitial = start;
15290                mUserPaddingRightInitial = end;
15291                internalSetPadding(start, top, end, bottom);
15292        }
15293    }
15294
15295    /**
15296     * Returns the top padding of this view.
15297     *
15298     * @return the top padding in pixels
15299     */
15300    public int getPaddingTop() {
15301        return mPaddingTop;
15302    }
15303
15304    /**
15305     * Returns the bottom padding of this view. If there are inset and enabled
15306     * scrollbars, this value may include the space required to display the
15307     * scrollbars as well.
15308     *
15309     * @return the bottom padding in pixels
15310     */
15311    public int getPaddingBottom() {
15312        return mPaddingBottom;
15313    }
15314
15315    /**
15316     * Returns the left padding of this view. If there are inset and enabled
15317     * scrollbars, this value may include the space required to display the
15318     * scrollbars as well.
15319     *
15320     * @return the left padding in pixels
15321     */
15322    public int getPaddingLeft() {
15323        if (!isPaddingResolved()) {
15324            resolvePadding();
15325        }
15326        return mPaddingLeft;
15327    }
15328
15329    /**
15330     * Returns the start padding of this view depending on its resolved layout direction.
15331     * If there are inset and enabled scrollbars, this value may include the space
15332     * required to display the scrollbars as well.
15333     *
15334     * @return the start padding in pixels
15335     */
15336    public int getPaddingStart() {
15337        if (!isPaddingResolved()) {
15338            resolvePadding();
15339        }
15340        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15341                mPaddingRight : mPaddingLeft;
15342    }
15343
15344    /**
15345     * Returns the right padding of this view. If there are inset and enabled
15346     * scrollbars, this value may include the space required to display the
15347     * scrollbars as well.
15348     *
15349     * @return the right padding in pixels
15350     */
15351    public int getPaddingRight() {
15352        if (!isPaddingResolved()) {
15353            resolvePadding();
15354        }
15355        return mPaddingRight;
15356    }
15357
15358    /**
15359     * Returns the end padding of this view depending on its resolved layout direction.
15360     * If there are inset and enabled scrollbars, this value may include the space
15361     * required to display the scrollbars as well.
15362     *
15363     * @return the end padding in pixels
15364     */
15365    public int getPaddingEnd() {
15366        if (!isPaddingResolved()) {
15367            resolvePadding();
15368        }
15369        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15370                mPaddingLeft : mPaddingRight;
15371    }
15372
15373    /**
15374     * Return if the padding as been set thru relative values
15375     * {@link #setPaddingRelative(int, int, int, int)} or thru
15376     * @attr ref android.R.styleable#View_paddingStart or
15377     * @attr ref android.R.styleable#View_paddingEnd
15378     *
15379     * @return true if the padding is relative or false if it is not.
15380     */
15381    public boolean isPaddingRelative() {
15382        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15383    }
15384
15385    Insets computeOpticalInsets() {
15386        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15387    }
15388
15389    /**
15390     * @hide
15391     */
15392    public void resetPaddingToInitialValues() {
15393        if (isRtlCompatibilityMode()) {
15394            mPaddingLeft = mUserPaddingLeftInitial;
15395            mPaddingRight = mUserPaddingRightInitial;
15396            return;
15397        }
15398        if (isLayoutRtl()) {
15399            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15400            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15401        } else {
15402            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15403            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15404        }
15405    }
15406
15407    /**
15408     * @hide
15409     */
15410    public Insets getOpticalInsets() {
15411        if (mLayoutInsets == null) {
15412            mLayoutInsets = computeOpticalInsets();
15413        }
15414        return mLayoutInsets;
15415    }
15416
15417    /**
15418     * Changes the selection state of this view. A view can be selected or not.
15419     * Note that selection is not the same as focus. Views are typically
15420     * selected in the context of an AdapterView like ListView or GridView;
15421     * the selected view is the view that is highlighted.
15422     *
15423     * @param selected true if the view must be selected, false otherwise
15424     */
15425    public void setSelected(boolean selected) {
15426        //noinspection DoubleNegation
15427        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15428            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15429            if (!selected) resetPressedState();
15430            invalidate(true);
15431            refreshDrawableState();
15432            dispatchSetSelected(selected);
15433            notifyViewAccessibilityStateChangedIfNeeded();
15434        }
15435    }
15436
15437    /**
15438     * Dispatch setSelected to all of this View's children.
15439     *
15440     * @see #setSelected(boolean)
15441     *
15442     * @param selected The new selected state
15443     */
15444    protected void dispatchSetSelected(boolean selected) {
15445    }
15446
15447    /**
15448     * Indicates the selection state of this view.
15449     *
15450     * @return true if the view is selected, false otherwise
15451     */
15452    @ViewDebug.ExportedProperty
15453    public boolean isSelected() {
15454        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15455    }
15456
15457    /**
15458     * Changes the activated state of this view. A view can be activated or not.
15459     * Note that activation is not the same as selection.  Selection is
15460     * a transient property, representing the view (hierarchy) the user is
15461     * currently interacting with.  Activation is a longer-term state that the
15462     * user can move views in and out of.  For example, in a list view with
15463     * single or multiple selection enabled, the views in the current selection
15464     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15465     * here.)  The activated state is propagated down to children of the view it
15466     * is set on.
15467     *
15468     * @param activated true if the view must be activated, false otherwise
15469     */
15470    public void setActivated(boolean activated) {
15471        //noinspection DoubleNegation
15472        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15473            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15474            invalidate(true);
15475            refreshDrawableState();
15476            dispatchSetActivated(activated);
15477        }
15478    }
15479
15480    /**
15481     * Dispatch setActivated to all of this View's children.
15482     *
15483     * @see #setActivated(boolean)
15484     *
15485     * @param activated The new activated state
15486     */
15487    protected void dispatchSetActivated(boolean activated) {
15488    }
15489
15490    /**
15491     * Indicates the activation state of this view.
15492     *
15493     * @return true if the view is activated, false otherwise
15494     */
15495    @ViewDebug.ExportedProperty
15496    public boolean isActivated() {
15497        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15498    }
15499
15500    /**
15501     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15502     * observer can be used to get notifications when global events, like
15503     * layout, happen.
15504     *
15505     * The returned ViewTreeObserver observer is not guaranteed to remain
15506     * valid for the lifetime of this View. If the caller of this method keeps
15507     * a long-lived reference to ViewTreeObserver, it should always check for
15508     * the return value of {@link ViewTreeObserver#isAlive()}.
15509     *
15510     * @return The ViewTreeObserver for this view's hierarchy.
15511     */
15512    public ViewTreeObserver getViewTreeObserver() {
15513        if (mAttachInfo != null) {
15514            return mAttachInfo.mTreeObserver;
15515        }
15516        if (mFloatingTreeObserver == null) {
15517            mFloatingTreeObserver = new ViewTreeObserver();
15518        }
15519        return mFloatingTreeObserver;
15520    }
15521
15522    /**
15523     * <p>Finds the topmost view in the current view hierarchy.</p>
15524     *
15525     * @return the topmost view containing this view
15526     */
15527    public View getRootView() {
15528        if (mAttachInfo != null) {
15529            final View v = mAttachInfo.mRootView;
15530            if (v != null) {
15531                return v;
15532            }
15533        }
15534
15535        View parent = this;
15536
15537        while (parent.mParent != null && parent.mParent instanceof View) {
15538            parent = (View) parent.mParent;
15539        }
15540
15541        return parent;
15542    }
15543
15544    /**
15545     * Transforms a motion event from view-local coordinates to on-screen
15546     * coordinates.
15547     *
15548     * @param ev the view-local motion event
15549     * @return false if the transformation could not be applied
15550     * @hide
15551     */
15552    public boolean toGlobalMotionEvent(MotionEvent ev) {
15553        final AttachInfo info = mAttachInfo;
15554        if (info == null) {
15555            return false;
15556        }
15557
15558        transformMotionEventToGlobal(ev);
15559        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15560        return true;
15561    }
15562
15563    /**
15564     * Transforms a motion event from on-screen coordinates to view-local
15565     * coordinates.
15566     *
15567     * @param ev the on-screen motion event
15568     * @return false if the transformation could not be applied
15569     * @hide
15570     */
15571    public boolean toLocalMotionEvent(MotionEvent ev) {
15572        final AttachInfo info = mAttachInfo;
15573        if (info == null) {
15574            return false;
15575        }
15576
15577        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15578        transformMotionEventToLocal(ev);
15579        return true;
15580    }
15581
15582    /**
15583     * Recursive helper method that applies transformations in post-order.
15584     *
15585     * @param ev the on-screen motion event
15586     */
15587    private void transformMotionEventToLocal(MotionEvent ev) {
15588        final ViewParent parent = mParent;
15589        if (parent instanceof View) {
15590            final View vp = (View) parent;
15591            vp.transformMotionEventToLocal(ev);
15592            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15593        } else if (parent instanceof ViewRootImpl) {
15594            final ViewRootImpl vr = (ViewRootImpl) parent;
15595            ev.offsetLocation(0, vr.mCurScrollY);
15596        }
15597
15598        ev.offsetLocation(-mLeft, -mTop);
15599
15600        if (!hasIdentityMatrix()) {
15601            ev.transform(getInverseMatrix());
15602        }
15603    }
15604
15605    /**
15606     * Recursive helper method that applies transformations in pre-order.
15607     *
15608     * @param ev the on-screen motion event
15609     */
15610    private void transformMotionEventToGlobal(MotionEvent ev) {
15611        if (!hasIdentityMatrix()) {
15612            ev.transform(getMatrix());
15613        }
15614
15615        ev.offsetLocation(mLeft, mTop);
15616
15617        final ViewParent parent = mParent;
15618        if (parent instanceof View) {
15619            final View vp = (View) parent;
15620            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15621            vp.transformMotionEventToGlobal(ev);
15622        } else if (parent instanceof ViewRootImpl) {
15623            final ViewRootImpl vr = (ViewRootImpl) parent;
15624            ev.offsetLocation(0, -vr.mCurScrollY);
15625        }
15626    }
15627
15628    /**
15629     * <p>Computes the coordinates of this view on the screen. The argument
15630     * must be an array of two integers. After the method returns, the array
15631     * contains the x and y location in that order.</p>
15632     *
15633     * @param location an array of two integers in which to hold the coordinates
15634     */
15635    public void getLocationOnScreen(int[] location) {
15636        getLocationInWindow(location);
15637
15638        final AttachInfo info = mAttachInfo;
15639        if (info != null) {
15640            location[0] += info.mWindowLeft;
15641            location[1] += info.mWindowTop;
15642        }
15643    }
15644
15645    /**
15646     * <p>Computes the coordinates of this view in its window. The argument
15647     * must be an array of two integers. After the method returns, the array
15648     * contains the x and y location in that order.</p>
15649     *
15650     * @param location an array of two integers in which to hold the coordinates
15651     */
15652    public void getLocationInWindow(int[] location) {
15653        if (location == null || location.length < 2) {
15654            throw new IllegalArgumentException("location must be an array of two integers");
15655        }
15656
15657        if (mAttachInfo == null) {
15658            // When the view is not attached to a window, this method does not make sense
15659            location[0] = location[1] = 0;
15660            return;
15661        }
15662
15663        float[] position = mAttachInfo.mTmpTransformLocation;
15664        position[0] = position[1] = 0.0f;
15665
15666        if (!hasIdentityMatrix()) {
15667            getMatrix().mapPoints(position);
15668        }
15669
15670        position[0] += mLeft;
15671        position[1] += mTop;
15672
15673        ViewParent viewParent = mParent;
15674        while (viewParent instanceof View) {
15675            final View view = (View) viewParent;
15676
15677            position[0] -= view.mScrollX;
15678            position[1] -= view.mScrollY;
15679
15680            if (!view.hasIdentityMatrix()) {
15681                view.getMatrix().mapPoints(position);
15682            }
15683
15684            position[0] += view.mLeft;
15685            position[1] += view.mTop;
15686
15687            viewParent = view.mParent;
15688         }
15689
15690        if (viewParent instanceof ViewRootImpl) {
15691            // *cough*
15692            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15693            position[1] -= vr.mCurScrollY;
15694        }
15695
15696        location[0] = (int) (position[0] + 0.5f);
15697        location[1] = (int) (position[1] + 0.5f);
15698    }
15699
15700    /**
15701     * {@hide}
15702     * @param id the id of the view to be found
15703     * @return the view of the specified id, null if cannot be found
15704     */
15705    protected View findViewTraversal(int id) {
15706        if (id == mID) {
15707            return this;
15708        }
15709        return null;
15710    }
15711
15712    /**
15713     * {@hide}
15714     * @param tag the tag of the view to be found
15715     * @return the view of specified tag, null if cannot be found
15716     */
15717    protected View findViewWithTagTraversal(Object tag) {
15718        if (tag != null && tag.equals(mTag)) {
15719            return this;
15720        }
15721        return null;
15722    }
15723
15724    /**
15725     * {@hide}
15726     * @param predicate The predicate to evaluate.
15727     * @param childToSkip If not null, ignores this child during the recursive traversal.
15728     * @return The first view that matches the predicate or null.
15729     */
15730    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15731        if (predicate.apply(this)) {
15732            return this;
15733        }
15734        return null;
15735    }
15736
15737    /**
15738     * Look for a child view with the given id.  If this view has the given
15739     * id, return this view.
15740     *
15741     * @param id The id to search for.
15742     * @return The view that has the given id in the hierarchy or null
15743     */
15744    public final View findViewById(int id) {
15745        if (id < 0) {
15746            return null;
15747        }
15748        return findViewTraversal(id);
15749    }
15750
15751    /**
15752     * Finds a view by its unuque and stable accessibility id.
15753     *
15754     * @param accessibilityId The searched accessibility id.
15755     * @return The found view.
15756     */
15757    final View findViewByAccessibilityId(int accessibilityId) {
15758        if (accessibilityId < 0) {
15759            return null;
15760        }
15761        return findViewByAccessibilityIdTraversal(accessibilityId);
15762    }
15763
15764    /**
15765     * Performs the traversal to find a view by its unuque and stable accessibility id.
15766     *
15767     * <strong>Note:</strong>This method does not stop at the root namespace
15768     * boundary since the user can touch the screen at an arbitrary location
15769     * potentially crossing the root namespace bounday which will send an
15770     * accessibility event to accessibility services and they should be able
15771     * to obtain the event source. Also accessibility ids are guaranteed to be
15772     * unique in the window.
15773     *
15774     * @param accessibilityId The accessibility id.
15775     * @return The found view.
15776     *
15777     * @hide
15778     */
15779    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15780        if (getAccessibilityViewId() == accessibilityId) {
15781            return this;
15782        }
15783        return null;
15784    }
15785
15786    /**
15787     * Look for a child view with the given tag.  If this view has the given
15788     * tag, return this view.
15789     *
15790     * @param tag The tag to search for, using "tag.equals(getTag())".
15791     * @return The View that has the given tag in the hierarchy or null
15792     */
15793    public final View findViewWithTag(Object tag) {
15794        if (tag == null) {
15795            return null;
15796        }
15797        return findViewWithTagTraversal(tag);
15798    }
15799
15800    /**
15801     * {@hide}
15802     * Look for a child view that matches the specified predicate.
15803     * If this view matches the predicate, return this view.
15804     *
15805     * @param predicate The predicate to evaluate.
15806     * @return The first view that matches the predicate or null.
15807     */
15808    public final View findViewByPredicate(Predicate<View> predicate) {
15809        return findViewByPredicateTraversal(predicate, null);
15810    }
15811
15812    /**
15813     * {@hide}
15814     * Look for a child view that matches the specified predicate,
15815     * starting with the specified view and its descendents and then
15816     * recusively searching the ancestors and siblings of that view
15817     * until this view is reached.
15818     *
15819     * This method is useful in cases where the predicate does not match
15820     * a single unique view (perhaps multiple views use the same id)
15821     * and we are trying to find the view that is "closest" in scope to the
15822     * starting view.
15823     *
15824     * @param start The view to start from.
15825     * @param predicate The predicate to evaluate.
15826     * @return The first view that matches the predicate or null.
15827     */
15828    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15829        View childToSkip = null;
15830        for (;;) {
15831            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15832            if (view != null || start == this) {
15833                return view;
15834            }
15835
15836            ViewParent parent = start.getParent();
15837            if (parent == null || !(parent instanceof View)) {
15838                return null;
15839            }
15840
15841            childToSkip = start;
15842            start = (View) parent;
15843        }
15844    }
15845
15846    /**
15847     * Sets the identifier for this view. The identifier does not have to be
15848     * unique in this view's hierarchy. The identifier should be a positive
15849     * number.
15850     *
15851     * @see #NO_ID
15852     * @see #getId()
15853     * @see #findViewById(int)
15854     *
15855     * @param id a number used to identify the view
15856     *
15857     * @attr ref android.R.styleable#View_id
15858     */
15859    public void setId(int id) {
15860        mID = id;
15861        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15862            mID = generateViewId();
15863        }
15864    }
15865
15866    /**
15867     * {@hide}
15868     *
15869     * @param isRoot true if the view belongs to the root namespace, false
15870     *        otherwise
15871     */
15872    public void setIsRootNamespace(boolean isRoot) {
15873        if (isRoot) {
15874            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15875        } else {
15876            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15877        }
15878    }
15879
15880    /**
15881     * {@hide}
15882     *
15883     * @return true if the view belongs to the root namespace, false otherwise
15884     */
15885    public boolean isRootNamespace() {
15886        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15887    }
15888
15889    /**
15890     * Returns this view's identifier.
15891     *
15892     * @return a positive integer used to identify the view or {@link #NO_ID}
15893     *         if the view has no ID
15894     *
15895     * @see #setId(int)
15896     * @see #findViewById(int)
15897     * @attr ref android.R.styleable#View_id
15898     */
15899    @ViewDebug.CapturedViewProperty
15900    public int getId() {
15901        return mID;
15902    }
15903
15904    /**
15905     * Returns this view's tag.
15906     *
15907     * @return the Object stored in this view as a tag
15908     *
15909     * @see #setTag(Object)
15910     * @see #getTag(int)
15911     */
15912    @ViewDebug.ExportedProperty
15913    public Object getTag() {
15914        return mTag;
15915    }
15916
15917    /**
15918     * Sets the tag associated with this view. A tag can be used to mark
15919     * a view in its hierarchy and does not have to be unique within the
15920     * hierarchy. Tags can also be used to store data within a view without
15921     * resorting to another data structure.
15922     *
15923     * @param tag an Object to tag the view with
15924     *
15925     * @see #getTag()
15926     * @see #setTag(int, Object)
15927     */
15928    public void setTag(final Object tag) {
15929        mTag = tag;
15930    }
15931
15932    /**
15933     * Returns the tag associated with this view and the specified key.
15934     *
15935     * @param key The key identifying the tag
15936     *
15937     * @return the Object stored in this view as a tag
15938     *
15939     * @see #setTag(int, Object)
15940     * @see #getTag()
15941     */
15942    public Object getTag(int key) {
15943        if (mKeyedTags != null) return mKeyedTags.get(key);
15944        return null;
15945    }
15946
15947    /**
15948     * Sets a tag associated with this view and a key. A tag can be used
15949     * to mark a view in its hierarchy and does not have to be unique within
15950     * the hierarchy. Tags can also be used to store data within a view
15951     * without resorting to another data structure.
15952     *
15953     * The specified key should be an id declared in the resources of the
15954     * application to ensure it is unique (see the <a
15955     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15956     * Keys identified as belonging to
15957     * the Android framework or not associated with any package will cause
15958     * an {@link IllegalArgumentException} to be thrown.
15959     *
15960     * @param key The key identifying the tag
15961     * @param tag An Object to tag the view with
15962     *
15963     * @throws IllegalArgumentException If they specified key is not valid
15964     *
15965     * @see #setTag(Object)
15966     * @see #getTag(int)
15967     */
15968    public void setTag(int key, final Object tag) {
15969        // If the package id is 0x00 or 0x01, it's either an undefined package
15970        // or a framework id
15971        if ((key >>> 24) < 2) {
15972            throw new IllegalArgumentException("The key must be an application-specific "
15973                    + "resource id.");
15974        }
15975
15976        setKeyedTag(key, tag);
15977    }
15978
15979    /**
15980     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15981     * framework id.
15982     *
15983     * @hide
15984     */
15985    public void setTagInternal(int key, Object tag) {
15986        if ((key >>> 24) != 0x1) {
15987            throw new IllegalArgumentException("The key must be a framework-specific "
15988                    + "resource id.");
15989        }
15990
15991        setKeyedTag(key, tag);
15992    }
15993
15994    private void setKeyedTag(int key, Object tag) {
15995        if (mKeyedTags == null) {
15996            mKeyedTags = new SparseArray<Object>(2);
15997        }
15998
15999        mKeyedTags.put(key, tag);
16000    }
16001
16002    /**
16003     * Prints information about this view in the log output, with the tag
16004     * {@link #VIEW_LOG_TAG}.
16005     *
16006     * @hide
16007     */
16008    public void debug() {
16009        debug(0);
16010    }
16011
16012    /**
16013     * Prints information about this view in the log output, with the tag
16014     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16015     * indentation defined by the <code>depth</code>.
16016     *
16017     * @param depth the indentation level
16018     *
16019     * @hide
16020     */
16021    protected void debug(int depth) {
16022        String output = debugIndent(depth - 1);
16023
16024        output += "+ " + this;
16025        int id = getId();
16026        if (id != -1) {
16027            output += " (id=" + id + ")";
16028        }
16029        Object tag = getTag();
16030        if (tag != null) {
16031            output += " (tag=" + tag + ")";
16032        }
16033        Log.d(VIEW_LOG_TAG, output);
16034
16035        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16036            output = debugIndent(depth) + " FOCUSED";
16037            Log.d(VIEW_LOG_TAG, output);
16038        }
16039
16040        output = debugIndent(depth);
16041        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16042                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16043                + "} ";
16044        Log.d(VIEW_LOG_TAG, output);
16045
16046        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16047                || mPaddingBottom != 0) {
16048            output = debugIndent(depth);
16049            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16050                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16051            Log.d(VIEW_LOG_TAG, output);
16052        }
16053
16054        output = debugIndent(depth);
16055        output += "mMeasureWidth=" + mMeasuredWidth +
16056                " mMeasureHeight=" + mMeasuredHeight;
16057        Log.d(VIEW_LOG_TAG, output);
16058
16059        output = debugIndent(depth);
16060        if (mLayoutParams == null) {
16061            output += "BAD! no layout params";
16062        } else {
16063            output = mLayoutParams.debug(output);
16064        }
16065        Log.d(VIEW_LOG_TAG, output);
16066
16067        output = debugIndent(depth);
16068        output += "flags={";
16069        output += View.printFlags(mViewFlags);
16070        output += "}";
16071        Log.d(VIEW_LOG_TAG, output);
16072
16073        output = debugIndent(depth);
16074        output += "privateFlags={";
16075        output += View.printPrivateFlags(mPrivateFlags);
16076        output += "}";
16077        Log.d(VIEW_LOG_TAG, output);
16078    }
16079
16080    /**
16081     * Creates a string of whitespaces used for indentation.
16082     *
16083     * @param depth the indentation level
16084     * @return a String containing (depth * 2 + 3) * 2 white spaces
16085     *
16086     * @hide
16087     */
16088    protected static String debugIndent(int depth) {
16089        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16090        for (int i = 0; i < (depth * 2) + 3; i++) {
16091            spaces.append(' ').append(' ');
16092        }
16093        return spaces.toString();
16094    }
16095
16096    /**
16097     * <p>Return the offset of the widget's text baseline from the widget's top
16098     * boundary. If this widget does not support baseline alignment, this
16099     * method returns -1. </p>
16100     *
16101     * @return the offset of the baseline within the widget's bounds or -1
16102     *         if baseline alignment is not supported
16103     */
16104    @ViewDebug.ExportedProperty(category = "layout")
16105    public int getBaseline() {
16106        return -1;
16107    }
16108
16109    /**
16110     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16111     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16112     * a layout pass.
16113     *
16114     * @return whether the view hierarchy is currently undergoing a layout pass
16115     */
16116    public boolean isInLayout() {
16117        ViewRootImpl viewRoot = getViewRootImpl();
16118        return (viewRoot != null && viewRoot.isInLayout());
16119    }
16120
16121    /**
16122     * Call this when something has changed which has invalidated the
16123     * layout of this view. This will schedule a layout pass of the view
16124     * tree. This should not be called while the view hierarchy is currently in a layout
16125     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16126     * end of the current layout pass (and then layout will run again) or after the current
16127     * frame is drawn and the next layout occurs.
16128     *
16129     * <p>Subclasses which override this method should call the superclass method to
16130     * handle possible request-during-layout errors correctly.</p>
16131     */
16132    public void requestLayout() {
16133        if (mMeasureCache != null) mMeasureCache.clear();
16134
16135        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16136            // Only trigger request-during-layout logic if this is the view requesting it,
16137            // not the views in its parent hierarchy
16138            ViewRootImpl viewRoot = getViewRootImpl();
16139            if (viewRoot != null && viewRoot.isInLayout()) {
16140                if (!viewRoot.requestLayoutDuringLayout(this)) {
16141                    return;
16142                }
16143            }
16144            mAttachInfo.mViewRequestingLayout = this;
16145        }
16146
16147        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16148        mPrivateFlags |= PFLAG_INVALIDATED;
16149
16150        if (mParent != null && !mParent.isLayoutRequested()) {
16151            mParent.requestLayout();
16152        }
16153        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16154            mAttachInfo.mViewRequestingLayout = null;
16155        }
16156    }
16157
16158    /**
16159     * Forces this view to be laid out during the next layout pass.
16160     * This method does not call requestLayout() or forceLayout()
16161     * on the parent.
16162     */
16163    public void forceLayout() {
16164        if (mMeasureCache != null) mMeasureCache.clear();
16165
16166        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16167        mPrivateFlags |= PFLAG_INVALIDATED;
16168    }
16169
16170    /**
16171     * <p>
16172     * This is called to find out how big a view should be. The parent
16173     * supplies constraint information in the width and height parameters.
16174     * </p>
16175     *
16176     * <p>
16177     * The actual measurement work of a view is performed in
16178     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16179     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16180     * </p>
16181     *
16182     *
16183     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16184     *        parent
16185     * @param heightMeasureSpec Vertical space requirements as imposed by the
16186     *        parent
16187     *
16188     * @see #onMeasure(int, int)
16189     */
16190    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16191        boolean optical = isLayoutModeOptical(this);
16192        if (optical != isLayoutModeOptical(mParent)) {
16193            Insets insets = getOpticalInsets();
16194            int oWidth  = insets.left + insets.right;
16195            int oHeight = insets.top  + insets.bottom;
16196            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16197            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16198        }
16199
16200        // Suppress sign extension for the low bytes
16201        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16202        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16203
16204        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16205                widthMeasureSpec != mOldWidthMeasureSpec ||
16206                heightMeasureSpec != mOldHeightMeasureSpec) {
16207
16208            // first clears the measured dimension flag
16209            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16210
16211            resolveRtlPropertiesIfNeeded();
16212
16213            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16214                    mMeasureCache.indexOfKey(key);
16215            if (cacheIndex < 0) {
16216                // measure ourselves, this should set the measured dimension flag back
16217                onMeasure(widthMeasureSpec, heightMeasureSpec);
16218                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16219            } else {
16220                long value = mMeasureCache.valueAt(cacheIndex);
16221                // Casting a long to int drops the high 32 bits, no mask needed
16222                setMeasuredDimension((int) (value >> 32), (int) value);
16223                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16224            }
16225
16226            // flag not set, setMeasuredDimension() was not invoked, we raise
16227            // an exception to warn the developer
16228            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16229                throw new IllegalStateException("onMeasure() did not set the"
16230                        + " measured dimension by calling"
16231                        + " setMeasuredDimension()");
16232            }
16233
16234            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16235        }
16236
16237        mOldWidthMeasureSpec = widthMeasureSpec;
16238        mOldHeightMeasureSpec = heightMeasureSpec;
16239
16240        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16241                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16242    }
16243
16244    /**
16245     * <p>
16246     * Measure the view and its content to determine the measured width and the
16247     * measured height. This method is invoked by {@link #measure(int, int)} and
16248     * should be overriden by subclasses to provide accurate and efficient
16249     * measurement of their contents.
16250     * </p>
16251     *
16252     * <p>
16253     * <strong>CONTRACT:</strong> When overriding this method, you
16254     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16255     * measured width and height of this view. Failure to do so will trigger an
16256     * <code>IllegalStateException</code>, thrown by
16257     * {@link #measure(int, int)}. Calling the superclass'
16258     * {@link #onMeasure(int, int)} is a valid use.
16259     * </p>
16260     *
16261     * <p>
16262     * The base class implementation of measure defaults to the background size,
16263     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16264     * override {@link #onMeasure(int, int)} to provide better measurements of
16265     * their content.
16266     * </p>
16267     *
16268     * <p>
16269     * If this method is overridden, it is the subclass's responsibility to make
16270     * sure the measured height and width are at least the view's minimum height
16271     * and width ({@link #getSuggestedMinimumHeight()} and
16272     * {@link #getSuggestedMinimumWidth()}).
16273     * </p>
16274     *
16275     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16276     *                         The requirements are encoded with
16277     *                         {@link android.view.View.MeasureSpec}.
16278     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16279     *                         The requirements are encoded with
16280     *                         {@link android.view.View.MeasureSpec}.
16281     *
16282     * @see #getMeasuredWidth()
16283     * @see #getMeasuredHeight()
16284     * @see #setMeasuredDimension(int, int)
16285     * @see #getSuggestedMinimumHeight()
16286     * @see #getSuggestedMinimumWidth()
16287     * @see android.view.View.MeasureSpec#getMode(int)
16288     * @see android.view.View.MeasureSpec#getSize(int)
16289     */
16290    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16291        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16292                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16293    }
16294
16295    /**
16296     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16297     * measured width and measured height. Failing to do so will trigger an
16298     * exception at measurement time.</p>
16299     *
16300     * @param measuredWidth The measured width of this view.  May be a complex
16301     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16302     * {@link #MEASURED_STATE_TOO_SMALL}.
16303     * @param measuredHeight The measured height of this view.  May be a complex
16304     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16305     * {@link #MEASURED_STATE_TOO_SMALL}.
16306     */
16307    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16308        boolean optical = isLayoutModeOptical(this);
16309        if (optical != isLayoutModeOptical(mParent)) {
16310            Insets insets = getOpticalInsets();
16311            int opticalWidth  = insets.left + insets.right;
16312            int opticalHeight = insets.top  + insets.bottom;
16313
16314            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16315            measuredHeight += optical ? opticalHeight : -opticalHeight;
16316        }
16317        mMeasuredWidth = measuredWidth;
16318        mMeasuredHeight = measuredHeight;
16319
16320        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16321    }
16322
16323    /**
16324     * Merge two states as returned by {@link #getMeasuredState()}.
16325     * @param curState The current state as returned from a view or the result
16326     * of combining multiple views.
16327     * @param newState The new view state to combine.
16328     * @return Returns a new integer reflecting the combination of the two
16329     * states.
16330     */
16331    public static int combineMeasuredStates(int curState, int newState) {
16332        return curState | newState;
16333    }
16334
16335    /**
16336     * Version of {@link #resolveSizeAndState(int, int, int)}
16337     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16338     */
16339    public static int resolveSize(int size, int measureSpec) {
16340        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16341    }
16342
16343    /**
16344     * Utility to reconcile a desired size and state, with constraints imposed
16345     * by a MeasureSpec.  Will take the desired size, unless a different size
16346     * is imposed by the constraints.  The returned value is a compound integer,
16347     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16348     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16349     * size is smaller than the size the view wants to be.
16350     *
16351     * @param size How big the view wants to be
16352     * @param measureSpec Constraints imposed by the parent
16353     * @return Size information bit mask as defined by
16354     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16355     */
16356    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16357        int result = size;
16358        int specMode = MeasureSpec.getMode(measureSpec);
16359        int specSize =  MeasureSpec.getSize(measureSpec);
16360        switch (specMode) {
16361        case MeasureSpec.UNSPECIFIED:
16362            result = size;
16363            break;
16364        case MeasureSpec.AT_MOST:
16365            if (specSize < size) {
16366                result = specSize | MEASURED_STATE_TOO_SMALL;
16367            } else {
16368                result = size;
16369            }
16370            break;
16371        case MeasureSpec.EXACTLY:
16372            result = specSize;
16373            break;
16374        }
16375        return result | (childMeasuredState&MEASURED_STATE_MASK);
16376    }
16377
16378    /**
16379     * Utility to return a default size. Uses the supplied size if the
16380     * MeasureSpec imposed no constraints. Will get larger if allowed
16381     * by the MeasureSpec.
16382     *
16383     * @param size Default size for this view
16384     * @param measureSpec Constraints imposed by the parent
16385     * @return The size this view should be.
16386     */
16387    public static int getDefaultSize(int size, int measureSpec) {
16388        int result = size;
16389        int specMode = MeasureSpec.getMode(measureSpec);
16390        int specSize = MeasureSpec.getSize(measureSpec);
16391
16392        switch (specMode) {
16393        case MeasureSpec.UNSPECIFIED:
16394            result = size;
16395            break;
16396        case MeasureSpec.AT_MOST:
16397        case MeasureSpec.EXACTLY:
16398            result = specSize;
16399            break;
16400        }
16401        return result;
16402    }
16403
16404    /**
16405     * Returns the suggested minimum height that the view should use. This
16406     * returns the maximum of the view's minimum height
16407     * and the background's minimum height
16408     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16409     * <p>
16410     * When being used in {@link #onMeasure(int, int)}, the caller should still
16411     * ensure the returned height is within the requirements of the parent.
16412     *
16413     * @return The suggested minimum height of the view.
16414     */
16415    protected int getSuggestedMinimumHeight() {
16416        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16417
16418    }
16419
16420    /**
16421     * Returns the suggested minimum width that the view should use. This
16422     * returns the maximum of the view's minimum width)
16423     * and the background's minimum width
16424     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16425     * <p>
16426     * When being used in {@link #onMeasure(int, int)}, the caller should still
16427     * ensure the returned width is within the requirements of the parent.
16428     *
16429     * @return The suggested minimum width of the view.
16430     */
16431    protected int getSuggestedMinimumWidth() {
16432        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16433    }
16434
16435    /**
16436     * Returns the minimum height of the view.
16437     *
16438     * @return the minimum height the view will try to be.
16439     *
16440     * @see #setMinimumHeight(int)
16441     *
16442     * @attr ref android.R.styleable#View_minHeight
16443     */
16444    public int getMinimumHeight() {
16445        return mMinHeight;
16446    }
16447
16448    /**
16449     * Sets the minimum height of the view. It is not guaranteed the view will
16450     * be able to achieve this minimum height (for example, if its parent layout
16451     * constrains it with less available height).
16452     *
16453     * @param minHeight The minimum height the view will try to be.
16454     *
16455     * @see #getMinimumHeight()
16456     *
16457     * @attr ref android.R.styleable#View_minHeight
16458     */
16459    public void setMinimumHeight(int minHeight) {
16460        mMinHeight = minHeight;
16461        requestLayout();
16462    }
16463
16464    /**
16465     * Returns the minimum width of the view.
16466     *
16467     * @return the minimum width the view will try to be.
16468     *
16469     * @see #setMinimumWidth(int)
16470     *
16471     * @attr ref android.R.styleable#View_minWidth
16472     */
16473    public int getMinimumWidth() {
16474        return mMinWidth;
16475    }
16476
16477    /**
16478     * Sets the minimum width of the view. It is not guaranteed the view will
16479     * be able to achieve this minimum width (for example, if its parent layout
16480     * constrains it with less available width).
16481     *
16482     * @param minWidth The minimum width the view will try to be.
16483     *
16484     * @see #getMinimumWidth()
16485     *
16486     * @attr ref android.R.styleable#View_minWidth
16487     */
16488    public void setMinimumWidth(int minWidth) {
16489        mMinWidth = minWidth;
16490        requestLayout();
16491
16492    }
16493
16494    /**
16495     * Get the animation currently associated with this view.
16496     *
16497     * @return The animation that is currently playing or
16498     *         scheduled to play for this view.
16499     */
16500    public Animation getAnimation() {
16501        return mCurrentAnimation;
16502    }
16503
16504    /**
16505     * Start the specified animation now.
16506     *
16507     * @param animation the animation to start now
16508     */
16509    public void startAnimation(Animation animation) {
16510        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16511        setAnimation(animation);
16512        invalidateParentCaches();
16513        invalidate(true);
16514    }
16515
16516    /**
16517     * Cancels any animations for this view.
16518     */
16519    public void clearAnimation() {
16520        if (mCurrentAnimation != null) {
16521            mCurrentAnimation.detach();
16522        }
16523        mCurrentAnimation = null;
16524        invalidateParentIfNeeded();
16525    }
16526
16527    /**
16528     * Sets the next animation to play for this view.
16529     * If you want the animation to play immediately, use
16530     * {@link #startAnimation(android.view.animation.Animation)} instead.
16531     * This method provides allows fine-grained
16532     * control over the start time and invalidation, but you
16533     * must make sure that 1) the animation has a start time set, and
16534     * 2) the view's parent (which controls animations on its children)
16535     * will be invalidated when the animation is supposed to
16536     * start.
16537     *
16538     * @param animation The next animation, or null.
16539     */
16540    public void setAnimation(Animation animation) {
16541        mCurrentAnimation = animation;
16542
16543        if (animation != null) {
16544            // If the screen is off assume the animation start time is now instead of
16545            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16546            // would cause the animation to start when the screen turns back on
16547            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16548                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16549                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16550            }
16551            animation.reset();
16552        }
16553    }
16554
16555    /**
16556     * Invoked by a parent ViewGroup to notify the start of the animation
16557     * currently associated with this view. If you override this method,
16558     * always call super.onAnimationStart();
16559     *
16560     * @see #setAnimation(android.view.animation.Animation)
16561     * @see #getAnimation()
16562     */
16563    protected void onAnimationStart() {
16564        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16565    }
16566
16567    /**
16568     * Invoked by a parent ViewGroup to notify the end of the animation
16569     * currently associated with this view. If you override this method,
16570     * always call super.onAnimationEnd();
16571     *
16572     * @see #setAnimation(android.view.animation.Animation)
16573     * @see #getAnimation()
16574     */
16575    protected void onAnimationEnd() {
16576        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16577    }
16578
16579    /**
16580     * Invoked if there is a Transform that involves alpha. Subclass that can
16581     * draw themselves with the specified alpha should return true, and then
16582     * respect that alpha when their onDraw() is called. If this returns false
16583     * then the view may be redirected to draw into an offscreen buffer to
16584     * fulfill the request, which will look fine, but may be slower than if the
16585     * subclass handles it internally. The default implementation returns false.
16586     *
16587     * @param alpha The alpha (0..255) to apply to the view's drawing
16588     * @return true if the view can draw with the specified alpha.
16589     */
16590    protected boolean onSetAlpha(int alpha) {
16591        return false;
16592    }
16593
16594    /**
16595     * This is used by the RootView to perform an optimization when
16596     * the view hierarchy contains one or several SurfaceView.
16597     * SurfaceView is always considered transparent, but its children are not,
16598     * therefore all View objects remove themselves from the global transparent
16599     * region (passed as a parameter to this function).
16600     *
16601     * @param region The transparent region for this ViewAncestor (window).
16602     *
16603     * @return Returns true if the effective visibility of the view at this
16604     * point is opaque, regardless of the transparent region; returns false
16605     * if it is possible for underlying windows to be seen behind the view.
16606     *
16607     * {@hide}
16608     */
16609    public boolean gatherTransparentRegion(Region region) {
16610        final AttachInfo attachInfo = mAttachInfo;
16611        if (region != null && attachInfo != null) {
16612            final int pflags = mPrivateFlags;
16613            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16614                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16615                // remove it from the transparent region.
16616                final int[] location = attachInfo.mTransparentLocation;
16617                getLocationInWindow(location);
16618                region.op(location[0], location[1], location[0] + mRight - mLeft,
16619                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16620            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16621                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16622                // exists, so we remove the background drawable's non-transparent
16623                // parts from this transparent region.
16624                applyDrawableToTransparentRegion(mBackground, region);
16625            }
16626        }
16627        return true;
16628    }
16629
16630    /**
16631     * Play a sound effect for this view.
16632     *
16633     * <p>The framework will play sound effects for some built in actions, such as
16634     * clicking, but you may wish to play these effects in your widget,
16635     * for instance, for internal navigation.
16636     *
16637     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16638     * {@link #isSoundEffectsEnabled()} is true.
16639     *
16640     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16641     */
16642    public void playSoundEffect(int soundConstant) {
16643        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16644            return;
16645        }
16646        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16647    }
16648
16649    /**
16650     * BZZZTT!!1!
16651     *
16652     * <p>Provide haptic feedback to the user for this view.
16653     *
16654     * <p>The framework will provide haptic feedback for some built in actions,
16655     * such as long presses, but you may wish to provide feedback for your
16656     * own widget.
16657     *
16658     * <p>The feedback will only be performed if
16659     * {@link #isHapticFeedbackEnabled()} is true.
16660     *
16661     * @param feedbackConstant One of the constants defined in
16662     * {@link HapticFeedbackConstants}
16663     */
16664    public boolean performHapticFeedback(int feedbackConstant) {
16665        return performHapticFeedback(feedbackConstant, 0);
16666    }
16667
16668    /**
16669     * BZZZTT!!1!
16670     *
16671     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16672     *
16673     * @param feedbackConstant One of the constants defined in
16674     * {@link HapticFeedbackConstants}
16675     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16676     */
16677    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16678        if (mAttachInfo == null) {
16679            return false;
16680        }
16681        //noinspection SimplifiableIfStatement
16682        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16683                && !isHapticFeedbackEnabled()) {
16684            return false;
16685        }
16686        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16687                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16688    }
16689
16690    /**
16691     * Request that the visibility of the status bar or other screen/window
16692     * decorations be changed.
16693     *
16694     * <p>This method is used to put the over device UI into temporary modes
16695     * where the user's attention is focused more on the application content,
16696     * by dimming or hiding surrounding system affordances.  This is typically
16697     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16698     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16699     * to be placed behind the action bar (and with these flags other system
16700     * affordances) so that smooth transitions between hiding and showing them
16701     * can be done.
16702     *
16703     * <p>Two representative examples of the use of system UI visibility is
16704     * implementing a content browsing application (like a magazine reader)
16705     * and a video playing application.
16706     *
16707     * <p>The first code shows a typical implementation of a View in a content
16708     * browsing application.  In this implementation, the application goes
16709     * into a content-oriented mode by hiding the status bar and action bar,
16710     * and putting the navigation elements into lights out mode.  The user can
16711     * then interact with content while in this mode.  Such an application should
16712     * provide an easy way for the user to toggle out of the mode (such as to
16713     * check information in the status bar or access notifications).  In the
16714     * implementation here, this is done simply by tapping on the content.
16715     *
16716     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16717     *      content}
16718     *
16719     * <p>This second code sample shows a typical implementation of a View
16720     * in a video playing application.  In this situation, while the video is
16721     * playing the application would like to go into a complete full-screen mode,
16722     * to use as much of the display as possible for the video.  When in this state
16723     * the user can not interact with the application; the system intercepts
16724     * touching on the screen to pop the UI out of full screen mode.  See
16725     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16726     *
16727     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16728     *      content}
16729     *
16730     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16731     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16732     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16733     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
16734     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16735     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16736     */
16737    public void setSystemUiVisibility(int visibility) {
16738        if (visibility != mSystemUiVisibility) {
16739            mSystemUiVisibility = visibility;
16740            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16741                mParent.recomputeViewAttributes(this);
16742            }
16743        }
16744    }
16745
16746    /**
16747     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
16748     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16749     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16750     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16751     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
16752     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16753     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16754     */
16755    public int getSystemUiVisibility() {
16756        return mSystemUiVisibility;
16757    }
16758
16759    /**
16760     * Returns the current system UI visibility that is currently set for
16761     * the entire window.  This is the combination of the
16762     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16763     * views in the window.
16764     */
16765    public int getWindowSystemUiVisibility() {
16766        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16767    }
16768
16769    /**
16770     * Override to find out when the window's requested system UI visibility
16771     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16772     * This is different from the callbacks received through
16773     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16774     * in that this is only telling you about the local request of the window,
16775     * not the actual values applied by the system.
16776     */
16777    public void onWindowSystemUiVisibilityChanged(int visible) {
16778    }
16779
16780    /**
16781     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16782     * the view hierarchy.
16783     */
16784    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16785        onWindowSystemUiVisibilityChanged(visible);
16786    }
16787
16788    /**
16789     * Set a listener to receive callbacks when the visibility of the system bar changes.
16790     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16791     */
16792    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16793        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16794        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16795            mParent.recomputeViewAttributes(this);
16796        }
16797    }
16798
16799    /**
16800     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16801     * the view hierarchy.
16802     */
16803    public void dispatchSystemUiVisibilityChanged(int visibility) {
16804        ListenerInfo li = mListenerInfo;
16805        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16806            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16807                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16808        }
16809    }
16810
16811    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16812        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16813        if (val != mSystemUiVisibility) {
16814            setSystemUiVisibility(val);
16815            return true;
16816        }
16817        return false;
16818    }
16819
16820    /** @hide */
16821    public void setDisabledSystemUiVisibility(int flags) {
16822        if (mAttachInfo != null) {
16823            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16824                mAttachInfo.mDisabledSystemUiVisibility = flags;
16825                if (mParent != null) {
16826                    mParent.recomputeViewAttributes(this);
16827                }
16828            }
16829        }
16830    }
16831
16832    /**
16833     * Creates an image that the system displays during the drag and drop
16834     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16835     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16836     * appearance as the given View. The default also positions the center of the drag shadow
16837     * directly under the touch point. If no View is provided (the constructor with no parameters
16838     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16839     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16840     * default is an invisible drag shadow.
16841     * <p>
16842     * You are not required to use the View you provide to the constructor as the basis of the
16843     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16844     * anything you want as the drag shadow.
16845     * </p>
16846     * <p>
16847     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16848     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16849     *  size and position of the drag shadow. It uses this data to construct a
16850     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16851     *  so that your application can draw the shadow image in the Canvas.
16852     * </p>
16853     *
16854     * <div class="special reference">
16855     * <h3>Developer Guides</h3>
16856     * <p>For a guide to implementing drag and drop features, read the
16857     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16858     * </div>
16859     */
16860    public static class DragShadowBuilder {
16861        private final WeakReference<View> mView;
16862
16863        /**
16864         * Constructs a shadow image builder based on a View. By default, the resulting drag
16865         * shadow will have the same appearance and dimensions as the View, with the touch point
16866         * over the center of the View.
16867         * @param view A View. Any View in scope can be used.
16868         */
16869        public DragShadowBuilder(View view) {
16870            mView = new WeakReference<View>(view);
16871        }
16872
16873        /**
16874         * Construct a shadow builder object with no associated View.  This
16875         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16876         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16877         * to supply the drag shadow's dimensions and appearance without
16878         * reference to any View object. If they are not overridden, then the result is an
16879         * invisible drag shadow.
16880         */
16881        public DragShadowBuilder() {
16882            mView = new WeakReference<View>(null);
16883        }
16884
16885        /**
16886         * Returns the View object that had been passed to the
16887         * {@link #View.DragShadowBuilder(View)}
16888         * constructor.  If that View parameter was {@code null} or if the
16889         * {@link #View.DragShadowBuilder()}
16890         * constructor was used to instantiate the builder object, this method will return
16891         * null.
16892         *
16893         * @return The View object associate with this builder object.
16894         */
16895        @SuppressWarnings({"JavadocReference"})
16896        final public View getView() {
16897            return mView.get();
16898        }
16899
16900        /**
16901         * Provides the metrics for the shadow image. These include the dimensions of
16902         * the shadow image, and the point within that shadow that should
16903         * be centered under the touch location while dragging.
16904         * <p>
16905         * The default implementation sets the dimensions of the shadow to be the
16906         * same as the dimensions of the View itself and centers the shadow under
16907         * the touch point.
16908         * </p>
16909         *
16910         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16911         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16912         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16913         * image.
16914         *
16915         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16916         * shadow image that should be underneath the touch point during the drag and drop
16917         * operation. Your application must set {@link android.graphics.Point#x} to the
16918         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16919         */
16920        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16921            final View view = mView.get();
16922            if (view != null) {
16923                shadowSize.set(view.getWidth(), view.getHeight());
16924                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16925            } else {
16926                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16927            }
16928        }
16929
16930        /**
16931         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16932         * based on the dimensions it received from the
16933         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16934         *
16935         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16936         */
16937        public void onDrawShadow(Canvas canvas) {
16938            final View view = mView.get();
16939            if (view != null) {
16940                view.draw(canvas);
16941            } else {
16942                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16943            }
16944        }
16945    }
16946
16947    /**
16948     * Starts a drag and drop operation. When your application calls this method, it passes a
16949     * {@link android.view.View.DragShadowBuilder} object to the system. The
16950     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16951     * to get metrics for the drag shadow, and then calls the object's
16952     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16953     * <p>
16954     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16955     *  drag events to all the View objects in your application that are currently visible. It does
16956     *  this either by calling the View object's drag listener (an implementation of
16957     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16958     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16959     *  Both are passed a {@link android.view.DragEvent} object that has a
16960     *  {@link android.view.DragEvent#getAction()} value of
16961     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16962     * </p>
16963     * <p>
16964     * Your application can invoke startDrag() on any attached View object. The View object does not
16965     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16966     * be related to the View the user selected for dragging.
16967     * </p>
16968     * @param data A {@link android.content.ClipData} object pointing to the data to be
16969     * transferred by the drag and drop operation.
16970     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16971     * drag shadow.
16972     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16973     * drop operation. This Object is put into every DragEvent object sent by the system during the
16974     * current drag.
16975     * <p>
16976     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16977     * to the target Views. For example, it can contain flags that differentiate between a
16978     * a copy operation and a move operation.
16979     * </p>
16980     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16981     * so the parameter should be set to 0.
16982     * @return {@code true} if the method completes successfully, or
16983     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16984     * do a drag, and so no drag operation is in progress.
16985     */
16986    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16987            Object myLocalState, int flags) {
16988        if (ViewDebug.DEBUG_DRAG) {
16989            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16990        }
16991        boolean okay = false;
16992
16993        Point shadowSize = new Point();
16994        Point shadowTouchPoint = new Point();
16995        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16996
16997        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16998                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16999            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17000        }
17001
17002        if (ViewDebug.DEBUG_DRAG) {
17003            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17004                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17005        }
17006        Surface surface = new Surface();
17007        try {
17008            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17009                    flags, shadowSize.x, shadowSize.y, surface);
17010            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17011                    + " surface=" + surface);
17012            if (token != null) {
17013                Canvas canvas = surface.lockCanvas(null);
17014                try {
17015                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17016                    shadowBuilder.onDrawShadow(canvas);
17017                } finally {
17018                    surface.unlockCanvasAndPost(canvas);
17019                }
17020
17021                final ViewRootImpl root = getViewRootImpl();
17022
17023                // Cache the local state object for delivery with DragEvents
17024                root.setLocalDragState(myLocalState);
17025
17026                // repurpose 'shadowSize' for the last touch point
17027                root.getLastTouchPoint(shadowSize);
17028
17029                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17030                        shadowSize.x, shadowSize.y,
17031                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17032                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17033
17034                // Off and running!  Release our local surface instance; the drag
17035                // shadow surface is now managed by the system process.
17036                surface.release();
17037            }
17038        } catch (Exception e) {
17039            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17040            surface.destroy();
17041        }
17042
17043        return okay;
17044    }
17045
17046    /**
17047     * Handles drag events sent by the system following a call to
17048     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17049     *<p>
17050     * When the system calls this method, it passes a
17051     * {@link android.view.DragEvent} object. A call to
17052     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17053     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17054     * operation.
17055     * @param event The {@link android.view.DragEvent} sent by the system.
17056     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17057     * in DragEvent, indicating the type of drag event represented by this object.
17058     * @return {@code true} if the method was successful, otherwise {@code false}.
17059     * <p>
17060     *  The method should return {@code true} in response to an action type of
17061     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17062     *  operation.
17063     * </p>
17064     * <p>
17065     *  The method should also return {@code true} in response to an action type of
17066     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17067     *  {@code false} if it didn't.
17068     * </p>
17069     */
17070    public boolean onDragEvent(DragEvent event) {
17071        return false;
17072    }
17073
17074    /**
17075     * Detects if this View is enabled and has a drag event listener.
17076     * If both are true, then it calls the drag event listener with the
17077     * {@link android.view.DragEvent} it received. If the drag event listener returns
17078     * {@code true}, then dispatchDragEvent() returns {@code true}.
17079     * <p>
17080     * For all other cases, the method calls the
17081     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17082     * method and returns its result.
17083     * </p>
17084     * <p>
17085     * This ensures that a drag event is always consumed, even if the View does not have a drag
17086     * event listener. However, if the View has a listener and the listener returns true, then
17087     * onDragEvent() is not called.
17088     * </p>
17089     */
17090    public boolean dispatchDragEvent(DragEvent event) {
17091        ListenerInfo li = mListenerInfo;
17092        //noinspection SimplifiableIfStatement
17093        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17094                && li.mOnDragListener.onDrag(this, event)) {
17095            return true;
17096        }
17097        return onDragEvent(event);
17098    }
17099
17100    boolean canAcceptDrag() {
17101        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17102    }
17103
17104    /**
17105     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17106     * it is ever exposed at all.
17107     * @hide
17108     */
17109    public void onCloseSystemDialogs(String reason) {
17110    }
17111
17112    /**
17113     * Given a Drawable whose bounds have been set to draw into this view,
17114     * update a Region being computed for
17115     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17116     * that any non-transparent parts of the Drawable are removed from the
17117     * given transparent region.
17118     *
17119     * @param dr The Drawable whose transparency is to be applied to the region.
17120     * @param region A Region holding the current transparency information,
17121     * where any parts of the region that are set are considered to be
17122     * transparent.  On return, this region will be modified to have the
17123     * transparency information reduced by the corresponding parts of the
17124     * Drawable that are not transparent.
17125     * {@hide}
17126     */
17127    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17128        if (DBG) {
17129            Log.i("View", "Getting transparent region for: " + this);
17130        }
17131        final Region r = dr.getTransparentRegion();
17132        final Rect db = dr.getBounds();
17133        final AttachInfo attachInfo = mAttachInfo;
17134        if (r != null && attachInfo != null) {
17135            final int w = getRight()-getLeft();
17136            final int h = getBottom()-getTop();
17137            if (db.left > 0) {
17138                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17139                r.op(0, 0, db.left, h, Region.Op.UNION);
17140            }
17141            if (db.right < w) {
17142                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17143                r.op(db.right, 0, w, h, Region.Op.UNION);
17144            }
17145            if (db.top > 0) {
17146                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17147                r.op(0, 0, w, db.top, Region.Op.UNION);
17148            }
17149            if (db.bottom < h) {
17150                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17151                r.op(0, db.bottom, w, h, Region.Op.UNION);
17152            }
17153            final int[] location = attachInfo.mTransparentLocation;
17154            getLocationInWindow(location);
17155            r.translate(location[0], location[1]);
17156            region.op(r, Region.Op.INTERSECT);
17157        } else {
17158            region.op(db, Region.Op.DIFFERENCE);
17159        }
17160    }
17161
17162    private void checkForLongClick(int delayOffset) {
17163        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17164            mHasPerformedLongPress = false;
17165
17166            if (mPendingCheckForLongPress == null) {
17167                mPendingCheckForLongPress = new CheckForLongPress();
17168            }
17169            mPendingCheckForLongPress.rememberWindowAttachCount();
17170            postDelayed(mPendingCheckForLongPress,
17171                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17172        }
17173    }
17174
17175    /**
17176     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17177     * LayoutInflater} class, which provides a full range of options for view inflation.
17178     *
17179     * @param context The Context object for your activity or application.
17180     * @param resource The resource ID to inflate
17181     * @param root A view group that will be the parent.  Used to properly inflate the
17182     * layout_* parameters.
17183     * @see LayoutInflater
17184     */
17185    public static View inflate(Context context, int resource, ViewGroup root) {
17186        LayoutInflater factory = LayoutInflater.from(context);
17187        return factory.inflate(resource, root);
17188    }
17189
17190    /**
17191     * Scroll the view with standard behavior for scrolling beyond the normal
17192     * content boundaries. Views that call this method should override
17193     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17194     * results of an over-scroll operation.
17195     *
17196     * Views can use this method to handle any touch or fling-based scrolling.
17197     *
17198     * @param deltaX Change in X in pixels
17199     * @param deltaY Change in Y in pixels
17200     * @param scrollX Current X scroll value in pixels before applying deltaX
17201     * @param scrollY Current Y scroll value in pixels before applying deltaY
17202     * @param scrollRangeX Maximum content scroll range along the X axis
17203     * @param scrollRangeY Maximum content scroll range along the Y axis
17204     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17205     *          along the X axis.
17206     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17207     *          along the Y axis.
17208     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17209     * @return true if scrolling was clamped to an over-scroll boundary along either
17210     *          axis, false otherwise.
17211     */
17212    @SuppressWarnings({"UnusedParameters"})
17213    protected boolean overScrollBy(int deltaX, int deltaY,
17214            int scrollX, int scrollY,
17215            int scrollRangeX, int scrollRangeY,
17216            int maxOverScrollX, int maxOverScrollY,
17217            boolean isTouchEvent) {
17218        final int overScrollMode = mOverScrollMode;
17219        final boolean canScrollHorizontal =
17220                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17221        final boolean canScrollVertical =
17222                computeVerticalScrollRange() > computeVerticalScrollExtent();
17223        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17224                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17225        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17226                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17227
17228        int newScrollX = scrollX + deltaX;
17229        if (!overScrollHorizontal) {
17230            maxOverScrollX = 0;
17231        }
17232
17233        int newScrollY = scrollY + deltaY;
17234        if (!overScrollVertical) {
17235            maxOverScrollY = 0;
17236        }
17237
17238        // Clamp values if at the limits and record
17239        final int left = -maxOverScrollX;
17240        final int right = maxOverScrollX + scrollRangeX;
17241        final int top = -maxOverScrollY;
17242        final int bottom = maxOverScrollY + scrollRangeY;
17243
17244        boolean clampedX = false;
17245        if (newScrollX > right) {
17246            newScrollX = right;
17247            clampedX = true;
17248        } else if (newScrollX < left) {
17249            newScrollX = left;
17250            clampedX = true;
17251        }
17252
17253        boolean clampedY = false;
17254        if (newScrollY > bottom) {
17255            newScrollY = bottom;
17256            clampedY = true;
17257        } else if (newScrollY < top) {
17258            newScrollY = top;
17259            clampedY = true;
17260        }
17261
17262        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17263
17264        return clampedX || clampedY;
17265    }
17266
17267    /**
17268     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17269     * respond to the results of an over-scroll operation.
17270     *
17271     * @param scrollX New X scroll value in pixels
17272     * @param scrollY New Y scroll value in pixels
17273     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17274     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17275     */
17276    protected void onOverScrolled(int scrollX, int scrollY,
17277            boolean clampedX, boolean clampedY) {
17278        // Intentionally empty.
17279    }
17280
17281    /**
17282     * Returns the over-scroll mode for this view. The result will be
17283     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17284     * (allow over-scrolling only if the view content is larger than the container),
17285     * or {@link #OVER_SCROLL_NEVER}.
17286     *
17287     * @return This view's over-scroll mode.
17288     */
17289    public int getOverScrollMode() {
17290        return mOverScrollMode;
17291    }
17292
17293    /**
17294     * Set the over-scroll mode for this view. Valid over-scroll modes are
17295     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17296     * (allow over-scrolling only if the view content is larger than the container),
17297     * or {@link #OVER_SCROLL_NEVER}.
17298     *
17299     * Setting the over-scroll mode of a view will have an effect only if the
17300     * view is capable of scrolling.
17301     *
17302     * @param overScrollMode The new over-scroll mode for this view.
17303     */
17304    public void setOverScrollMode(int overScrollMode) {
17305        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17306                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17307                overScrollMode != OVER_SCROLL_NEVER) {
17308            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17309        }
17310        mOverScrollMode = overScrollMode;
17311    }
17312
17313    /**
17314     * Gets a scale factor that determines the distance the view should scroll
17315     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17316     * @return The vertical scroll scale factor.
17317     * @hide
17318     */
17319    protected float getVerticalScrollFactor() {
17320        if (mVerticalScrollFactor == 0) {
17321            TypedValue outValue = new TypedValue();
17322            if (!mContext.getTheme().resolveAttribute(
17323                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17324                throw new IllegalStateException(
17325                        "Expected theme to define listPreferredItemHeight.");
17326            }
17327            mVerticalScrollFactor = outValue.getDimension(
17328                    mContext.getResources().getDisplayMetrics());
17329        }
17330        return mVerticalScrollFactor;
17331    }
17332
17333    /**
17334     * Gets a scale factor that determines the distance the view should scroll
17335     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17336     * @return The horizontal scroll scale factor.
17337     * @hide
17338     */
17339    protected float getHorizontalScrollFactor() {
17340        // TODO: Should use something else.
17341        return getVerticalScrollFactor();
17342    }
17343
17344    /**
17345     * Return the value specifying the text direction or policy that was set with
17346     * {@link #setTextDirection(int)}.
17347     *
17348     * @return the defined text direction. It can be one of:
17349     *
17350     * {@link #TEXT_DIRECTION_INHERIT},
17351     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17352     * {@link #TEXT_DIRECTION_ANY_RTL},
17353     * {@link #TEXT_DIRECTION_LTR},
17354     * {@link #TEXT_DIRECTION_RTL},
17355     * {@link #TEXT_DIRECTION_LOCALE}
17356     *
17357     * @attr ref android.R.styleable#View_textDirection
17358     *
17359     * @hide
17360     */
17361    @ViewDebug.ExportedProperty(category = "text", mapping = {
17362            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17363            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17364            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17365            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17366            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17367            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17368    })
17369    public int getRawTextDirection() {
17370        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17371    }
17372
17373    /**
17374     * Set the text direction.
17375     *
17376     * @param textDirection the direction to set. Should be one of:
17377     *
17378     * {@link #TEXT_DIRECTION_INHERIT},
17379     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17380     * {@link #TEXT_DIRECTION_ANY_RTL},
17381     * {@link #TEXT_DIRECTION_LTR},
17382     * {@link #TEXT_DIRECTION_RTL},
17383     * {@link #TEXT_DIRECTION_LOCALE}
17384     *
17385     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17386     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17387     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17388     *
17389     * @attr ref android.R.styleable#View_textDirection
17390     */
17391    public void setTextDirection(int textDirection) {
17392        if (getRawTextDirection() != textDirection) {
17393            // Reset the current text direction and the resolved one
17394            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17395            resetResolvedTextDirection();
17396            // Set the new text direction
17397            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17398            // Do resolution
17399            resolveTextDirection();
17400            // Notify change
17401            onRtlPropertiesChanged(getLayoutDirection());
17402            // Refresh
17403            requestLayout();
17404            invalidate(true);
17405        }
17406    }
17407
17408    /**
17409     * Return the resolved text direction.
17410     *
17411     * @return the resolved text direction. Returns one of:
17412     *
17413     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17414     * {@link #TEXT_DIRECTION_ANY_RTL},
17415     * {@link #TEXT_DIRECTION_LTR},
17416     * {@link #TEXT_DIRECTION_RTL},
17417     * {@link #TEXT_DIRECTION_LOCALE}
17418     *
17419     * @attr ref android.R.styleable#View_textDirection
17420     */
17421    @ViewDebug.ExportedProperty(category = "text", mapping = {
17422            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17423            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17424            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17425            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17426            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17427            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17428    })
17429    public int getTextDirection() {
17430        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17431    }
17432
17433    /**
17434     * Resolve the text direction.
17435     *
17436     * @return true if resolution has been done, false otherwise.
17437     *
17438     * @hide
17439     */
17440    public boolean resolveTextDirection() {
17441        // Reset any previous text direction resolution
17442        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17443
17444        if (hasRtlSupport()) {
17445            // Set resolved text direction flag depending on text direction flag
17446            final int textDirection = getRawTextDirection();
17447            switch(textDirection) {
17448                case TEXT_DIRECTION_INHERIT:
17449                    if (!canResolveTextDirection()) {
17450                        // We cannot do the resolution if there is no parent, so use the default one
17451                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17452                        // Resolution will need to happen again later
17453                        return false;
17454                    }
17455
17456                    // Parent has not yet resolved, so we still return the default
17457                    try {
17458                        if (!mParent.isTextDirectionResolved()) {
17459                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17460                            // Resolution will need to happen again later
17461                            return false;
17462                        }
17463                    } catch (AbstractMethodError e) {
17464                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17465                                " does not fully implement ViewParent", e);
17466                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17467                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17468                        return true;
17469                    }
17470
17471                    // Set current resolved direction to the same value as the parent's one
17472                    int parentResolvedDirection;
17473                    try {
17474                        parentResolvedDirection = mParent.getTextDirection();
17475                    } catch (AbstractMethodError e) {
17476                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17477                                " does not fully implement ViewParent", e);
17478                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17479                    }
17480                    switch (parentResolvedDirection) {
17481                        case TEXT_DIRECTION_FIRST_STRONG:
17482                        case TEXT_DIRECTION_ANY_RTL:
17483                        case TEXT_DIRECTION_LTR:
17484                        case TEXT_DIRECTION_RTL:
17485                        case TEXT_DIRECTION_LOCALE:
17486                            mPrivateFlags2 |=
17487                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17488                            break;
17489                        default:
17490                            // Default resolved direction is "first strong" heuristic
17491                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17492                    }
17493                    break;
17494                case TEXT_DIRECTION_FIRST_STRONG:
17495                case TEXT_DIRECTION_ANY_RTL:
17496                case TEXT_DIRECTION_LTR:
17497                case TEXT_DIRECTION_RTL:
17498                case TEXT_DIRECTION_LOCALE:
17499                    // Resolved direction is the same as text direction
17500                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17501                    break;
17502                default:
17503                    // Default resolved direction is "first strong" heuristic
17504                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17505            }
17506        } else {
17507            // Default resolved direction is "first strong" heuristic
17508            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17509        }
17510
17511        // Set to resolved
17512        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17513        return true;
17514    }
17515
17516    /**
17517     * Check if text direction resolution can be done.
17518     *
17519     * @return true if text direction resolution can be done otherwise return false.
17520     */
17521    public boolean canResolveTextDirection() {
17522        switch (getRawTextDirection()) {
17523            case TEXT_DIRECTION_INHERIT:
17524                if (mParent != null) {
17525                    try {
17526                        return mParent.canResolveTextDirection();
17527                    } catch (AbstractMethodError e) {
17528                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17529                                " does not fully implement ViewParent", e);
17530                    }
17531                }
17532                return false;
17533
17534            default:
17535                return true;
17536        }
17537    }
17538
17539    /**
17540     * Reset resolved text direction. Text direction will be resolved during a call to
17541     * {@link #onMeasure(int, int)}.
17542     *
17543     * @hide
17544     */
17545    public void resetResolvedTextDirection() {
17546        // Reset any previous text direction resolution
17547        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17548        // Set to default value
17549        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17550    }
17551
17552    /**
17553     * @return true if text direction is inherited.
17554     *
17555     * @hide
17556     */
17557    public boolean isTextDirectionInherited() {
17558        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17559    }
17560
17561    /**
17562     * @return true if text direction is resolved.
17563     */
17564    public boolean isTextDirectionResolved() {
17565        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17566    }
17567
17568    /**
17569     * Return the value specifying the text alignment or policy that was set with
17570     * {@link #setTextAlignment(int)}.
17571     *
17572     * @return the defined text alignment. It can be one of:
17573     *
17574     * {@link #TEXT_ALIGNMENT_INHERIT},
17575     * {@link #TEXT_ALIGNMENT_GRAVITY},
17576     * {@link #TEXT_ALIGNMENT_CENTER},
17577     * {@link #TEXT_ALIGNMENT_TEXT_START},
17578     * {@link #TEXT_ALIGNMENT_TEXT_END},
17579     * {@link #TEXT_ALIGNMENT_VIEW_START},
17580     * {@link #TEXT_ALIGNMENT_VIEW_END}
17581     *
17582     * @attr ref android.R.styleable#View_textAlignment
17583     *
17584     * @hide
17585     */
17586    @ViewDebug.ExportedProperty(category = "text", mapping = {
17587            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17588            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17589            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17590            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17591            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17592            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17593            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17594    })
17595    public int getRawTextAlignment() {
17596        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17597    }
17598
17599    /**
17600     * Set the text alignment.
17601     *
17602     * @param textAlignment The text alignment to set. Should be one of
17603     *
17604     * {@link #TEXT_ALIGNMENT_INHERIT},
17605     * {@link #TEXT_ALIGNMENT_GRAVITY},
17606     * {@link #TEXT_ALIGNMENT_CENTER},
17607     * {@link #TEXT_ALIGNMENT_TEXT_START},
17608     * {@link #TEXT_ALIGNMENT_TEXT_END},
17609     * {@link #TEXT_ALIGNMENT_VIEW_START},
17610     * {@link #TEXT_ALIGNMENT_VIEW_END}
17611     *
17612     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17613     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17614     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17615     *
17616     * @attr ref android.R.styleable#View_textAlignment
17617     */
17618    public void setTextAlignment(int textAlignment) {
17619        if (textAlignment != getRawTextAlignment()) {
17620            // Reset the current and resolved text alignment
17621            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17622            resetResolvedTextAlignment();
17623            // Set the new text alignment
17624            mPrivateFlags2 |=
17625                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17626            // Do resolution
17627            resolveTextAlignment();
17628            // Notify change
17629            onRtlPropertiesChanged(getLayoutDirection());
17630            // Refresh
17631            requestLayout();
17632            invalidate(true);
17633        }
17634    }
17635
17636    /**
17637     * Return the resolved text alignment.
17638     *
17639     * @return the resolved text alignment. Returns one of:
17640     *
17641     * {@link #TEXT_ALIGNMENT_GRAVITY},
17642     * {@link #TEXT_ALIGNMENT_CENTER},
17643     * {@link #TEXT_ALIGNMENT_TEXT_START},
17644     * {@link #TEXT_ALIGNMENT_TEXT_END},
17645     * {@link #TEXT_ALIGNMENT_VIEW_START},
17646     * {@link #TEXT_ALIGNMENT_VIEW_END}
17647     *
17648     * @attr ref android.R.styleable#View_textAlignment
17649     */
17650    @ViewDebug.ExportedProperty(category = "text", mapping = {
17651            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17652            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17653            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17654            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17655            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17656            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17657            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17658    })
17659    public int getTextAlignment() {
17660        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17661                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17662    }
17663
17664    /**
17665     * Resolve the text alignment.
17666     *
17667     * @return true if resolution has been done, false otherwise.
17668     *
17669     * @hide
17670     */
17671    public boolean resolveTextAlignment() {
17672        // Reset any previous text alignment resolution
17673        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17674
17675        if (hasRtlSupport()) {
17676            // Set resolved text alignment flag depending on text alignment flag
17677            final int textAlignment = getRawTextAlignment();
17678            switch (textAlignment) {
17679                case TEXT_ALIGNMENT_INHERIT:
17680                    // Check if we can resolve the text alignment
17681                    if (!canResolveTextAlignment()) {
17682                        // We cannot do the resolution if there is no parent so use the default
17683                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17684                        // Resolution will need to happen again later
17685                        return false;
17686                    }
17687
17688                    // Parent has not yet resolved, so we still return the default
17689                    try {
17690                        if (!mParent.isTextAlignmentResolved()) {
17691                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17692                            // Resolution will need to happen again later
17693                            return false;
17694                        }
17695                    } catch (AbstractMethodError e) {
17696                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17697                                " does not fully implement ViewParent", e);
17698                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17699                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17700                        return true;
17701                    }
17702
17703                    int parentResolvedTextAlignment;
17704                    try {
17705                        parentResolvedTextAlignment = mParent.getTextAlignment();
17706                    } catch (AbstractMethodError e) {
17707                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17708                                " does not fully implement ViewParent", e);
17709                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17710                    }
17711                    switch (parentResolvedTextAlignment) {
17712                        case TEXT_ALIGNMENT_GRAVITY:
17713                        case TEXT_ALIGNMENT_TEXT_START:
17714                        case TEXT_ALIGNMENT_TEXT_END:
17715                        case TEXT_ALIGNMENT_CENTER:
17716                        case TEXT_ALIGNMENT_VIEW_START:
17717                        case TEXT_ALIGNMENT_VIEW_END:
17718                            // Resolved text alignment is the same as the parent resolved
17719                            // text alignment
17720                            mPrivateFlags2 |=
17721                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17722                            break;
17723                        default:
17724                            // Use default resolved text alignment
17725                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17726                    }
17727                    break;
17728                case TEXT_ALIGNMENT_GRAVITY:
17729                case TEXT_ALIGNMENT_TEXT_START:
17730                case TEXT_ALIGNMENT_TEXT_END:
17731                case TEXT_ALIGNMENT_CENTER:
17732                case TEXT_ALIGNMENT_VIEW_START:
17733                case TEXT_ALIGNMENT_VIEW_END:
17734                    // Resolved text alignment is the same as text alignment
17735                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17736                    break;
17737                default:
17738                    // Use default resolved text alignment
17739                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17740            }
17741        } else {
17742            // Use default resolved text alignment
17743            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17744        }
17745
17746        // Set the resolved
17747        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17748        return true;
17749    }
17750
17751    /**
17752     * Check if text alignment resolution can be done.
17753     *
17754     * @return true if text alignment resolution can be done otherwise return false.
17755     */
17756    public boolean canResolveTextAlignment() {
17757        switch (getRawTextAlignment()) {
17758            case TEXT_DIRECTION_INHERIT:
17759                if (mParent != null) {
17760                    try {
17761                        return mParent.canResolveTextAlignment();
17762                    } catch (AbstractMethodError e) {
17763                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17764                                " does not fully implement ViewParent", e);
17765                    }
17766                }
17767                return false;
17768
17769            default:
17770                return true;
17771        }
17772    }
17773
17774    /**
17775     * Reset resolved text alignment. Text alignment will be resolved during a call to
17776     * {@link #onMeasure(int, int)}.
17777     *
17778     * @hide
17779     */
17780    public void resetResolvedTextAlignment() {
17781        // Reset any previous text alignment resolution
17782        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17783        // Set to default
17784        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17785    }
17786
17787    /**
17788     * @return true if text alignment is inherited.
17789     *
17790     * @hide
17791     */
17792    public boolean isTextAlignmentInherited() {
17793        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17794    }
17795
17796    /**
17797     * @return true if text alignment is resolved.
17798     */
17799    public boolean isTextAlignmentResolved() {
17800        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17801    }
17802
17803    /**
17804     * Generate a value suitable for use in {@link #setId(int)}.
17805     * This value will not collide with ID values generated at build time by aapt for R.id.
17806     *
17807     * @return a generated ID value
17808     */
17809    public static int generateViewId() {
17810        for (;;) {
17811            final int result = sNextGeneratedId.get();
17812            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17813            int newValue = result + 1;
17814            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17815            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17816                return result;
17817            }
17818        }
17819    }
17820
17821    //
17822    // Properties
17823    //
17824    /**
17825     * A Property wrapper around the <code>alpha</code> functionality handled by the
17826     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17827     */
17828    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17829        @Override
17830        public void setValue(View object, float value) {
17831            object.setAlpha(value);
17832        }
17833
17834        @Override
17835        public Float get(View object) {
17836            return object.getAlpha();
17837        }
17838    };
17839
17840    /**
17841     * A Property wrapper around the <code>translationX</code> functionality handled by the
17842     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17843     */
17844    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17845        @Override
17846        public void setValue(View object, float value) {
17847            object.setTranslationX(value);
17848        }
17849
17850                @Override
17851        public Float get(View object) {
17852            return object.getTranslationX();
17853        }
17854    };
17855
17856    /**
17857     * A Property wrapper around the <code>translationY</code> functionality handled by the
17858     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17859     */
17860    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17861        @Override
17862        public void setValue(View object, float value) {
17863            object.setTranslationY(value);
17864        }
17865
17866        @Override
17867        public Float get(View object) {
17868            return object.getTranslationY();
17869        }
17870    };
17871
17872    /**
17873     * A Property wrapper around the <code>x</code> functionality handled by the
17874     * {@link View#setX(float)} and {@link View#getX()} methods.
17875     */
17876    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17877        @Override
17878        public void setValue(View object, float value) {
17879            object.setX(value);
17880        }
17881
17882        @Override
17883        public Float get(View object) {
17884            return object.getX();
17885        }
17886    };
17887
17888    /**
17889     * A Property wrapper around the <code>y</code> functionality handled by the
17890     * {@link View#setY(float)} and {@link View#getY()} methods.
17891     */
17892    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17893        @Override
17894        public void setValue(View object, float value) {
17895            object.setY(value);
17896        }
17897
17898        @Override
17899        public Float get(View object) {
17900            return object.getY();
17901        }
17902    };
17903
17904    /**
17905     * A Property wrapper around the <code>rotation</code> functionality handled by the
17906     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17907     */
17908    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17909        @Override
17910        public void setValue(View object, float value) {
17911            object.setRotation(value);
17912        }
17913
17914        @Override
17915        public Float get(View object) {
17916            return object.getRotation();
17917        }
17918    };
17919
17920    /**
17921     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17922     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17923     */
17924    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17925        @Override
17926        public void setValue(View object, float value) {
17927            object.setRotationX(value);
17928        }
17929
17930        @Override
17931        public Float get(View object) {
17932            return object.getRotationX();
17933        }
17934    };
17935
17936    /**
17937     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17938     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17939     */
17940    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17941        @Override
17942        public void setValue(View object, float value) {
17943            object.setRotationY(value);
17944        }
17945
17946        @Override
17947        public Float get(View object) {
17948            return object.getRotationY();
17949        }
17950    };
17951
17952    /**
17953     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17954     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17955     */
17956    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17957        @Override
17958        public void setValue(View object, float value) {
17959            object.setScaleX(value);
17960        }
17961
17962        @Override
17963        public Float get(View object) {
17964            return object.getScaleX();
17965        }
17966    };
17967
17968    /**
17969     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17970     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17971     */
17972    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17973        @Override
17974        public void setValue(View object, float value) {
17975            object.setScaleY(value);
17976        }
17977
17978        @Override
17979        public Float get(View object) {
17980            return object.getScaleY();
17981        }
17982    };
17983
17984    /**
17985     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17986     * Each MeasureSpec represents a requirement for either the width or the height.
17987     * A MeasureSpec is comprised of a size and a mode. There are three possible
17988     * modes:
17989     * <dl>
17990     * <dt>UNSPECIFIED</dt>
17991     * <dd>
17992     * The parent has not imposed any constraint on the child. It can be whatever size
17993     * it wants.
17994     * </dd>
17995     *
17996     * <dt>EXACTLY</dt>
17997     * <dd>
17998     * The parent has determined an exact size for the child. The child is going to be
17999     * given those bounds regardless of how big it wants to be.
18000     * </dd>
18001     *
18002     * <dt>AT_MOST</dt>
18003     * <dd>
18004     * The child can be as large as it wants up to the specified size.
18005     * </dd>
18006     * </dl>
18007     *
18008     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18009     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18010     */
18011    public static class MeasureSpec {
18012        private static final int MODE_SHIFT = 30;
18013        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18014
18015        /**
18016         * Measure specification mode: The parent has not imposed any constraint
18017         * on the child. It can be whatever size it wants.
18018         */
18019        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18020
18021        /**
18022         * Measure specification mode: The parent has determined an exact size
18023         * for the child. The child is going to be given those bounds regardless
18024         * of how big it wants to be.
18025         */
18026        public static final int EXACTLY     = 1 << MODE_SHIFT;
18027
18028        /**
18029         * Measure specification mode: The child can be as large as it wants up
18030         * to the specified size.
18031         */
18032        public static final int AT_MOST     = 2 << MODE_SHIFT;
18033
18034        /**
18035         * Creates a measure specification based on the supplied size and mode.
18036         *
18037         * The mode must always be one of the following:
18038         * <ul>
18039         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18040         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18041         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18042         * </ul>
18043         *
18044         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18045         * implementation was such that the order of arguments did not matter
18046         * and overflow in either value could impact the resulting MeasureSpec.
18047         * {@link android.widget.RelativeLayout} was affected by this bug.
18048         * Apps targeting API levels greater than 17 will get the fixed, more strict
18049         * behavior.</p>
18050         *
18051         * @param size the size of the measure specification
18052         * @param mode the mode of the measure specification
18053         * @return the measure specification based on size and mode
18054         */
18055        public static int makeMeasureSpec(int size, int mode) {
18056            if (sUseBrokenMakeMeasureSpec) {
18057                return size + mode;
18058            } else {
18059                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18060            }
18061        }
18062
18063        /**
18064         * Extracts the mode from the supplied measure specification.
18065         *
18066         * @param measureSpec the measure specification to extract the mode from
18067         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18068         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18069         *         {@link android.view.View.MeasureSpec#EXACTLY}
18070         */
18071        public static int getMode(int measureSpec) {
18072            return (measureSpec & MODE_MASK);
18073        }
18074
18075        /**
18076         * Extracts the size from the supplied measure specification.
18077         *
18078         * @param measureSpec the measure specification to extract the size from
18079         * @return the size in pixels defined in the supplied measure specification
18080         */
18081        public static int getSize(int measureSpec) {
18082            return (measureSpec & ~MODE_MASK);
18083        }
18084
18085        static int adjust(int measureSpec, int delta) {
18086            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18087        }
18088
18089        /**
18090         * Returns a String representation of the specified measure
18091         * specification.
18092         *
18093         * @param measureSpec the measure specification to convert to a String
18094         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18095         */
18096        public static String toString(int measureSpec) {
18097            int mode = getMode(measureSpec);
18098            int size = getSize(measureSpec);
18099
18100            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18101
18102            if (mode == UNSPECIFIED)
18103                sb.append("UNSPECIFIED ");
18104            else if (mode == EXACTLY)
18105                sb.append("EXACTLY ");
18106            else if (mode == AT_MOST)
18107                sb.append("AT_MOST ");
18108            else
18109                sb.append(mode).append(" ");
18110
18111            sb.append(size);
18112            return sb.toString();
18113        }
18114    }
18115
18116    class CheckForLongPress implements Runnable {
18117
18118        private int mOriginalWindowAttachCount;
18119
18120        public void run() {
18121            if (isPressed() && (mParent != null)
18122                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18123                if (performLongClick()) {
18124                    mHasPerformedLongPress = true;
18125                }
18126            }
18127        }
18128
18129        public void rememberWindowAttachCount() {
18130            mOriginalWindowAttachCount = mWindowAttachCount;
18131        }
18132    }
18133
18134    private final class CheckForTap implements Runnable {
18135        public void run() {
18136            mPrivateFlags &= ~PFLAG_PREPRESSED;
18137            setPressed(true);
18138            checkForLongClick(ViewConfiguration.getTapTimeout());
18139        }
18140    }
18141
18142    private final class PerformClick implements Runnable {
18143        public void run() {
18144            performClick();
18145        }
18146    }
18147
18148    /** @hide */
18149    public void hackTurnOffWindowResizeAnim(boolean off) {
18150        mAttachInfo.mTurnOffWindowResizeAnim = off;
18151    }
18152
18153    /**
18154     * This method returns a ViewPropertyAnimator object, which can be used to animate
18155     * specific properties on this View.
18156     *
18157     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18158     */
18159    public ViewPropertyAnimator animate() {
18160        if (mAnimator == null) {
18161            mAnimator = new ViewPropertyAnimator(this);
18162        }
18163        return mAnimator;
18164    }
18165
18166    /**
18167     * Interface definition for a callback to be invoked when a hardware key event is
18168     * dispatched to this view. The callback will be invoked before the key event is
18169     * given to the view. This is only useful for hardware keyboards; a software input
18170     * method has no obligation to trigger this listener.
18171     */
18172    public interface OnKeyListener {
18173        /**
18174         * Called when a hardware key is dispatched to a view. This allows listeners to
18175         * get a chance to respond before the target view.
18176         * <p>Key presses in software keyboards will generally NOT trigger this method,
18177         * although some may elect to do so in some situations. Do not assume a
18178         * software input method has to be key-based; even if it is, it may use key presses
18179         * in a different way than you expect, so there is no way to reliably catch soft
18180         * input key presses.
18181         *
18182         * @param v The view the key has been dispatched to.
18183         * @param keyCode The code for the physical key that was pressed
18184         * @param event The KeyEvent object containing full information about
18185         *        the event.
18186         * @return True if the listener has consumed the event, false otherwise.
18187         */
18188        boolean onKey(View v, int keyCode, KeyEvent event);
18189    }
18190
18191    /**
18192     * Interface definition for a callback to be invoked when a touch event is
18193     * dispatched to this view. The callback will be invoked before the touch
18194     * event is given to the view.
18195     */
18196    public interface OnTouchListener {
18197        /**
18198         * Called when a touch event is dispatched to a view. This allows listeners to
18199         * get a chance to respond before the target view.
18200         *
18201         * @param v The view the touch event has been dispatched to.
18202         * @param event The MotionEvent object containing full information about
18203         *        the event.
18204         * @return True if the listener has consumed the event, false otherwise.
18205         */
18206        boolean onTouch(View v, MotionEvent event);
18207    }
18208
18209    /**
18210     * Interface definition for a callback to be invoked when a hover event is
18211     * dispatched to this view. The callback will be invoked before the hover
18212     * event is given to the view.
18213     */
18214    public interface OnHoverListener {
18215        /**
18216         * Called when a hover event is dispatched to a view. This allows listeners to
18217         * get a chance to respond before the target view.
18218         *
18219         * @param v The view the hover event has been dispatched to.
18220         * @param event The MotionEvent object containing full information about
18221         *        the event.
18222         * @return True if the listener has consumed the event, false otherwise.
18223         */
18224        boolean onHover(View v, MotionEvent event);
18225    }
18226
18227    /**
18228     * Interface definition for a callback to be invoked when a generic motion event is
18229     * dispatched to this view. The callback will be invoked before the generic motion
18230     * event is given to the view.
18231     */
18232    public interface OnGenericMotionListener {
18233        /**
18234         * Called when a generic motion event is dispatched to a view. This allows listeners to
18235         * get a chance to respond before the target view.
18236         *
18237         * @param v The view the generic motion event has been dispatched to.
18238         * @param event The MotionEvent object containing full information about
18239         *        the event.
18240         * @return True if the listener has consumed the event, false otherwise.
18241         */
18242        boolean onGenericMotion(View v, MotionEvent event);
18243    }
18244
18245    /**
18246     * Interface definition for a callback to be invoked when a view has been clicked and held.
18247     */
18248    public interface OnLongClickListener {
18249        /**
18250         * Called when a view has been clicked and held.
18251         *
18252         * @param v The view that was clicked and held.
18253         *
18254         * @return true if the callback consumed the long click, false otherwise.
18255         */
18256        boolean onLongClick(View v);
18257    }
18258
18259    /**
18260     * Interface definition for a callback to be invoked when a drag is being dispatched
18261     * to this view.  The callback will be invoked before the hosting view's own
18262     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18263     * onDrag(event) behavior, it should return 'false' from this callback.
18264     *
18265     * <div class="special reference">
18266     * <h3>Developer Guides</h3>
18267     * <p>For a guide to implementing drag and drop features, read the
18268     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18269     * </div>
18270     */
18271    public interface OnDragListener {
18272        /**
18273         * Called when a drag event is dispatched to a view. This allows listeners
18274         * to get a chance to override base View behavior.
18275         *
18276         * @param v The View that received the drag event.
18277         * @param event The {@link android.view.DragEvent} object for the drag event.
18278         * @return {@code true} if the drag event was handled successfully, or {@code false}
18279         * if the drag event was not handled. Note that {@code false} will trigger the View
18280         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18281         */
18282        boolean onDrag(View v, DragEvent event);
18283    }
18284
18285    /**
18286     * Interface definition for a callback to be invoked when the focus state of
18287     * a view changed.
18288     */
18289    public interface OnFocusChangeListener {
18290        /**
18291         * Called when the focus state of a view has changed.
18292         *
18293         * @param v The view whose state has changed.
18294         * @param hasFocus The new focus state of v.
18295         */
18296        void onFocusChange(View v, boolean hasFocus);
18297    }
18298
18299    /**
18300     * Interface definition for a callback to be invoked when a view is clicked.
18301     */
18302    public interface OnClickListener {
18303        /**
18304         * Called when a view has been clicked.
18305         *
18306         * @param v The view that was clicked.
18307         */
18308        void onClick(View v);
18309    }
18310
18311    /**
18312     * Interface definition for a callback to be invoked when the context menu
18313     * for this view is being built.
18314     */
18315    public interface OnCreateContextMenuListener {
18316        /**
18317         * Called when the context menu for this view is being built. It is not
18318         * safe to hold onto the menu after this method returns.
18319         *
18320         * @param menu The context menu that is being built
18321         * @param v The view for which the context menu is being built
18322         * @param menuInfo Extra information about the item for which the
18323         *            context menu should be shown. This information will vary
18324         *            depending on the class of v.
18325         */
18326        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18327    }
18328
18329    /**
18330     * Interface definition for a callback to be invoked when the status bar changes
18331     * visibility.  This reports <strong>global</strong> changes to the system UI
18332     * state, not what the application is requesting.
18333     *
18334     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18335     */
18336    public interface OnSystemUiVisibilityChangeListener {
18337        /**
18338         * Called when the status bar changes visibility because of a call to
18339         * {@link View#setSystemUiVisibility(int)}.
18340         *
18341         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18342         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18343         * This tells you the <strong>global</strong> state of these UI visibility
18344         * flags, not what your app is currently applying.
18345         */
18346        public void onSystemUiVisibilityChange(int visibility);
18347    }
18348
18349    /**
18350     * Interface definition for a callback to be invoked when this view is attached
18351     * or detached from its window.
18352     */
18353    public interface OnAttachStateChangeListener {
18354        /**
18355         * Called when the view is attached to a window.
18356         * @param v The view that was attached
18357         */
18358        public void onViewAttachedToWindow(View v);
18359        /**
18360         * Called when the view is detached from a window.
18361         * @param v The view that was detached
18362         */
18363        public void onViewDetachedFromWindow(View v);
18364    }
18365
18366    private final class UnsetPressedState implements Runnable {
18367        public void run() {
18368            setPressed(false);
18369        }
18370    }
18371
18372    /**
18373     * Base class for derived classes that want to save and restore their own
18374     * state in {@link android.view.View#onSaveInstanceState()}.
18375     */
18376    public static class BaseSavedState extends AbsSavedState {
18377        /**
18378         * Constructor used when reading from a parcel. Reads the state of the superclass.
18379         *
18380         * @param source
18381         */
18382        public BaseSavedState(Parcel source) {
18383            super(source);
18384        }
18385
18386        /**
18387         * Constructor called by derived classes when creating their SavedState objects
18388         *
18389         * @param superState The state of the superclass of this view
18390         */
18391        public BaseSavedState(Parcelable superState) {
18392            super(superState);
18393        }
18394
18395        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18396                new Parcelable.Creator<BaseSavedState>() {
18397            public BaseSavedState createFromParcel(Parcel in) {
18398                return new BaseSavedState(in);
18399            }
18400
18401            public BaseSavedState[] newArray(int size) {
18402                return new BaseSavedState[size];
18403            }
18404        };
18405    }
18406
18407    /**
18408     * A set of information given to a view when it is attached to its parent
18409     * window.
18410     */
18411    static class AttachInfo {
18412        interface Callbacks {
18413            void playSoundEffect(int effectId);
18414            boolean performHapticFeedback(int effectId, boolean always);
18415        }
18416
18417        /**
18418         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18419         * to a Handler. This class contains the target (View) to invalidate and
18420         * the coordinates of the dirty rectangle.
18421         *
18422         * For performance purposes, this class also implements a pool of up to
18423         * POOL_LIMIT objects that get reused. This reduces memory allocations
18424         * whenever possible.
18425         */
18426        static class InvalidateInfo {
18427            private static final int POOL_LIMIT = 10;
18428
18429            private static final SynchronizedPool<InvalidateInfo> sPool =
18430                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18431
18432            View target;
18433
18434            int left;
18435            int top;
18436            int right;
18437            int bottom;
18438
18439            public static InvalidateInfo obtain() {
18440                InvalidateInfo instance = sPool.acquire();
18441                return (instance != null) ? instance : new InvalidateInfo();
18442            }
18443
18444            public void recycle() {
18445                target = null;
18446                sPool.release(this);
18447            }
18448        }
18449
18450        final IWindowSession mSession;
18451
18452        final IWindow mWindow;
18453
18454        final IBinder mWindowToken;
18455
18456        final Display mDisplay;
18457
18458        final Callbacks mRootCallbacks;
18459
18460        HardwareCanvas mHardwareCanvas;
18461
18462        IWindowId mIWindowId;
18463        WindowId mWindowId;
18464
18465        /**
18466         * The top view of the hierarchy.
18467         */
18468        View mRootView;
18469
18470        IBinder mPanelParentWindowToken;
18471        Surface mSurface;
18472
18473        boolean mHardwareAccelerated;
18474        boolean mHardwareAccelerationRequested;
18475        HardwareRenderer mHardwareRenderer;
18476
18477        boolean mScreenOn;
18478
18479        /**
18480         * Scale factor used by the compatibility mode
18481         */
18482        float mApplicationScale;
18483
18484        /**
18485         * Indicates whether the application is in compatibility mode
18486         */
18487        boolean mScalingRequired;
18488
18489        /**
18490         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18491         */
18492        boolean mTurnOffWindowResizeAnim;
18493
18494        /**
18495         * Left position of this view's window
18496         */
18497        int mWindowLeft;
18498
18499        /**
18500         * Top position of this view's window
18501         */
18502        int mWindowTop;
18503
18504        /**
18505         * Indicates whether views need to use 32-bit drawing caches
18506         */
18507        boolean mUse32BitDrawingCache;
18508
18509        /**
18510         * For windows that are full-screen but using insets to layout inside
18511         * of the screen areas, these are the current insets to appear inside
18512         * the overscan area of the display.
18513         */
18514        final Rect mOverscanInsets = new Rect();
18515
18516        /**
18517         * For windows that are full-screen but using insets to layout inside
18518         * of the screen decorations, these are the current insets for the
18519         * content of the window.
18520         */
18521        final Rect mContentInsets = new Rect();
18522
18523        /**
18524         * For windows that are full-screen but using insets to layout inside
18525         * of the screen decorations, these are the current insets for the
18526         * actual visible parts of the window.
18527         */
18528        final Rect mVisibleInsets = new Rect();
18529
18530        /**
18531         * The internal insets given by this window.  This value is
18532         * supplied by the client (through
18533         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18534         * be given to the window manager when changed to be used in laying
18535         * out windows behind it.
18536         */
18537        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18538                = new ViewTreeObserver.InternalInsetsInfo();
18539
18540        /**
18541         * All views in the window's hierarchy that serve as scroll containers,
18542         * used to determine if the window can be resized or must be panned
18543         * to adjust for a soft input area.
18544         */
18545        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18546
18547        final KeyEvent.DispatcherState mKeyDispatchState
18548                = new KeyEvent.DispatcherState();
18549
18550        /**
18551         * Indicates whether the view's window currently has the focus.
18552         */
18553        boolean mHasWindowFocus;
18554
18555        /**
18556         * The current visibility of the window.
18557         */
18558        int mWindowVisibility;
18559
18560        /**
18561         * Indicates the time at which drawing started to occur.
18562         */
18563        long mDrawingTime;
18564
18565        /**
18566         * Indicates whether or not ignoring the DIRTY_MASK flags.
18567         */
18568        boolean mIgnoreDirtyState;
18569
18570        /**
18571         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18572         * to avoid clearing that flag prematurely.
18573         */
18574        boolean mSetIgnoreDirtyState = false;
18575
18576        /**
18577         * Indicates whether the view's window is currently in touch mode.
18578         */
18579        boolean mInTouchMode;
18580
18581        /**
18582         * Indicates that ViewAncestor should trigger a global layout change
18583         * the next time it performs a traversal
18584         */
18585        boolean mRecomputeGlobalAttributes;
18586
18587        /**
18588         * Always report new attributes at next traversal.
18589         */
18590        boolean mForceReportNewAttributes;
18591
18592        /**
18593         * Set during a traveral if any views want to keep the screen on.
18594         */
18595        boolean mKeepScreenOn;
18596
18597        /**
18598         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18599         */
18600        int mSystemUiVisibility;
18601
18602        /**
18603         * Hack to force certain system UI visibility flags to be cleared.
18604         */
18605        int mDisabledSystemUiVisibility;
18606
18607        /**
18608         * Last global system UI visibility reported by the window manager.
18609         */
18610        int mGlobalSystemUiVisibility;
18611
18612        /**
18613         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18614         * attached.
18615         */
18616        boolean mHasSystemUiListeners;
18617
18618        /**
18619         * Set if the window has requested to extend into the overscan region
18620         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18621         */
18622        boolean mOverscanRequested;
18623
18624        /**
18625         * Set if the visibility of any views has changed.
18626         */
18627        boolean mViewVisibilityChanged;
18628
18629        /**
18630         * Set to true if a view has been scrolled.
18631         */
18632        boolean mViewScrollChanged;
18633
18634        /**
18635         * Global to the view hierarchy used as a temporary for dealing with
18636         * x/y points in the transparent region computations.
18637         */
18638        final int[] mTransparentLocation = new int[2];
18639
18640        /**
18641         * Global to the view hierarchy used as a temporary for dealing with
18642         * x/y points in the ViewGroup.invalidateChild implementation.
18643         */
18644        final int[] mInvalidateChildLocation = new int[2];
18645
18646
18647        /**
18648         * Global to the view hierarchy used as a temporary for dealing with
18649         * x/y location when view is transformed.
18650         */
18651        final float[] mTmpTransformLocation = new float[2];
18652
18653        /**
18654         * The view tree observer used to dispatch global events like
18655         * layout, pre-draw, touch mode change, etc.
18656         */
18657        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18658
18659        /**
18660         * A Canvas used by the view hierarchy to perform bitmap caching.
18661         */
18662        Canvas mCanvas;
18663
18664        /**
18665         * The view root impl.
18666         */
18667        final ViewRootImpl mViewRootImpl;
18668
18669        /**
18670         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18671         * handler can be used to pump events in the UI events queue.
18672         */
18673        final Handler mHandler;
18674
18675        /**
18676         * Temporary for use in computing invalidate rectangles while
18677         * calling up the hierarchy.
18678         */
18679        final Rect mTmpInvalRect = new Rect();
18680
18681        /**
18682         * Temporary for use in computing hit areas with transformed views
18683         */
18684        final RectF mTmpTransformRect = new RectF();
18685
18686        /**
18687         * Temporary for use in transforming invalidation rect
18688         */
18689        final Matrix mTmpMatrix = new Matrix();
18690
18691        /**
18692         * Temporary for use in transforming invalidation rect
18693         */
18694        final Transformation mTmpTransformation = new Transformation();
18695
18696        /**
18697         * Temporary list for use in collecting focusable descendents of a view.
18698         */
18699        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18700
18701        /**
18702         * The id of the window for accessibility purposes.
18703         */
18704        int mAccessibilityWindowId = View.NO_ID;
18705
18706        /**
18707         * Flags related to accessibility processing.
18708         *
18709         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18710         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18711         */
18712        int mAccessibilityFetchFlags;
18713
18714        /**
18715         * The drawable for highlighting accessibility focus.
18716         */
18717        Drawable mAccessibilityFocusDrawable;
18718
18719        /**
18720         * Show where the margins, bounds and layout bounds are for each view.
18721         */
18722        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18723
18724        /**
18725         * Point used to compute visible regions.
18726         */
18727        final Point mPoint = new Point();
18728
18729        /**
18730         * Used to track which View originated a requestLayout() call, used when
18731         * requestLayout() is called during layout.
18732         */
18733        View mViewRequestingLayout;
18734
18735        /**
18736         * Creates a new set of attachment information with the specified
18737         * events handler and thread.
18738         *
18739         * @param handler the events handler the view must use
18740         */
18741        AttachInfo(IWindowSession session, IWindow window, Display display,
18742                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18743            mSession = session;
18744            mWindow = window;
18745            mWindowToken = window.asBinder();
18746            mDisplay = display;
18747            mViewRootImpl = viewRootImpl;
18748            mHandler = handler;
18749            mRootCallbacks = effectPlayer;
18750        }
18751    }
18752
18753    /**
18754     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18755     * is supported. This avoids keeping too many unused fields in most
18756     * instances of View.</p>
18757     */
18758    private static class ScrollabilityCache implements Runnable {
18759
18760        /**
18761         * Scrollbars are not visible
18762         */
18763        public static final int OFF = 0;
18764
18765        /**
18766         * Scrollbars are visible
18767         */
18768        public static final int ON = 1;
18769
18770        /**
18771         * Scrollbars are fading away
18772         */
18773        public static final int FADING = 2;
18774
18775        public boolean fadeScrollBars;
18776
18777        public int fadingEdgeLength;
18778        public int scrollBarDefaultDelayBeforeFade;
18779        public int scrollBarFadeDuration;
18780
18781        public int scrollBarSize;
18782        public ScrollBarDrawable scrollBar;
18783        public float[] interpolatorValues;
18784        public View host;
18785
18786        public final Paint paint;
18787        public final Matrix matrix;
18788        public Shader shader;
18789
18790        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18791
18792        private static final float[] OPAQUE = { 255 };
18793        private static final float[] TRANSPARENT = { 0.0f };
18794
18795        /**
18796         * When fading should start. This time moves into the future every time
18797         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18798         */
18799        public long fadeStartTime;
18800
18801
18802        /**
18803         * The current state of the scrollbars: ON, OFF, or FADING
18804         */
18805        public int state = OFF;
18806
18807        private int mLastColor;
18808
18809        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18810            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18811            scrollBarSize = configuration.getScaledScrollBarSize();
18812            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18813            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18814
18815            paint = new Paint();
18816            matrix = new Matrix();
18817            // use use a height of 1, and then wack the matrix each time we
18818            // actually use it.
18819            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18820            paint.setShader(shader);
18821            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18822
18823            this.host = host;
18824        }
18825
18826        public void setFadeColor(int color) {
18827            if (color != mLastColor) {
18828                mLastColor = color;
18829
18830                if (color != 0) {
18831                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18832                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18833                    paint.setShader(shader);
18834                    // Restore the default transfer mode (src_over)
18835                    paint.setXfermode(null);
18836                } else {
18837                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18838                    paint.setShader(shader);
18839                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18840                }
18841            }
18842        }
18843
18844        public void run() {
18845            long now = AnimationUtils.currentAnimationTimeMillis();
18846            if (now >= fadeStartTime) {
18847
18848                // the animation fades the scrollbars out by changing
18849                // the opacity (alpha) from fully opaque to fully
18850                // transparent
18851                int nextFrame = (int) now;
18852                int framesCount = 0;
18853
18854                Interpolator interpolator = scrollBarInterpolator;
18855
18856                // Start opaque
18857                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18858
18859                // End transparent
18860                nextFrame += scrollBarFadeDuration;
18861                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18862
18863                state = FADING;
18864
18865                // Kick off the fade animation
18866                host.invalidate(true);
18867            }
18868        }
18869    }
18870
18871    /**
18872     * Resuable callback for sending
18873     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18874     */
18875    private class SendViewScrolledAccessibilityEvent implements Runnable {
18876        public volatile boolean mIsPending;
18877
18878        public void run() {
18879            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18880            mIsPending = false;
18881        }
18882    }
18883
18884    /**
18885     * <p>
18886     * This class represents a delegate that can be registered in a {@link View}
18887     * to enhance accessibility support via composition rather via inheritance.
18888     * It is specifically targeted to widget developers that extend basic View
18889     * classes i.e. classes in package android.view, that would like their
18890     * applications to be backwards compatible.
18891     * </p>
18892     * <div class="special reference">
18893     * <h3>Developer Guides</h3>
18894     * <p>For more information about making applications accessible, read the
18895     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18896     * developer guide.</p>
18897     * </div>
18898     * <p>
18899     * A scenario in which a developer would like to use an accessibility delegate
18900     * is overriding a method introduced in a later API version then the minimal API
18901     * version supported by the application. For example, the method
18902     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18903     * in API version 4 when the accessibility APIs were first introduced. If a
18904     * developer would like his application to run on API version 4 devices (assuming
18905     * all other APIs used by the application are version 4 or lower) and take advantage
18906     * of this method, instead of overriding the method which would break the application's
18907     * backwards compatibility, he can override the corresponding method in this
18908     * delegate and register the delegate in the target View if the API version of
18909     * the system is high enough i.e. the API version is same or higher to the API
18910     * version that introduced
18911     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18912     * </p>
18913     * <p>
18914     * Here is an example implementation:
18915     * </p>
18916     * <code><pre><p>
18917     * if (Build.VERSION.SDK_INT >= 14) {
18918     *     // If the API version is equal of higher than the version in
18919     *     // which onInitializeAccessibilityNodeInfo was introduced we
18920     *     // register a delegate with a customized implementation.
18921     *     View view = findViewById(R.id.view_id);
18922     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18923     *         public void onInitializeAccessibilityNodeInfo(View host,
18924     *                 AccessibilityNodeInfo info) {
18925     *             // Let the default implementation populate the info.
18926     *             super.onInitializeAccessibilityNodeInfo(host, info);
18927     *             // Set some other information.
18928     *             info.setEnabled(host.isEnabled());
18929     *         }
18930     *     });
18931     * }
18932     * </code></pre></p>
18933     * <p>
18934     * This delegate contains methods that correspond to the accessibility methods
18935     * in View. If a delegate has been specified the implementation in View hands
18936     * off handling to the corresponding method in this delegate. The default
18937     * implementation the delegate methods behaves exactly as the corresponding
18938     * method in View for the case of no accessibility delegate been set. Hence,
18939     * to customize the behavior of a View method, clients can override only the
18940     * corresponding delegate method without altering the behavior of the rest
18941     * accessibility related methods of the host view.
18942     * </p>
18943     */
18944    public static class AccessibilityDelegate {
18945
18946        /**
18947         * Sends an accessibility event of the given type. If accessibility is not
18948         * enabled this method has no effect.
18949         * <p>
18950         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18951         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18952         * been set.
18953         * </p>
18954         *
18955         * @param host The View hosting the delegate.
18956         * @param eventType The type of the event to send.
18957         *
18958         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18959         */
18960        public void sendAccessibilityEvent(View host, int eventType) {
18961            host.sendAccessibilityEventInternal(eventType);
18962        }
18963
18964        /**
18965         * Performs the specified accessibility action on the view. For
18966         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18967         * <p>
18968         * The default implementation behaves as
18969         * {@link View#performAccessibilityAction(int, Bundle)
18970         *  View#performAccessibilityAction(int, Bundle)} for the case of
18971         *  no accessibility delegate been set.
18972         * </p>
18973         *
18974         * @param action The action to perform.
18975         * @return Whether the action was performed.
18976         *
18977         * @see View#performAccessibilityAction(int, Bundle)
18978         *      View#performAccessibilityAction(int, Bundle)
18979         */
18980        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18981            return host.performAccessibilityActionInternal(action, args);
18982        }
18983
18984        /**
18985         * Sends an accessibility event. This method behaves exactly as
18986         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18987         * empty {@link AccessibilityEvent} and does not perform a check whether
18988         * accessibility is enabled.
18989         * <p>
18990         * The default implementation behaves as
18991         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18992         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18993         * the case of no accessibility delegate been set.
18994         * </p>
18995         *
18996         * @param host The View hosting the delegate.
18997         * @param event The event to send.
18998         *
18999         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19000         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19001         */
19002        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19003            host.sendAccessibilityEventUncheckedInternal(event);
19004        }
19005
19006        /**
19007         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19008         * to its children for adding their text content to the event.
19009         * <p>
19010         * The default implementation behaves as
19011         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19012         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19013         * the case of no accessibility delegate been set.
19014         * </p>
19015         *
19016         * @param host The View hosting the delegate.
19017         * @param event The event.
19018         * @return True if the event population was completed.
19019         *
19020         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19021         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19022         */
19023        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19024            return host.dispatchPopulateAccessibilityEventInternal(event);
19025        }
19026
19027        /**
19028         * Gives a chance to the host View to populate the accessibility event with its
19029         * text content.
19030         * <p>
19031         * The default implementation behaves as
19032         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19033         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19034         * the case of no accessibility delegate been set.
19035         * </p>
19036         *
19037         * @param host The View hosting the delegate.
19038         * @param event The accessibility event which to populate.
19039         *
19040         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19041         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19042         */
19043        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19044            host.onPopulateAccessibilityEventInternal(event);
19045        }
19046
19047        /**
19048         * Initializes an {@link AccessibilityEvent} with information about the
19049         * the host View which is the event source.
19050         * <p>
19051         * The default implementation behaves as
19052         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19053         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19054         * the case of no accessibility delegate been set.
19055         * </p>
19056         *
19057         * @param host The View hosting the delegate.
19058         * @param event The event to initialize.
19059         *
19060         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19061         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19062         */
19063        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19064            host.onInitializeAccessibilityEventInternal(event);
19065        }
19066
19067        /**
19068         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19069         * <p>
19070         * The default implementation behaves as
19071         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19072         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19073         * the case of no accessibility delegate been set.
19074         * </p>
19075         *
19076         * @param host The View hosting the delegate.
19077         * @param info The instance to initialize.
19078         *
19079         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19080         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19081         */
19082        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19083            host.onInitializeAccessibilityNodeInfoInternal(info);
19084        }
19085
19086        /**
19087         * Called when a child of the host View has requested sending an
19088         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19089         * to augment the event.
19090         * <p>
19091         * The default implementation behaves as
19092         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19093         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19094         * the case of no accessibility delegate been set.
19095         * </p>
19096         *
19097         * @param host The View hosting the delegate.
19098         * @param child The child which requests sending the event.
19099         * @param event The event to be sent.
19100         * @return True if the event should be sent
19101         *
19102         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19103         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19104         */
19105        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19106                AccessibilityEvent event) {
19107            return host.onRequestSendAccessibilityEventInternal(child, event);
19108        }
19109
19110        /**
19111         * Gets the provider for managing a virtual view hierarchy rooted at this View
19112         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19113         * that explore the window content.
19114         * <p>
19115         * The default implementation behaves as
19116         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19117         * the case of no accessibility delegate been set.
19118         * </p>
19119         *
19120         * @return The provider.
19121         *
19122         * @see AccessibilityNodeProvider
19123         */
19124        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19125            return null;
19126        }
19127
19128        /**
19129         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19130         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19131         * This method is responsible for obtaining an accessibility node info from a
19132         * pool of reusable instances and calling
19133         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19134         * view to initialize the former.
19135         * <p>
19136         * <strong>Note:</strong> The client is responsible for recycling the obtained
19137         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19138         * creation.
19139         * </p>
19140         * <p>
19141         * The default implementation behaves as
19142         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19143         * the case of no accessibility delegate been set.
19144         * </p>
19145         * @return A populated {@link AccessibilityNodeInfo}.
19146         *
19147         * @see AccessibilityNodeInfo
19148         *
19149         * @hide
19150         */
19151        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19152            return host.createAccessibilityNodeInfoInternal();
19153        }
19154    }
19155
19156    private class MatchIdPredicate implements Predicate<View> {
19157        public int mId;
19158
19159        @Override
19160        public boolean apply(View view) {
19161            return (view.mID == mId);
19162        }
19163    }
19164
19165    private class MatchLabelForPredicate implements Predicate<View> {
19166        private int mLabeledId;
19167
19168        @Override
19169        public boolean apply(View view) {
19170            return (view.mLabelForId == mLabeledId);
19171        }
19172    }
19173
19174    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19175        private boolean mPosted;
19176        private long mLastEventTimeMillis;
19177
19178        public void run() {
19179            mPosted = false;
19180            mLastEventTimeMillis = SystemClock.uptimeMillis();
19181            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19182                AccessibilityEvent event = AccessibilityEvent.obtain();
19183                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19184                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
19185                sendAccessibilityEventUnchecked(event);
19186            }
19187        }
19188
19189        public void runOrPost() {
19190            if (mPosted) {
19191                return;
19192            }
19193            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19194            final long minEventIntevalMillis =
19195                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19196            if (timeSinceLastMillis >= minEventIntevalMillis) {
19197                removeCallbacks(this);
19198                run();
19199            } else {
19200                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19201                mPosted = true;
19202            }
19203        }
19204    }
19205
19206    /**
19207     * Dump all private flags in readable format, useful for documentation and
19208     * sanity checking.
19209     */
19210    private static void dumpFlags() {
19211        final HashMap<String, String> found = Maps.newHashMap();
19212        try {
19213            for (Field field : View.class.getDeclaredFields()) {
19214                final int modifiers = field.getModifiers();
19215                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19216                    if (field.getType().equals(int.class)) {
19217                        final int value = field.getInt(null);
19218                        dumpFlag(found, field.getName(), value);
19219                    } else if (field.getType().equals(int[].class)) {
19220                        final int[] values = (int[]) field.get(null);
19221                        for (int i = 0; i < values.length; i++) {
19222                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19223                        }
19224                    }
19225                }
19226            }
19227        } catch (IllegalAccessException e) {
19228            throw new RuntimeException(e);
19229        }
19230
19231        final ArrayList<String> keys = Lists.newArrayList();
19232        keys.addAll(found.keySet());
19233        Collections.sort(keys);
19234        for (String key : keys) {
19235            Log.d(VIEW_LOG_TAG, found.get(key));
19236        }
19237    }
19238
19239    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19240        // Sort flags by prefix, then by bits, always keeping unique keys
19241        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19242        final int prefix = name.indexOf('_');
19243        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19244        final String output = bits + " " + name;
19245        found.put(key, output);
19246    }
19247}
19248